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 |
|---|---|---|---|---|---|
Does the savetopdf method in aspose.slides still not allow saving ppt to pdf in Porait mode?
Dear tlangan,
<?xml:namespace prefix = o
Thanks for considering Aspose.Slides.
Presentation.SaveToPdf actually takes its page size from its source PowerPoint file. If it is in portrait, it will save it in portrait mode.
Currently, it is not saving it correctly, if the slide size is other than normal size and we are fixing it.
when will this be fixed?
We are developing new pdf renderer for Aspose.Slides without intermediate SVG convertation.
Page mode should work right in this new version. The estimated release date is September. | https://forum.aspose.com/t/savetopdf-in-portrait-mode/101307 | CC-MAIN-2022-33 | refinedweb | 106 | 62.14 |
« Return to documentation listing
MPI_Type_dup - Duplicates a data type with associated key values.
#include <mpi.h>
int MPI_Type_dup(MPI_Datatype type, MPI_Datatype *newtype)
INCLUDE 'mpif.h'
MPI_TYPE_DUP(TYPE, NEWTYPE, IERROR)
INTEGER TYPE, NEWTYPE, IERROR
#include <mpi.h>
MPI::Datatype MPI::Datatype::Dup() const
type Data type (handle).
newtype Copy of type (handle).
IERROR Fortran only: Error status (integer).
MPI_Type_dup is a type constructor that duplicates the existing type
with associated key values. For each key value, the respective copy
callback function determines the attribute value associated with this
key in the new communicator. One particular action that a copy callback
may take is to delete the attribute from the new data type. Returns in
newtype a new data type with exactly the same properties as type, as
well as any copied cached information. The new data type has identical
upper bound and lower bound and yields the same net result when fully
decoded with the functions described in Section 8.6 of the MPI-2 stan-
dard. newtype has the same committed state as the old. | http://icl.cs.utk.edu/open-mpi/doc/v1.2/man3/MPI_Type_dup.3.php | CC-MAIN-2016-26 | refinedweb | 175 | 50.12 |
Feature #9548open
Module curry
Added by Anonymous about 7 years ago. Updated about 7 years ago.
Description
I would like to beg for either
Module#curry method with syntax
module Foo curry( :sym2, :sym1, 0 => 42, 1 => 43, 3 => 44, foo: "bar" ) end
or
curry directive similar to the existing
alias directive
module Foo curry sym2 sym1( 42, 43, *, 44, foo: "bar ) end
Example usage:
module MyMath def power a, b a ** b end curry square power( *, 2 ) curry square_root power( *, 0.5 ) curry cube( *, 3 ) curry pow2 power( 2, * ) curry pow_e power( Math::E, * ) curry pow10 power( 10, * ) end
Updated by srawlins (Sam Rawlins) about 7 years ago
Firstly, Proc has a #curry, though not as flexible as you would like:
Secondly, to implement such flexibility is not too hard in pure Ruby. Here is an implementation of arbitrary currying for Procs:
def curry(prc, *args) Proc.new { |*remaining| prc.call(*args.map { |arg| arg || remaining.shift }) } end
and one for Methods:
def curry_m(m, n, *args) define_method(m, curry(method(n), *args)) end
Thusly, you can do:
power = ->(a,b){ "#{a}**#{b} is #{a**b}" } square = curry power, nil, 2 pow2 = curry power, 2, nil puts "3 squared is #{square.call(3)}" #=> 3 squared is 9 puts "two to the 3 is #{pow2.call(3)}" #=> two to the 3 is 8 list = ->(a,b,c,d) { "#{a}, #{b}, #{c}, #{d}" } static_a = curry list, :hi, nil, nil, nil static_b_c = curry list, nil, :sam, :adam, nil puts "static_a: #{static_a.call(:b, :c, :d)}" #=> static_a: hi, b, c, d puts "static_b_c: #{static_b_c.call(:a, :d)}" #=> static_b,c: a, sam, adam, d def power_m(a,b); a**b; end curry_m(:square_m, :power_m, nil, 2) curry_m(:pow2_m, :power_m, 2, nil) puts "3 squared is #{square_m(3)}" #=> 3 squared is 9 puts "two to the 3 is #{pow2_m(3)}" #=> two to the 3 is 8
gist:
Updated by mame (Yusuke Endoh) about 7 years ago
That is not "currying", but "partial application."
--
Yusuke Endoh mame@tsg.ne.jp
Updated by Anonymous about 7 years ago
mame (Yusuke Endoh), I don't quite get these nuances between "currying" and "partial application". I could try and
learn them, but my approach is different here. I do not want to learn. I want to be stubborn like
Amazonians when first confronted with Bible. Pragmatically, partial application is all I need. And
since it's long, so let the word be
curry. Whole point of using this hunger evoking word (Anglosaxon
surnames notwithstanding) is because it's short and unique, like "quark". And, a shameful secret,
my mnemonic for curry is, oh, it's like with food, there is something (mutton, chicken, veggies...),
and you can add different types of curry to it. And
#curry decides about curry, and I then decide
about something. So it's "partial application". I suggest to cannibalize the theorists and settle
for this naïve interpretation of
curry. (Just in case that I am really missing something here,
the theorists can go find a different word for that something after we steal
curry from them and
use it for "partial application".)
@sam, see #7939 for my take on what
Proc#curry should do. Your example implementation
precludes the use of falsey values for currying (in the naïve sense of the word).
Updated by Anonymous about 7 years ago
I have just learned about the existence of
Method#parameters method, which would enable to write near-perfect
Module#curry without asking for core-level syntax on par with
alias. The supporting facts for this feature request are thus slightly weaker than I thought when writing it.
Updated by matz (Yukihiro Matsumoto) about 7 years ago
- Status changed from Open to Feedback
I don't think the term 'curry' is a proper name for the sought behavior.
In addition, I cannot think of a use-case for the feature.
Any concrete example?
Matz.
Updated by Anonymous about 7 years ago
Indeed, there is much less use for currying than for chaining in the functional world. (In #9552, I now prefer
#chain to
#map!.) Yet there is already
Proc#curry in Ruby (whose present behavior is horrible, imo), therefore it is fair to consider giving the same convenience to the functions employed in modules as methods.
As for the name, in this particular case, I would still argue in favor of
Module#curry. My list of imagined possibilities:
#curry --- 5
#partial_application --- 1 --- too long
#partial_apply --- 1
#partially_apply --- 0
#partial --- 2
#filter --- 0 --- means too many things
Should it be decided that this feature on
Module is desirable at all, I would like to pretty please you to give your nod to misuse the word
curry for it.
As for the usecases, again, there are less of them than for chaining, but let me make up some real-world example which would be of use in my code:
class Simulation def initialize( initial_marking: {}, marking_clamps: {}, method: :pseudo_euler, step: 1.0, target_time: 60.0, sampling: 5.0, guarded: false ) # object initialization end # class assets end class Net # class assets def simulation **named_args Simulation.new **named_args end curry euler simulation( method: :euler, ** ) curry pseudo_euler simulation( method: :pseudo_euler, ** ) curry runge_kutta simulation( method: :runge_kutta, ** ) curry gillespie simulation( method: :gillespie, step: nil, ** ) # Gillespie method computes its own step length. end net = Net.new # And then, instead of sim = net.simulation( method: :gillespie, initial_marking: { A: 100, B: 200 }, # etc. ) # one could just type sim = net.gillespie( initial_marking: { A: 100, B: 200 }, # etc. )
So my mnemonic is, here we have simulation with curry named "euler", and then another one with curry named "runge_kutta", etc. (Note that I have simplified the above example, in the real code,
Net instances own each a parametrized subclass of
Simulation.)
Updated by Anonymous about 7 years ago
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/9548?tab=notes | CC-MAIN-2021-17 | refinedweb | 962 | 61.97 |
Adding some shortcut sugar to your day-by-day programming in Elm on Atom.
Disclaimer: this package is in early stage. I'm not covering all the possible scenarios, but the most ones used by me. Feel free to PR!
apm install elm-snippets
Write the prefixes below and press the
Tab key and you're good to go.
module <name> (..) where
import <name>
import <name> as <alias>
import <name> exposing (..)
type alias <name> =<something>
String
Signal
Signal.map <(a -> b)> <Signal a>
Signal.mailbox ""
case <something> of<Condition> -><action>
Good catch. Let us know what about this package looks wrong to you, and we'll investigate right away. | https://api.atom.io/packages/elm-snippets | CC-MAIN-2020-50 | refinedweb | 109 | 78.25 |
1. Get a copy of OpenOCD with the TI-ICDI driver enabled
On openSUSE Linux the OpenOCD package already has this driver enabled. However, the OpenOCD binary currently shipped with ChibiStudio does not have the TI-ICDI driver enabled. It can be enabled by passing --enable-ti-icdi to the configure script used when building with MSYS2.
I've attached a 7-zip archive file with a copy of OpenOCD that's been compiled with the TI-ICDI driver enabled, plus an extra patch that fixes potential problems with the WinUSB driver (link to the patch in the enclosed README.txt file). All you have to do is replace the contents of C:\ChibiStudio\tools\openocd with the contents of the openocd folder in the archive file. If you already have TI's Code Composer Studio installed, you're probably good to go. Otherwise, you can use Zadig to install the WinUSB driver so that OpenOCD will work.
2. Set up paths correctly in the Makefile
After importing a Tiva demo project in ChibiStudio, open the Makefile and make sure the variables CHIBIOS and CHIBIOSCONTRIB are set correctly. For example, the lines in my Makefile look like this (your setup may look different):
Code: Select all
# Imported source files and paths
CHIBIOS = ../../../../chibios203
CHIBIOS_CONTRIB = $(CHIBIOS)/../ChibiOS-Contrib
3. Remove inclusion of nonexistant halconf_community.h
Open the file halconf.h and remove the line that reads
Code: Select all
#include "halconf_community.h"
4. Configure ChibiStudio (Eclipse) to be compatible with OpenOCD
A somewhat-recent change in the Eclipse's GDB Hardware Debugging plug-in will throw an error and stop your code from launching (more information here). To fix this, just click the drop-down menu button attached to the "Debug" icon at the top of the screen, click on Debug Configurations..., and then open "RT-TM4C12xx-LAUNCHPAD (OpenOCD, Flash and Run)" from the list on the left-hand side of the dialog. Then, go to the Startup tab and deselect the boxes Reset and delay and Halt. Click on the Apply button and you're good to go.
Good luck & hope this is helpful. | https://forum.chibios.org/viewtopic.php?f=29&p=38773&sid=7c886f42d86585b626cbefbfb62c6782 | CC-MAIN-2021-43 | refinedweb | 354 | 62.48 |
Theme based on the Twitter Bootstrap 3 CSS framework. More...
#include <Wt/WBootstrap3Theme.h>
Theme based on the Twitter Bootstrap 3 CSS framework.
This theme implements support for building a Wt web application that uses Twitter Bootstrap as a theme for its (layout and) styling. The theme comes with CSS from Bootstrap Wt distribution, but since the Twitter Bootstrap CSS API is a popular API for custom themes, you can easily replace the CSS with custom-built CSS (by reimplementing styleSheets()).
Although this theme facilitates the use of Twitter Bootstrap with Wt, it is still important to understand how Bootstrap expects markup to be, especially related to layout using its grid system, for which we refer to the official bootstrap documentation, see.
Returns whether responsive features are enabled.
Enables form-control on all applicable form widgets.
By applying "form-control" on form widgets, they will become block level elements that take the size of the parent (which is in bootstrap's philosphy a grid layout).
The default value is
true.
Enables responsive features.
Responsive features can be enabled only at application startup. For bootstrap 3, you need to use the progressive bootstrap feature of Wt (see 10.2 General application settings (wt_config.xml)) as it requires setting HTML meta flags.
Responsive features are disabled by default.. | https://webtoolkit.eu/wt/doc/reference/html/classWt_1_1WBootstrap3Theme.html | CC-MAIN-2022-05 | refinedweb | 216 | 57.37 |
A few weeks ago, someone I know was trying to solve a somewhat interesting problem (interesting to me, at least). They wanted to know all the words that could be formed from all the combinations of the last 4 digits of a phone number. We were assuming each digit has 3 letters (no Q or Z). So, for each combination of 2..9 choose 4 digits (0 and 1 don't have any letters on them), there are combinations of 0..2 choose 4 letters. These assumptions do not hold perfectly, as some phones have Q and Z on them, and the situation is likely much more complex outside of the US, but they will work for the sake of the problem.
The naive solution is to nest as many for loops as required. This is a pain, and hardly elegant. I wanted to come up with something better. I searched around the Monastery, looked at a few combinations generators (it seems everyone has their own favorite method), and came up with something that fits nicely in my brainspace.
The most elegant algorithms count up in base N (where N is the length of the list), and map that representation back to the original list. Since counting in base N wasn't the natural way for me to think about the problem, I decided to count in decimal and then convert it to the base N. TMTOWTDI, and all that. :-)
I had been writing all this code in Perl, but the Other Guy was using Python. I thought, "hey, I'm flexible. I'll just port it from Perl to Python." It was a surprisingly simple port. Perhaps the code doesn't look perfectly Pythonic, but it works as advertised, and made me happy.
Then I started playing with Pugs, and thought, "hey, this is fun. I'll port it from Perl to Perl 6." Of course, in doing this I uncovered a few bugs in Pugs, and ended up writing and committing failing test cases for those bugs (which were apparently fixed 2 days later, as the tests stopped failing and the code started working as advertised).
At the end of this adventure, I decided to share it with the Monks. So here it is, and for those who are dying to see, here's all three versions of the code. First, the original Perl 5 implementation:
#!/usr/bin/perl
use strict;
use warnings;_combinations;
my $letterchooser = choose([0 .. 2], 4);
while (my $letters = $letterchooser->()) {
push @letter_combinations, $letters;
}
my $digitchooser = choose([2 .. 9], 4);
while (my $digits = $digitchooser->()) {
for my $letters (@letter_combinations) {
my @digits = split //, $digits;
my @letters = split //, $letters;
my @word = map { $digit_letters{$digits[$_]}[$letters[$_]] }
0 .. $#digits;
print "$digits: ", @word, "\n";
}
}
sub basen {
my ($base, $num) = @_;
my $q = int($num / $base);
my $r = $num % $base;
return $r if $q == 0;
return basen($base, $q), $r;
}
sub choose {
my ($list, $number) = @_;
my $listcount = @$list;
my $combcount = @$list**$number;
my $curr = 0;
sub {
return if $curr >= $combcount;
my @choice = basen($listcount, $curr++);
unshift @choice, 0 while @choice < $number;
return join "", map $list->[$_], @choice;
}
}
[download]
Next, Python (the output is slightly different, but I didn't feel like wrangling it into shape):
#!/usr/bin/python
def basen (base, num):
q = num / base
r = num % base
if q == 0:
return [r]
else:
return basen(base, q) + [r]
def choose (list, number):
iterations = len(list)**number
for i in range(0, iterations):
choice = basen(len(list), i)
while len(choice) < number:
choice.insert(0, 0)
yield [ list[x] for x in choice ]
digit_letters = { 2: [ 'a', 'b', 'c' ],
3: [ 'd', 'e', 'f' ],
4: [ 'g', 'h', 'i' ],
5: [ 'j', 'k', 'l' ],
6: [ 'm', 'n', 'o' ],
7: [ 'p', 'r', 's' ],
8: [ 't', 'u', 'v' ],
9: [ 'w', 'x', 'y' ] }
letter_choices = []
for letters in choose([0,1,2], 4):
letter_choices.append(letters)
for digits in choose(range(2,10), 4):
for letters in letter_choices:
word = []
for i in range(0, len(digits)):
digit = digits[i]
letter_i = letters[i]
letter = digit_letters[digit][letter_i]
word.append(letter)
print digits, ":", ''.join(word)
[download]
And finally, the Perl 6 version:
#!/usr/bin/pugschoices;
my $letters;
my $letterchooser = choose([0 .. 2], 4);
while $letters = $letterchooser() {
push @letterchoices, $letters;
}
my $digits;
my $digitchooser = choose([2 .. 9], 4);
while $digits = $digitchooser() {
my $letters;
for @letterchoices -> $letters {
my @digits = split '', $digits;
my @letters = split '', $letters;
my @word;
for zip(@digits, @letters) -> $digit, $letter {
push @word, %digit_letters{$digit}[$letter];
}
say "$digits: ", @word;
}
}
sub basen ($base, $num) {
my $q = int($num / $base);
my $r = $num % $base;
return $r if $q == 0;
return basen($base, $q), $r;
}
sub choose ($list, $number) {
my $iterations = $list.elems ** $number;
my $current = 0;
return sub {
return if $current >= $iterations;
my @choice = basen($list.elems, $current++);
unshift @choice, 0 while @choice.elems < $number;
return @choice.map({$list[$_]}).join("");
};
}
[download]
There are a few things I got from this experience. One thing that really stood out was how similar the solutions were. Perhaps that was a consequence of the fact that I was porting the code from one to the next, rather than starting all over, but it shows that the facilities used here are available in all three languages.
Also, I noticed that the Perl 6 version still looks very much like Perl. It just has a few changes, and I think they're for the better. Perhaps the code can be further P6-ified, but I don't think it will change the feel dramatically. I think the new language is going to turn out nicely.
Finally, I noticed that -- yes, I am master of the obvious -- Python does some things that Perl doesn't. The big standout here was the built in iterator support. Just using yield instead of return is a heck of a lot easier than using an anonymous sub that wrangles closures to provide the same functionality. It's not that I would want to get rid of the closures (which seems to be the Python solution), but I'd like to have the easier technique too. Perl is supposed to be the language that steals good ideas from all around, isn't it?
As always, code criticisms/critiques welcome. I'm especially interested in any Perl6ish improvements to that version. I tend to limit myself to things that work in Pugs, but I know there are others here who don't have that limitation, and I'd love to hear from them. Anything else welcome, too! Please reply early and often. :-)
#!perl
use strict;
use warnings;
my %digit_letters = (
2 => '{a,b,c}',
3 => '{d,e,f}',
4 => '{g,h,i}',
5 => '{j,k,l}',
6 => '{m,n,o}',
7 => '{p,r,s}',
8 => '{t,u,v}',
9 => '{w,x,y}',
);
my $digit_glob = '{' . join(',', 2..9) . '}';
my $limit = 20;
for my $num (glob($digit_glob x 4)) {
(my $word_glob = $num) =~ s/(.)/$digit_letters{$1}/g;
for my $word (glob $word_glob) {
print "$num: $word\n";
}
}
[download]
$ARGV[0]=~s{([2-9])}
{'['.substr("abcdefghijklmnoprstuvwxy",3*($1-2),3).']'}eg;
exec 'grep', "^$ARGV[0]\$", '/usr/share/dict/words';
[download]
When I first read this, I thought you meant actual words, in a dictionary, but it sounds like you mean combinations. Just an aside, if someone wants to limit this to actual words, it's pretty trivial with something like...
perl -lne 'if (/^[a-p,r-y]{4}$/i) {($a = lc $_) =~ tr/[a-p,r-y]/222333
+444555666777888999/; print "$_: $a"}' < /usr/share/dict/words
[download]
If the dictionary has more than one entry for the same word (i.e. capitalized and not), then you'll see it more than once, so putting things in a hash might help.
When I first read this, I thought you meant actual words, in a dictionary, but it sounds like you mean combinations.
Well, generating words was the original goal. Combinations are a step on the way to that goal. Once the combinations are generated, grepping for real words (e.g. using /usr/share/dict/words) is easy. But you have flipped the algorithm around, and used the words to generate the numbers, which is actually quite nice. I hadn't thought about it that way. Many thanks for the reply!
Perl6 is supposed to have lots of features;
but it's supposed
to be simple (unlike Java) in that if you don't
want to use these advanced features
(like for example
continuations, coroutines with yield, exceptions,
quantum-superpositions, multimethods, strong typing,
operator overloading, macros,
calling parrot or native code, or even just objects),
you don't have to use any of them.
You should still be able to write one-liners or
(basic|fortran|pascal)-like programs in it.
(Well, this is the theory, I don't know how much perl6 will
actually be like this, I'm still a bit affraid it will not
be.)
Cheers - L~R
# digit_letters is defined as in the original
def go():
import probstat # module for combinatorics
valid_numbers = range(2,10) # 2..9 inclusive
for (number_set) in probstat.Cartesian([valid_numbers]*4):
answers = []
letter_sets = probstat.Cartesian([digit_letters[number] for number
+ in number_set])
for (letter_set) in letter_sets:
answers.append(''.join(letter_set)) # combine the four letters
print number_set, ", ".join(answers)
[download]
for (four_numbers) in Carteisian([2..9]*[2..9]*[2..9]*[2..9]):
print four_numbers
for (four_letters) in Cartesian(the letters for four_numbers):
print four_letters
[download]
use Math::BaseCnv;@n=split(//,<STDIN>);@l=(a..p,r..z);for(1..3**$#n){
my@q=split(//,cnv($t++,10,3));for(0..$#n-1){
print$l[($n[$_]-2)*3+$q[$#n-$_]]}print"\n";}
[download]
Yes
No
Other opinion (please explain)
Results (99 votes),
past polls | http://www.perlmonks.org/index.pl?node_id=453821 | CC-MAIN-2015-40 | refinedweb | 1,599 | 62.88 |
Test client and simpletemplate
One of the nice things about Django tests is that if you are testing your views (and who doesn't) you can test the context that comes back. That is, when you make a call to a template, you could check the HTML if you wanted, but you could just check the right data was sent to the template.
Unless you are using my simpletemplate that is, since Django testing patches the internal Django templating to pass back the context. I've just added the same to simpletemplate, so that it does the same. At the top of your tests you need to add one line:
from django.contrib.simpletemplate import test
Then in a test we can do:
c = Client() res = c.get("/") assert res.status_code == 200 assert res.context != None, "Test that my simpletemplate patch is working" assert res.context["objects"], "Check that we have some objects"
That's in simpletemplate SVN.
Sigh, the more I use simpletemplate, the more I see all the silly things I did when I wrote it (like putting it in contrib) and need to clean that up one day . | http://agmweb.ca/2009-01-27-test-client-and-simpletemplate/ | CC-MAIN-2019-09 | refinedweb | 191 | 80.11 |
As a developer, a commonly requested feature is the ability to export data from the Web into MS Excel.
Choosing the best way to export your data from an ASP.NET Web page to Excel for your users is never an easy task. There are several ways to generate your reports, with each way having its pros and cons. For starters you’ll have to take into consideration if you are developing a Web based application that needs to enforce strong security, or a more permissive Web-based application that will allow you to write temporary files to your server’s hard drive.
In an earlier article I covered one of the more common ways: how to take an existing report that has already been generated as an HTML table and stream it as Excel to the client browser. This is a great technique, but leaves it up to Excel to interpret the HTML that you are sending its way. Furthermore, Microsoft seems to be deprecating the markup that was previously so amazingly convenient when formatting HTML streamed to Excel. The article also goes into depth about what markup commands are still useful and what markup has been deprecated. It’s definitely worth reading this article if you are considering streaming HTML as an Excel document using the command: Response.ContentType = “application/ms-excel”
Before I go into further details on using the Interop.Excel namespace to generate Excel files, I’d like to point out that I am providing a fully functional example at the end of this article. If you are primarily interested in the code, then you can skip to the bottom of this article and you can copy and paste the code sample into a Visual Studio project where it should run without any problems.
The Benefits of Using the Interop.Excel Namespace to Generate an Excel Document
In this article I will cover a way of handling your exports to Excel from a Web page using the Interop.Excel namespace. In this case, the idea is not to copy an already rendered HTML report to Excel, but instead to re-run the report and then to render it as an actual Excel document. This has the benefit of giving you, the developer, in-depth programmatic control over the work sheets, including detailed control over the cells as they are rendered.
To the user, this method is transparent. You can provide them with something as simple as a button on a Web page that will generate the Excel when it is clicked. Once a user has clicked the button, your code will generate the Excel document from scratch and the user will be prompted to save it to their hard-drive. The Excel file generated won’t have the traditional problems that files generated from HTML can have and your users will thank you for it.
A point to note about this method is that it does require saving to the filesystem of the Server. Furthermore, you will need to configure your Web server to allow DCOM calls from your ASP.NET site. For detailed steps on how to set up your Web server to be able to serve up Excel files using this technique, please see the follow-up article I have linked.
Downsides of Using this Method of Generating an Excel Document
Naturally, this method of creating an Excel document also has its drawbacks. Because you need to iterate through each cell as you render the content of your document, the document generation process is slowed down significantly with larger data sets. So although it is a benefit that you have very granular control over how each cell renders, this process creates a significant performance hit that may be frustrating to your users when they are working with large result-sets.
For example, if you are returning 4,000 rows of data containing five columns, you can expect the document generation time to take a whopping 18 seconds. So if you do use this strategy to generate your Excel documents, you will need to make sure that either the user will only work with smaller data sets, or that they are made aware that the process will not be instant.
Reviewing the Code
Now that we have reviewed the pros and cons of using the Interop.Excel namespace to create Excel documents in your ASP.NET Web applications it’s time to look at how to actually write your code. For starters, the Microsoft.Office.Interop.Excel namespace is not automatically a part of Visual Studio, so you may need to add a reference to this namespace manually. You can find out more about Visual Studio Tools for Office and referencing the proper namespace from this MSDN article. Bottom line, though, is that you will need to reference the Microsoft.Office.Interop.Excel namespace in your code as well as to add a reference to it in your Visual Studio project.
As you can see from the code example below, the process of generating your Excel document is quite straightforward.
- First you need to query your database. In the example I have put together a direct inline SQL call using barebones System.Data SQL syntax that populates a DataTable.
- Once you have your DataTable in place, it’s time to start up your Excel document.
- The first step is to instantiate your Excel document as an Excel.Application object
- Then you create a WorkBooks collection for your Application object
- Then you instantiate a specific WorkBook in your WorkBooks collection
- Finally you can instantiate your new WorkSheet within your WorkBook
- When you have a reference to your new WorkSheet, you need to go about populating the content.
- In the case of this example, we just start up a simple loop through the rows of our DataTable, and we have a sub-loop through the columns in order to read each cell in our resultset so that we can copy it into our WorkSheet.
- Once you have finished looping through your DataTable, you need to complete your work on the Excel document. To do so, call the Quit() method on your Application object.
That’s all there is to it. You can see that as I mentioned, the process is quite straightforward. The only catch with this method is the performance issue that crops up when your results start exceeding 4,000 records. However, the granular control over the contents of your document that this technique gives is quite valuable as well. You will need to weigh the pros and cons depending on your project’s user requirements and make a decision accordingly.
<%@ Page <script runat="server"> Protected m_connStr As String = String.Empty Protected Sub Page_Load(sender As Object, e As System.EventArgs) Dim tmpTbl As System.Data.DataTable = getSearchResultsTable() Dim appExcel As New Microsoft.Office.Interop.Excel.Application() Dim wbExcelBooks As Microsoft.Office.Interop.Excel.Workbooks = CType(appExcel.Workbooks, Workbooks) Dim wbExcelNewBook As Microsoft.Office.Interop.Excel.Workbook = wbExcelBooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet) Dim wsWorkingSheet As Microsoft.Office.Interop.Excel.Worksheet = CType(wbExcelNewBook.Worksheets(1), Worksheet) wsWorkingSheet.Cells(1, 1) = "Generated Excel Document" For colCnt As Int32 = 0 To tmpTbl.Columns.Count - 1 For rowCnt As Int32 = 0 To tmpTbl.Rows.Count - 1 wsWorkingSheet.Cells(rowCnt + 2, colCnt + 1) = tmpTbl.Rows(rowCnt)(colCnt) Next Next appExcel.Quit() End Sub Private Function getSearchResultsTable() As System.Data.DataTable Dim returnValue As System.Data.DataTable = Nothing Dim dvSource As New DataView() Dim da As New SqlDataAdapter() Dim ds As New DataSet() Dim conn As New SqlConnection() m_connStr = ConfigurationManager.ConnectionStrings("ConnDb").ConnectionString conn = New SqlConnection() conn.ConnectionString = m_connStr Try conn.ConnectionString = m_connStr conn.Open() Dim cmd As New SqlCommand() cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandText = "SELECT [Id] " & _ ",[Name] " & _ ",[Alias] " & _ ",[Desc] " & _ ",[Status] " & _ " FROM [MyDB].[dbo].[tblExample]" da = New SqlDataAdapter() da.SelectCommand = cmd da.Fill(ds) returnValue = ds.Tables(0) Catch ex As Exception Finally ds.Dispose() ds = Nothing If Not da Is Nothing Then da.Dispose() da = Nothing End If conn.Close() conn.Dispose() conn = Nothing End Try Return returnValue End Function </script>
8 thoughts on “ASP.NET – Generating an Excel Report on the Fly Using the Interop.Excel Namespace”
so how would you transmit this then without saving it to the server? I’ve been doing this using a tab separated file or converting a gridview to html and saving to excel. Both allow me to transmit the file directly to the user. Is there a way to do this without saving?
Good question. I’m still trying to find a way to stream the file directly without saving.
If you like using the Interop.Excel Namespace, I wrote a follow up article () about setting up your Web server with sufficient permissions to save & then stream the file, but the downside is that you need to play with the server’s security configuration which your network admins might not like.
Using the GridView to Excel technique using mso markup for formatting still seems the most reliable way, but unfortunately MS is scaling back support for it. | https://jwcooney.com/2012/09/02/asp-net-generating-an-excel-report-on-the-fly-using-the-interop-excel-namespace/ | CC-MAIN-2017-22 | refinedweb | 1,518 | 55.64 |
JavaScript functions can be used to create script fragments that can be used over and over again. When written properly, functions are abstract—they can be used in many situations and are ideally completely self-contained, with data passing in and out through well-defined interfaces. JavaScript allows for the creation of such functions, but many developers avoid writing code in such a modular fashion and rely instead on global variables and side-effects to accomplish their tasks. This is a shame, because JavaScript supports all the features necessary to write modular code using functions and even supports some advanced features, such as variable parameter lists. This chapter presents the basics of functions, and the next two chapters discuss how, underneath it all, the real power of JavaScript comes from objects!
The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:
function functionname(parameter-list) { statements }
A simple function that takes no parameters called sayHello is defined here:
function sayHello() { alert("Hello there"); }
To invoke the function somewhere later in the script, you would use the statement
sayHello();
Very often we will want to pass information to functions that will change the operation the function performs or to be used in a calculation. Data passed to functions, whether in literals or variables, are termed parameters, or occasionally arguments. Consider the following modification of the sayHello function to take a single parameter called someName:
function sayHello(someName) { if (someName != "") alert("Hello there "+someName); else alert("Don’t be shy"); }
In this case, the function receives a value that determines which output string to display. Calling the function with
sayHello("George");
results in the alert being displayed:
Calling the function either as
sayHello("");
or simply without a parameter,
sayHello();
will result in the other dialog being displayed:
When you invoke a function that expects arguments without passing any in, JavaScript fills in any arguments that have not been passed with undefined values. This behavior is both useful and extremely dangerous at the same time. While some people might like the ability to avoid typing in all parameters if they aren’t using them, the function itself might have to be written carefully to avoid doing something inappropriate with an undefined value. In short, it is always good programming practice to carefully check parameters passed in.
Functions do not have to receive only literal values; they can also be passed variables or any combination of variables and literals. Consider the function here named addThree that takes three values and displays their result in an alert dialog.
function addThree(arg1, arg2, arg3) { alert(arg1+arg2+arg3); } var x = 5, y = 7; addThree(x, y, 11);
Be careful with parameter passing because JavaScript is weakly typed. Therefore, you might not get the results you expect. For example, consider what would happen if you called addThree.
addThree(5, 11, "Watch out!");
You would see that type conversion would result in a string being displayed.
Using the typeof operator, we might be able to improve the function to report errors.
function addThree(arg1, arg2, arg3) { if ( (typeof arg1 != "number") || (typeof arg2 != "number") || (typeof arg3 != "number") ) alert("Error: Numbers only. "); else alert(arg1+arg2+arg3); }
We’ll see a number of other ways to make a more bullet-proof function later in the chapter. For now, let’s concentrate on returning data from a function.
We might want to extend our example function to save the result of the addition; this is easily performed using a return statement. The inclusion of a return statement indicates that a function should exit and potentially return a value as well. If the function returns a value, the value returned is the value the function invocation takes on in the expression. Here the function addThree has been modified to return a value:
function addThree(arg1, arg2, arg3) { return (arg1+arg2+arg3); } var x = 5, y = 7, result; result = addThree(x,y,11); alert(result);
Functions also can include multiple return statements, as shown here:
function myMax(arg1, arg2) { if (arg1 >>= arg2) return arg1; else return arg2; }
Functions always return some form of result, regardless of whether or not a return statement is included. By default, unless an explicit value is returned, a value of undefined will be returned. While the return statement should be the primary way that data is returned from a function, parameters can be used as well in some situations.
Primitive data types are passed by value in JavaScript. This means that a copy is made of a variable when it is passed to a function, so any manipulation of a parameter holding primitive data in the body of the function leaves the value of the original variable untouched. This is best illustrated by an example:
function fiddle(arg1) { arg1 = 10; document.write("In function fiddle arg1 = "+arg1+"<<br />>"); } var x = 5; document.write("Before function call x = "+x+"<<br />>"); fiddle(x); document.write("After function call x ="+x+"<<br />>");
The result of the example is shown here:
Notice that the function fiddle does not modify the value of the variable x because it only receives a copy of x.
Unlike primitive data types, composite types such as arrays and objects are passed by reference rather than value. For this reason, non-primitive types are often called “reference types.” When a function is passed a reference type, script in the function’s body modifying the parameter will modify the original value in the calling context as well. Instead of a copy of the original data, the function receives a reference to the original data. Consider the following modification of the previous fiddle function.
function fiddle(arg1) { arg1[0] = "changed"; document.write("In function fiddle arg1 = "+arg1+"<<br />>"); } var x = ["first", "second", "third"]; document.write("Before function call x = "+x+"<<br />>"); fiddle(x); document.write("After function call x ="+x+"<<br />>");
In this situation, the function fiddle can change the values of the array held in the variable x, as shown here:
This is “pass by reference” in action. A pointer to the object is passed to the function rather than a copy of it.
Fortunately, unlike other languages such as C, JavaScript doesn’t force the user to worry about pointers or how to de-reference parameters. If you want to modify values within a function, just pass them within an object. For example, if you wanted to modify the value of a string in a function, you would wrap it in an Object:
function fiddle(arg1) { arg1.myString = "New value"; document.write("In function fiddle arg1.myString = "+arg1.myString+"<<br />>"); } var x = new Object(); x.myString = "Original value"; document.write("Before function call x.myString = "+x.myString+"<<br />>"); fiddle(x); document.write("After function call x.myString ="+x.myString+"<<br />>");
The result is
Of course, you could also use a return statement to pass back a new value instead.
One potentially confusing aspect of references is that references are passed by value. In computer science terms, this means that JavaScript references are pointers, not aliases. In less technical terms, this means that you can modify the value in the calling context but you cannot replace it. Assigning a value to a parameter that received a reference type will not overwrite the value in the calling context. For example:
function fiddle(arg1) { arg1 = new String("New value"); document.write("In function fiddle arg1 = "+arg1+"<<br />>"); } var x = new String("Original value"); document.write("Before function call x = "+x+"<<br />>"); fiddle(x); document.write("After function call x ="+x+"<<br />>");
At the beginning of fiddle, arg1 has a reference to the value of x:
It does not, however, have a reference to x itself. Assigning "New value" to arg1 replaces its reference to x’s data with a reference to a new string:
Since the assignment of "New value" isn’t a modification of x’s value, it is not reflected in x:
If this discussion went over your head, don’t worry; it’s rather advanced material. Just keep the following rule in mind: functions passed reference types can modify but not replace values in the calling context. | http://www.yaldex.com/javascript_tutorial_2/LiB0031.html | CC-MAIN-2017-22 | refinedweb | 1,383 | 53.1 |
Pualee wrote:Well actually there is a C-flat, it is called B
Slacker007 wrote:Oh, thaaaat Visual Studio.
jeron1 wrote:all the cool kids call it C hashtag
S Houghtelin wrote:There’s no such thing as C
public class SanderRossel : Lazy<Person>
{
public void DoWork()
{
throw new NotSupportedException();
}
}
Sander Rossel wrote: guitarist who's told too many drummer jokes
S Houghtelin wrote:It's a good thing they don't always know that I'm telling a joke.
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Lounge.aspx?fid=1159&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None&select=4486015&fr=2762 | CC-MAIN-2014-52 | refinedweb | 109 | 57.95 |
Closed Bug 1024858 Opened 6 years ago Closed 6 years ago
Source
Buffer switching hangs in MSR::Initialize Pending Decoders due to data starvation
Categories
(Core :: Audio/Video, defect)
Tracking
()
mozilla34
People
(Reporter: kinetik, Assigned: kinetik)
References
(Blocks 1 open bug)
Details
Attachments
(1 file, 1 obsolete file)
Previous testing always had perfect alignment or a slight overlap.
I can't reproduce the bug as described, and I can't see how it can happen in the current code, so I'm morphing this into a similar bug that I can reproduce (and which may be this bug and was incorrectly diagnosed originally). Steps to reproduce: 1. Start a YT MSE video playing and open the stats for nerds display 2. Force it to low quality (240p) playback 3. Once it switches, quickly (to avoid buffering too much at 240p) back to auto 4. Sometimes the playback will hang when attempting to switch What I'm seeing in the MSE logs at step 4 is a new initialization segment appended to an existing SourceBuffer causing a new decoder to start up. The player appends only enough to trigger the initialization segment switch logic (~250 bytes) and never appends more data. The decoder thread then hangs inside MSR::InitializePendingDecoders (called from an event dispatched by EnqueueDecoderInitialization) while waiting for enough data to return from ReadMetadata.
Summary: MSE doesn't switch playback to next SourceBuffer when there's a ~1 frame gap between buffers → SourceBuffer switching hangs in MSR::InitializePendingDecoders due to data starvation
tl;dr: Fx MSE clears 'buffered' on adaptation. - Background - The MSE Source Buffer Monitoring algorithm is implemented partially or incorrectly in a number of browsers, and as a result the YT player has a number of workarounds. One of these is based on the observation that most media stacks sync to the audio clock. If video buffered ranges is, say, [0, 10], but audio is [0, 20], the spec says that we should hit HAVE_CURRENT_DATA at t=10 and stall, but most platforms keep on playing until t=20, displaying no video or even corrupt video during [10, 20]. So instead, the YT player withholds audio appends until that portion of the timeline has been covered by video appends; in other words it'll only append audio past t=10 once the video buffered ranges expands past [0,10]. This algorithm uses the current media time to identify the buffered time ranges corresponding to the appropriate segment. On a spec-compliant browser, this would be safe, as the source buffer monitoring algorithm prohibits playback unless the current time is a member of the buffered ranges of all active source buffers. - Problem - In Firefox, appending a new initialization segment immediately clears all buffered ranges for the source buffer. Any media data appended subsequently starts a new buffered time range. Here's an example scenario where this produces the observed results: - Initial format is chosen to be 240p. - Video is appended from [0,15]. Because the duration is not added to the buffered ranges, videoSourceBuffer.buffered.end(0) has the value '14.98'. - Audio is appended from [0,15], using linear interpolation to estimate the byte offset that corresponds to 15s within the chunk. Because this method is imperfect, audioSourceBuffer.buffered.end(0) is '14.9'. (The alternative, a full sample-accurate parser in JS, would be excessive.) - 360p is selected. A new initialization segment is appended for 360p. videoSourceBuffer.buffered.length is 0. - A video segment from [15, 25] is appended. --> If buffered ranges were retained and merged here into a single segment, everything would be fine. - Playback advances, but because the current time (in the range 0 -> 14.9) and the video buffered ranges (in the range 15 to 25) never intersect, the logic which allows audio data to be appended is never satisfied. - Video playback proceeds to 14.9 and stalls hard due to lack of data. - Occasionally, something like a tab switch will cause the decoder to pull the next available frame, which happens to be at 15s. - Current time now is set to 15s, which intersects with the current buffered range and allows appending of audio. Playback resumes. - Suggested fix - Don't discard all media data on adaptation, but instead merge new data with existing data in the media timeline. Because the Source Buffer Monitoring algorithm indicates that the eviction on new initialization segment would immediately result in a playback stall, and thus make seamless resolution switching impossible, I believe that the problem here is with Fx's implementation of Media Source, and not the way YT player is using it. Let me know if you have a different opinion and we can discuss. - Repro tools - It's possible to observe this manually by wiring up an adaptation example, which I'll do in a bit. Here's a Greasemonkey script which configures the initial byterate used by the HTML5 player. This can be used to trigger various kinds of adaptive behavior near startup. --- // ==UserScript== // @name Set initial bandwidth // @namespace ytl // @description Set initial bandwidth on YT. // @include* // @include* // @version 1 // @grant none // @run-at document-start // ==/UserScript== unsafeWindow.console.log('Setting initial bandwidth'); unsafeWindow.localStorage['yt-player-bandwidth'] = JSON.stringify({ data: JSON.stringify({ delay: 0, tailDelay: 0, byterate: 40000 }), creation: Date.now(), expiration: Date.now() + (3600 * 24 * 7 * 1000) }); ---
Thanks Steve, that comment and the two new bugs you filed are immensely helpful!
Also bug 1050083 for WebM buffered fixes.
Reimplement @buffered for media elements using a MediaSource in terms of the active source buffers (matching MSE spec). Also include buffered ranges from discarded decoders in SourceBuffer @buffered.
Attachment #8470613 - Flags: review?(cajbir.bugzilla)
Status: ASSIGNED → RESOLVED
Closed: 6 years ago
Resolution: --- → FIXED
Target Milestone: --- → mozilla34 | https://bugzilla.mozilla.org/show_bug.cgi?id=1024858 | CC-MAIN-2020-34 | refinedweb | 952 | 54.93 |
22 June 2012 18:20 [Source: ICIS news]
WASHINGTON (ICIS)--A major ?xml:namespace>
The Manufacturers Alliance for Productivity and Innovation (MAPI) said it was lowering its outlook for
“We forecast that GDP growth will increase at annual rates of 2.1% over the next five quarters,” said MAPI chief economist Daniel Meckstroth.
“These growth rates are categorized as a relatively modest pace and well below what would be considered normal for an expansion following a severe recession,” he said.
“Consumers are deleveraging and are reducing debt and therefore can only increase spending commensurate with employment and wage growth,” he added.
US GDP grew at an anaemic 1.9% in the first quarter this year, following a 3% growth rate in the fourth quarter of 2011. The
The first official estimate of the nation’s second quarter GDP performance will be made by the Commerce Department on 27 July.
MAPI had earlier forecast a full-year GDP growth of 2.2%.
If MAPI’s new forecast of 2.1% second-half growth is accurate, that pace of expansion combined with the first quarter’s 1.9% GDP would likely mean an overall 2012 GDP of around 2%.
Part of MAPI’s lower expectation for overall US GDP expansion this year and early 2013 was attributed to a new cool-down in manufacturing growth.
The alliance noted that US manufacturing industries expanded “at a scorching 10% annual rate in the first quarter of this year, [but] it will decelerate to an average of 3% for the remainder of the year”.
Although 3% annual growth for manufacturing is good and considerably better than the outlook for the overall economy, MAPI indicated that industrial production going forward might have been better.
“The positive news for manufacturing is tempered by anticipated slow growth in the overall economy,” the alliance said.
In addition, while there is strong demand among emerging economies worldwide for equipment and infrastructure improvement that would benefit US manufacturing exports, Meckstroth cautioned that “One negative is that the recession in
On Wednesday this week the Federal Reserve Board, the US central bank, also lowered its outlook for the nation's economy through the rest | http://www.icis.com/Articles/2012/06/22/9572178/US-manufacturers-lower-outlook-for-production-GDP-growth.html | CC-MAIN-2015-06 | refinedweb | 362 | 50.77 |
How to Create Endless Loops in C Programming happens because of programmer error. And with the way loops are set up in C, it’s easy to unintentionally loop ad infinitum.
A Common Way to Make an Endless Loop illustrates a common endless loop, which is a programming error, not a syntax error.
A COMMON WAY TO MAKE AN ENDLESS LOOP
#include <stdio.h> int main() { int x; for(x=0;x=10;x=x+1) { puts("What are you lookin' at?"); } return(0); }
The problem with the code in A Common Way to Make an Endless Loop is that the for statement’s exit condition is always true: x=10. Read it again if you didn’t catch it the first time, or just do Exercise 9-18.
Exercise 1: Type the source code for A Common Way to Make an Endless Loop. Save, build, and run.
The compiler may warn you about the constant TRUE condition in the for statement. Code::Blocks should do that, and any other compiler would, if you ratcheted up its error-checking. Otherwise, the program compiles and runs — infinitely.
To break out of an endless loop, press Ctrl+C on the keyboard. This trick works only for console programs, and it may not always work. If it doesn’t, you need to kill the process run amok.
Endless loops are also referred to as infinite loops.
How to loop endlessly but on purpose
Occasionally, a program needs an endless loop. For example, a microcontroller may load a program that runs as long as the device is on. When you set up such a loop on purpose in C, one of two statements is used:
for(;;)
Read this statement as “for ever.” With no items in the parentheses, but still with the required two semicolons, the for loop repeats eternally — even after the cows come home. Here’s the while loop equivalent:
while(1)
The value in the parentheses doesn’t necessarily need to be 1; any True or non-zero value works. When the loop is endless on purpose, however, most programmers set the value to 1 simply to self-document that they know what’s up.
How to break out of a loop
Any loop can be terminated instantly — including endless loops — by using a break statement within the loop’s repeating group of statements. When break is encountered, looping stops and program execution picks up with the next statement after the loop’s final curly bracket. Get Me Outta Here! demonstrates the process.
GET ME OUTTA HERE!
#include <stdio.h> int main() { int count; count = 0; while(1) { printf("%d, ",count); count = count+1; if( count > 50) break; } putchar('n'); return(0); }
The while loop at Line 8 is configured to go on forever, but the if test at Line 12 can stop it: When the value of count is greater than 50, the break statement (refer to Line 13) is executed and the loop halts.
Exercise 2: Build and run a new project using the source code from Get Me Outta Here!
Exercise 3: Rewrite the source code from Get Me Outta Here! so that an endless for loop is used instead of an endless while loop.
You don’t need to construct an endless loop to use the break statement. You can break out of any loop. When you do, execution continues with the first statement after the loop’s final curly bracket.
How you can screw up a loop with C
There are two common ways to mess up a loop. These trouble spots crop up for beginners and pros alike. The only way to avoid these spots is to keep a keen eye so that you can spot ’em quick.
The first goof-up is specifying a condition that can never be met; for example:
for(x=1;x==10;x=x+1)
In the preceding line, the exit condition is false before the loop spins once, so the loop is never executed. This error is almost as insidious as using an assignment operator (a single equal sign) instead of the “is equal to” operator (as just shown).
Another common mistake is misplacing the semicolon, as in
for(x=1;x<14;x=x+1); { puts(“Sore shoulder surgery”); }
Because the first line, the for statement, ends in a semicolon, the compiler believes that the line is the entire loop. The empty code repeats 13 times, which is what the for statement dictates. The puts() statement is then executed once.
Those rogue semicolons can be frustrating!
The problem is worse with while loops because the do-while structure requires a semicolon after the final while statement. In fact, forgetting that particular semicolon is also a source of woe. For a traditional while loop, you don’t do this:
while(x<14); { puts(“Sore shoulder surgery”); }
The severely stupid thing about these semicolon errors is that the compiler doesn’t catch them. It believes that your intent is to have a loop without statements. Such a thing is possible.
A FOR LOOP WITH NO BODY
#include <stdio.h> int main() { int x; for(x=0;x<10;x=x+1,printf("%dn",x)) ; return(0); }
In the example shown in A for Loop with No Body, the semicolon is placed on the line after the for statement (refer to Line 8 in A for Loop with No Body). That shows deliberate intent.
You can see that two items are placed in the for statement’s parentheses, both separated by a comma. That’s perfectly legal, and it works, though it’s not quite readable.
Exercise 4: Type the source code from A for Loop with No Body into your editor. Build and run.
Though you can load up items in a for statement’s parentheses, it’s rare and definitely not recommended, for readability’s sake. | https://www.dummies.com/programming/c/how-to-create-endless-loops-in-c-programming/ | CC-MAIN-2019-39 | refinedweb | 978 | 72.05 |
import "gopkg.in/src-d/go-vitess.v1/vt/vtgate/gatewaytest"
Package gatewaytest contains a test suite to run against a Gateway object. We re-use the tabletconn test suite, as it tests all queries and parameters go through. There are two exceptions: - the health check: we just make that one work, so the gateway knows the
tablet is healthy.
- the error type returned: it's not a TabletError any more, but a ShardError.
We still check the error code is correct though which is really all we care about.
func CreateFakeServers(t *testing.T) (*tabletconntest.FakeQueryService, *topo.Server, string)
CreateFakeServers returns the servers to use for these tests
func TestSuite(t *testing.T, name string, g gateway.Gateway, f *tabletconntest.FakeQueryService)
TestSuite executes a set of tests on the provided gateway. The provided gateway needs to be configured with one established connection for tabletconntest.TestTarget.{Keyspace, Shard, TabletType} to the provided tabletconntest.FakeQueryService.
Package gatewaytest imports 11 packages (graph). Updated 2019-06-13. Refresh now. Tools for package owners. | https://godoc.org/gopkg.in/src-d/go-vitess.v1/vt/vtgate/gatewaytest | CC-MAIN-2019-51 | refinedweb | 170 | 52.46 |
Plug flow reactor with a pressure drop
Posted February 18, 2013 at 09:00 AM | categories: ode | tags: reaction engineering, fluids | View Comments
Updated March 06, 2013 at 04:39 PM
If there is a pressure drop in a plug flow reactor, 1 there are two equations needed to determine the exit conversion: one for the conversion, and one from the pressure drop.\begin{eqnarray} \frac{dX}{dW} &=& \frac{k'}{F_A0} \left ( \frac{1-X}{1 + \epsilon X} \right) y\\ \frac{dX}{dy} &=& -\frac{\alpha (1 + \epsilon X)}{2y} \end{eqnarray}
Here is how to integrate these equations numerically in python.
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt kprime = 0.0266 Fa0 = 1.08 alpha = 0.0166 epsilon = -0.15 def dFdW(F, W): 'set of ODEs to integrate' X = F[0] y = F[1] dXdW = kprime / Fa0 * (1-X) / (1 + epsilon*X) * y dydW = -alpha * (1 + epsilon * X) / (2 * y) return [dXdW, dydW] Wspan = np.linspace(0,60) X0 = 0.0 y0 = 1.0 F0 = [X0, y0] sol = odeint(dFdW, F0, Wspan) # now plot the results plt.plot(Wspan, sol[:,0], label='Conversion') plt.plot(Wspan, sol[:,1], 'g--', label='y=$P/P_0$') plt.legend(loc='best') plt.xlabel('Catalyst weight (lb_m)') plt.savefig('images/2013-01-08-pdrop.png')
Here is the resulting figure.
Copyright (C) 2013 by John Kitchin. See the License for information about copying. | http://kitchingroup.cheme.cmu.edu/blog/2013/02/18/Plug-flow-reactor-with-a-pressure-drop/ | CC-MAIN-2020-05 | refinedweb | 236 | 61.22 |
Name methods and variables with respect to the owning class by asking the question “If I were the class, what would the method or variable be called from my perspective? What would I call it when I wanted to refer to it?”
For example, an IntegrationPartnerConnection class is used to store communication details so we can query external systems. It has two names for JMS queues in it, one for incoming data and another for outgoing data. But is it “incoming” with respect to the external party or with respect to the IntegrationPartnerConnection?
public class IntegrationPartnerConnection { : // is it our incoming or the external partner incoming queue? private String incomingQueueName; // is it our outgoing or the external partner outgoing queue? private String outgoingQueueName; : }
The answer can be determined by looking at where the queue variables are defined. They are defined in the IntegrationPartnerConnection so they should be named with respect to it.
“If I was an IntegrationPartnerConnection, what would I call my incoming queue?”
So the queues are always named with respect to the owning class, but an added comment to avoid any ambiguity helps.
eg.
public class IntegrationPartnerConnection { : // My queues, from the perspective of me, the Connection private String incomingQueueName; private String outgoingQueueName; : }
As another example, think of a piece of code that deals with a folder that used both an import or export directory. Class OrderUploader uses the folder as an export directory (it places a file there), and OrderProcessor uses the folder as an import directory (it reads a file from there).
public class OrderUploader { private File exportFolder; : } public class OrderProcessor { private File importFolder; : }
Therefore the name of the folder in OrderUploader is “exportFolder”, and the name of the folder in OrderProcessor is “importFolder”. ie. “am I exporting or importing?” This example seems simple enough but for more complex tasks, getting the right context is important.
Trap: a common mistake is to name variables based on other classes that will be using the variables even though they are not the owners of the variable. Repeat the question: “If I am the owning class, what does the variable represent to me?”.
After applying this rule, if you still can't work out if the name of the variable should be 'input' or 'output', perhaps it is defined in the wrong class. Your fellow programmers are always happy to discuss the best choice of naming convention and variable location. | http://javagoodways.com/name_context_Name_attributes_with_respect_to_the_class.html | CC-MAIN-2021-21 | refinedweb | 399 | 51.28 |
java.lang.StringBuilder
StringBuilder class is introduced in Java 5.0 version. This class is replacement for the
existing StringBuffer class. If you look into the operations of the both the classes,
there is no difference.
also read:
- If you are using StringBuilder, no guarantee of synchronization. This is the only difference with StringBuffer class.
- It is recommended that this class be used in preference to StringBuffer as it will be faster.
- You can easily replace the exisitng StringBuffer implementaion with StringBuilder without any compilation
problem.
StringBuilderExample.java
package javabeat.net.java; /** * source : */ public class StringBuilderExample { public static void main(String[] args) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Add a string"); System.out.println(stringBuilder.toString()); }
}
[…] without even iterating the whole list . As a side note, we could also use a StringBuffer (Read : StringBuilder) to concatenate our Strings, but the return should be stringbuffer.toString (). The example below […] | http://www.javabeat.net/stringbuilder-class-in-java-5-0/ | CC-MAIN-2014-15 | refinedweb | 148 | 52.56 |
Django version 0.96 release notes¶
Welcome to Django 0.96!
The primary goal for 0.96 is a cleanup and stabilization of the features introduced in 0.95. There have been a few small backwards-incompatible changes since 0.95, but the upgrade process should be fairly simple and should not require major changes to existing applications.
However, we’re also releasing 0.96 now because we have a set of backwards-incompatible changes scheduled for the near future. Once completed, they will involve some code changes for application developers, so we recommend that you stick with Django 0.96 until the next official release; then you’ll be able to upgrade in one step instead of needing to make incremental changes to keep up with the development version of Django.
Backwards-incompatible changes¶
The following changes may require you to update your code when you switch from 0.95 to 0.96:
MySQLdb version requirement¶
Due to a bug in older versions of the MySQLdb Python module (which Django uses to connect to MySQL databases), Django’s MySQL backend now requires version 1.2.1p2 or higher of MySQLdb, and will raise exceptions if you attempt to use an older version.
If you’re currently unable to upgrade your copy of MySQLdb to meet this requirement, a separate, backwards-compatible backend, called “mysql_old”, has been added to Django. To use this backend, change the DATABASE_ENGINE setting in your Django settings file from this:
DATABASE_ENGINE = "mysql"
to this:
DATABASE_ENGINE = "mysql_old"
However, we strongly encourage MySQL users to upgrade to a more recent version of MySQLdb as soon as possible, The “mysql_old” backend is provided only to ease this transition, and is considered deprecated; aside from any necessary security fixes, it will not be actively maintained, and it will be removed in a future release of Django.
Also, note that some features, like the new DATABASE_OPTIONS setting (see the databases documentation for details), are only available on the “mysql” backend, and will not be made available for “mysql_old”.
Database constraint names changed¶
The format of the constraint names Django generates for foreign key references have changed slightly. These names are generally only used when it is not possible to put the reference directly on the affected column, so they are not always visible.
The effect of this change is that running manage.py reset and similar commands against an existing database may generate SQL with the new form of constraint name, while the database itself contains constraints named in the old form; this will cause the database server to raise an error message about modifying non-existent constraints.
If you need to work around this, there are two methods available:
- Redirect the output of manage.py to a file, and edit the generated SQL to use the correct constraint names before executing it.
- Examine the output of manage.py sqlall to see the new-style constraint names, and use that as a guide to rename existing constraints in your database.
Name changes in manage.py¶
A few of the options to manage.py have changed with the addition of fixture support:
- There are new dumpdata and loaddata commands which, as you might expect, will dump and load data to/from the database. These commands can operate against any of Django’s supported serialization formats.
- The sqlinitialdata command has been renamed to sqlcustom to emphasize that loaddata should be used for data (and sqlcustom for other custom SQL – views, stored procedures, etc.).
- The vestigial install command has been removed. Use syncdb.
Backslash escaping changed¶
The Django database API now escapes backslashes given as query parameters. If you have any database API code that matches backslashes, and it was working before (despite the lack of escaping), you’ll have to change your code to “unescape” the slashes one level.
For example, this used to work:
# Find text containing a single backslash MyModel.objects.filter(text__contains='\\\\')
The above is now incorrect, and should be rewritten as:
# Find text containing a single backslash MyModel.objects.filter(text__contains='\\')
What’s new in 0.96?¶
This revision represents over a thousand source commits and over four hundred bug fixes, so we can’t possibly catalog all the changes. Here, we describe the most notable changes in this release.
New forms library¶
django.newforms is Django’s new form-handling library. It’s a replacement for django.forms, the old form/manipulator/validation framework. Both APIs are available in 0.96, but over the next two releases we plan to switch completely to the new forms system, and deprecate and remove the old system.
There are three elements to this transition:
We’ve copied the current django.forms to django.oldforms. This allows you to upgrade your code now rather than waiting for the backwards-incompatible change and rushing to fix your code after the fact. Just change your import statements like this:
from django import forms # 0.95-style from django import oldforms as forms # 0.96-style
The next official release of Django will move the current django.newforms to django.forms. This will be a backwards-incompatible change, and anyone still using the old version of django.forms at that time will need to change their import statements as described above.
The next release after that will completely remove django.oldforms.
Although the newforms library will continue to evolve, it’s ready for use for most common cases. We recommend that anyone new to form handling skip the old forms system and start with the new.
For more information about django.newforms, read the newforms documentation.
URLconf improvements¶
You can now use any callable as the callback in URLconfs (previously, only strings that referred to callables were allowed). This allows a much more natural use of URLconfs. For example, this URLconf:
from django.conf.urls.defaults import * urlpatterns = patterns('', ('^myview/$', 'mysite.myapp.views.myview') )
can now be rewritten as:
from django.conf.urls.defaults import * from mysite.myapp.views import myview urlpatterns = patterns('', ('^myview/$', myview) )
One useful application of this can be seen when using decorators; this change allows you to apply decorators to views in your URLconf. Thus, you can make a generic view require login very easily:
from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from django.views.generic.list_detail import object_list from mysite.myapp.models import MyModel info = { "queryset" : MyModel.objects.all(), } urlpatterns = patterns('', ('^myview/$', login_required(object_list), info) )
Note that both syntaxes (strings and callables) are valid, and will continue to be valid for the foreseeable future.
The test framework¶
Django now includes a test framework so you can start transmuting fear into boredom (with apologies to Kent Beck). You can write tests based on doctest or unittest and test your views with a simple test client.
There is also new support for “fixtures” – initial data, stored in any of the supported serialization formats, that will be loaded into your database at the start of your tests. This makes testing with real data much easier.
See the testing documentation for the full details.
Thanks¶
Since 0.95, a number of people have stepped forward and taken a major new role in Django’s development. We’d like to thank these people for all their hard work:
- Russell Keith-Magee and Malcolm Tredinnick for their major code contributions. This release wouldn’t have been possible without them.
- Our new release manager, James Bennett, for his work in getting out 0.95.1, 0.96, and (hopefully) future release.
- Our ticket managers Chris Beaven (aka SmileyChris), Simon Greenhill, Michael Radziej, and Gary Wilson. They agreed to take on the monumental task of wrangling our tickets into nicely cataloged submission. Figuring out what to work on is now about a million times easier; thanks again, guys.
- Everyone who submitted a bug report, patch or ticket comment. We can’t possibly thank everyone by name – over 200 developers submitted patches that went into 0.96 – but everyone who’s contributed to Django is listed in AUTHORS. | https://docs.djangoproject.com/en/1.6/releases/0.96/ | CC-MAIN-2015-18 | refinedweb | 1,336 | 57.16 |
Asyncio
Asyncio is a co-operative multitasking library available in Python since version 3.6. Celery is fantastic for running concurrent tasks out of process, but there are certain times you would need to run multiple tasks in a single thread inside a single process.
If you are not familiar with async/await concepts (say from JavaScript or C#) then it involves a bit of steep learning curve. However, it is well worth your time as it can speed up your code tremendously (unless it is completely CPU-bound). Moreover, it helps in understanding other libraries built on top of them like Django Channels.
This post is an attempt to explain the concepts in a simplified manner rather than try to be comprehensive. I want you to start using asynchronous programming and enjoy it. You can learn the nitty gritties later.
All asyncio programs are driven by an event loop, which is pretty much an indefinite loop that calls all registered coroutines in some order until they all terminate. Each coroutine operates cooperatively by yielding control to fellow coroutines at well-defined places. This is called awaiting.
A coroutine is like a special function which can suspend and resume execution. They work like lightweight threads. Native coroutines use the async and await keywords, as follows:
import asyncio async def sleeper_coroutine(): await asyncio.sleep(5) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(sleeper_coroutine())
This is a minimal example of an event loop running one coroutine named sleeper_coroutine. When invoked this coroutine runs until the await statement and yields control back to the event loop. This is usually where an Input/Output activity occurs.
The control comes back to the coroutine at the same line when the activity being awaited is completed (after five seconds). Then then coroutine returns or is considered completed.
Explain async and await
[TLDR; Watch my screencast to understand this section with a lot more code examples.]
Initially, I was confused by the presence of the new keywords in Python: async and await. Asynchronous code seemed to be littered with these keywords yet it was not clear what they did or when to use them.
Let’s first look at the
async keyword. Commonly used before a function definition as
async def, it indicates that you are defining a (native) coroutine.
You should know two things about coroutines:
- Don’t perform slow or blocking operations synchronously inside coroutines.
- Don’t call a coroutine directly like a regular function call. Either schedule it in an event loop or await it from another coroutine.
Unlike a normal function call, if you invoke a coroutine its body will not get executed right away. Instead it will be suspended and returns a coroutine object. Invoking the send method of this coroutine will start the execution of the coroutine body.
>>> async def hi(): ... print("HOWDY!") ... >>> o = hi() >>> o <coroutine object hi at 0x000001DAE26E2F68> >>> o.send(None) HOWDY! Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
However, when the coroutine returns it will end in a StopIteration exception. Hence it is better to use the asyncio provided event loop to run a coroutine. The loop will handle exceptions in addition to all other machinery for running coroutines concurrently.
>>> import asyncio >>> loop = asyncio.get_event_loop() >>> o = hi() >>> loop.run_until_complete(o) HOWDY!
Next we have the
await keyword which must be only used inside a coroutine. If you call another coroutine, chances are that it might get blocked at some point, say while waiting for I/O.
>>> async def sleepy(): ... await asyncio.sleep(3) ... >>> o = sleepy() >>> loop.run_until_complete(o) # After three seconds >>>
The sleep coroutine from asyncio module is different from its synchronous counterpart time.sleep. It is non-blocking. This means that other coroutines can be executed while this coroutine is awaiting the sleep to be completed.
When a coroutine uses the await keyword to call another coroutines, it acts like a bookmark. When a blocking operation happens, it suspends the coroutine (and all the coroutines who are await-ing it) and returns control back to the event loop. Later, when the event loop is notified of the completion of the blocking operation, then the execution is resumed from the await expression paused and continues onward.
Asyncio vs Threads
If you have worked on multi-threaded code, then you might wonder – Why not just use threads? There are several reasons why threads are not popular in Python.
Firstly, threads need to be synchronized while accessing shared resources or we will have race conditions. There are several types of synchronization primitives like locks but essentially, they involve waiting which degrades performance and could cause deadlocks or starvation.
A thread may be interrupted any time. Coroutines have well-defined places where execution is handed over i.e. co-operative multitasking. As a result, you may make changes to a shared state as long as you leave it in a known state. For instance you can retrieve a field from a database, perform calculations and overwrite the field without worrying that another coroutine might have interrupted you in between. All this is possible without locks.
Secondly, coroutines are lightweight. Each coroutine needs an order of magnitude less memory than a thread. If you can run a maximum of hundreds of threads, then you might be able to run tens of thousands of coroutines given the same memory. Thread switching also takes some time (few milliseconds). This means you might be able to run more tasks or serve more concurrent users (just like how Node.js works on a single thread without blocking).
The downsides of coroutines is that you cannot mix blocking and non-blocking code. So once you enter the event loop, rest of the code driven by it must be written in asynchronous style, even the standard or third-party libraries you use. This might make using some older libraries with synchronous code somewhat difficult.
If you really want to call asynchronous code from synchronous or vice versa, then do read this excellent overview of various cases and adaptors you can use by Andrew Godwin.
The Classic Web-scraper Example
Let’s look at an example of how we can rewrite synchronous code into asynchronous. We will look at a webscraper which downloads pages from a couple of URLs and measures its size. This is a common example because it is very I/O bound which shows a significant speedup when handled concurrently.
Synchronous web scraping
The synchronous scraper uses Python 3 standard libraries like urllib. It downloads the home page of three popular sites and the fourth is a large file to simulate a slow connection. It prints the respective page sizes and the total running time.
Here is the code for the synchronous scraper:
# sync.py """Synchronously download a list of webpages and time it""" from urllib.request import Request, urlopen from time import time sites = [ "", "", "", ] def find_size(url): req = Request(url) with urlopen(req) as response: page = response.read() return len(page) def main(): for site in sites: size = find_size(site) print("Read {:8d} chars from {}".format(size, site)) if __name__ == '__main__': start_time = time() main() print("Ran in {:6.3f} secs".format(time() - start_time))
On a test laptop, this code took 5.4 seconds to run. It is the cumulative loading time of each site. Let’s see how asynchronous code runs.
Asynchronous web scraping
This asyncio code requires installation of a few Python asynchronous network libraries such as aiohttp and aiodns. They are mentioned in the docstring.
Here is the code for the asynchronous scraper – it is structured to be as close as possible to the synchronous version so it is easier to compare:
# async.py """ Asynchronously download a list of webpages and time it Dependencies: Make sure you install aiohttp using: pip install aiohttp aiodns """ import asyncio import aiohttp from time import time # Configuring logging to show timestamps import logging logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%H:%M:%S]') log = logging.getLogger() log.setLevel(logging.INFO) sites = [ "", "", "", ] async def find_size(session, url): log.info("START {}".format(url)) async with session.get(url) as response: log.info("RESPONSE {}".format(url)) page = await response.read() log.info("PAGE {}".format(url)) return url, len(page) async def main(): tasks = [] async with aiohttp.ClientSession() as session: for site in sites: tasks.append(find_size(session, site)) results = await asyncio.gather(*tasks) for site, size in results: print("Read {:8d} chars from {}".format(size, site)) if __name__ == '__main__': start_time = time() loop = asyncio.get_event_loop() loop.set_debug(True) loop.run_until_complete(main()) print("Ran in {:6.3f} secs".format(time() - start_time))
The main function is a coroutine which triggers the creation of a separate coroutine for each website. Then it awaits until all these triggered coroutines are completed. As a best practice, the web session object is passed to avoid re-creating new sessions for each page.
The total running time of this program on the same test laptop is 1.5 s. This is a speedup of 3.6x on the same single core. This surprising result can be better understood if we can visualize how the time was spent, as shown below:
A simplistic representation comparing tasks in the synchronous and asynchronous scrapers
The synchronous scraper is easy to understand. Scraping activity needs very little CPU time and the majority of the time is spent waiting for the data to arrive from the network. Each task is waiting for the previous task to complete. As a result the tasks cascade sequentially like a waterfall.
On the other hand the asynchronous scraper starts the first task and as soon as it starts waiting for I/O, it switches to the next task. The CPU is hardly idle as the execution goes back to the event loop as soon as the waiting starts. Eventually the I/O completes in the same amount of time but due to the multiplexing of activity, the overall time taken is drastically reduced.
In fact, the asynchronous code can be speeded up further. The standard asyncio event loop is written in pure Python and provided as a reference implementation. You can consider faster implementations like uvloop for further speedup (my running time came down to 1.3 secs).
Concurrency is not Parallelism
Concurrency is the ability to perform other tasks while you are waiting on the current task. Imagine you are cooking a lot of dishes for some guests. While waiting for something to cook, you are free to do other things like peeling onions or cutting vegetables. Even when one person cooks, typically there will be several things happening concurrently.
Parallelism is when two or more execution engines are performing a task. Continuing on our analogy, this is when two or more cooks work on the same dish to (hopefully) save time.
It is very easy to confuse concurrency and parallelism because they can happen at the same time. You could be concurrently running tasks without parallelism or vice versa. But they refer to two different things. Concurrency is a way of structuring your programs while Parallelism refers to how it is executed.
Due to the Global Interpreter Lock, we cannot run more than one thread of the Python interpreter (to be specific, the standard CPython interpreter) at a time even in multicore systems. This limits the amount of parallelism which we can achieve with a single instance of the Python process.
Optimal usage of your computing resources require both concurrency and parallelism. Concurrency will help you avoid idling the processor core while waiting for say I/O events. While parallelism will help distribute work among all the available cores.
In both cases, you are not executing synchronously i.e. waiting for a task to finish before moving on to another task. Asynchronous systems might seem to be the most optimal. However, they are harder to build and reason about.
Why another Asynchronous Framework?
Asyncio is by no means the first cooperative multitasking or light-weight thread library. If you have used gevent or eventlet, you might find asyncio needs more explicit separation between synchronous and asynchronous code. This is usually a good thing.
Gevent, relies on monkey-patching to change blocking I/O calls to non-blocking ones. This can lead to hard to find performance issues due to an unpatched blocking call slowing the event loop. As the Zen says, ‘Explicit is better than Implicit’.
Another objective of asyncio was to provide a standardized concurrency framework for all implementations like gevent or Twisted. This not only reduces duplicated efforts by library authors but also ensures that code is portable for end users.
Personally, I think the asyncio module can be more streamlined. There are a lot of ideas which somewhat expose implementation details (e.g. native coroutines vs generator-based coroutines). But it is useful as a standard to write future-proof code.
Can we use asyncio in Django?
Strictly speaking, the answer is No. Django is a synchronous web framework. You might be able to run a seperate worker process, say in Celery, to run an embedded event loop. This can be used for I/O background tasks like web scraping.
However, Django Channels changes all that. Django might fit in the asynchronous world after all. But that’s the subject of another post.
This article contains an excerpt from "Django Design Patterns and Best Practices" by Arun Ravindran | https://arunrocks.com/get-started-with-async-and-await/ | CC-MAIN-2018-39 | refinedweb | 2,224 | 66.03 |
Created on 2021-01-08 09:28 by vstinner, last changed 2021-01-08 14:49 by vstinner. This issue is now closed.
$ ./python -m test test_multibytecodec -m test.test_multibytecodec.Test_IncrementalEncoder.test_subinterp -R 3:3
(...)
test_multibytecodec leaked [258, 258, 258] references, sum=774
I simplified the code. The following test leaks references:
def test_subinterp(self):
import _testcapi
code = textwrap.dedent("""
import _codecs_jp
codec = _codecs_jp.getcodec('cp932')
codec = None
""")
_testcapi.run_in_subinterp(code)
_codecs_jp.getcodec() is defined in Modules/cjkcodecs/cjkcodecs.h. Extract:
cofunc = getmultibytecodec();
...
codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
if (codecobj == NULL)
return NULL;
r = PyObject_CallOneArg(cofunc, codecobj);
Py_DECREF(codecobj);
getmultibytecodec() is the _multibytecodec.__create_codec() which is defined in Modules/cjkcodecs/multibytecodec.c. Simplified code:
codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME);
_multibytecodec_state *state = _multibytecodec_get_state(module);
self = PyObject_New(MultibyteCodecObject, state->multibytecodec_type);
self->codec = codec;
return (PyObject *)self;
I added the test which leaks in bpo-42846.
commit 07f2cee93f1b619650403981c455f47bfed8d818
Author: Victor Stinner <vstinner@python.org>
Date: Fri Jan 8 00:15:22 2021 +0100
bpo-42846: Convert CJK codec extensions to multiphase init (GH-24157)
Convert the 6 CJK codec extension modules (_codecs_cn, _codecs_hk,
_codecs_iso2022, _codecs_jp, _codecs_kr and _codecs_tw) to the
multiphase initialization API (PEP 489).
Remove getmultibytecodec() local cache: always import
_multibytecodec. It should be uncommon to get a codec. For example,
this function is only called once per CJK codec module.
Fix a reference leak in register_maps() error path.
I don't think that the leak is new. It's just that it wasn't seen previously.
By the way, I wrote an article "Leaks discovered by subinterpreters":
This leak may be new kind related to capsule, I'm not sure so far.
Thank you so much for taking the time to write these blog posts, Victor, and for explaining your fixes is such great detail. It is very helpful!
PR 24165 fix one reference leak in the getcodec() function of CJK codecs. But it doesn't fix all ref leaks of this issue.
The leak can be simplified to:
@support.cpython_only
def test_subinterp(self):
import _testcapi
code = textwrap.dedent("""
import encodings
import _codecs_jp
encodings._cache['cp932'] = _codecs_jp.getcodec('cp932')
""")
res = _testcapi.run_in_subinterp(code)
self.assertEqual(res, 0)
Links about ref leaks related to encodings:
*
*
*
*
See also bpo-42671 "Make the Python finalization more deterministic" but it seems like PR 23826 makes the leak worse (+2000 leaked references instead of +200) :-)
> encodings._cache['cp932'] = _codecs_jp.getcodec('cp932')
* encodings._cache is kept alive by encodings.search_function.__globals__
* encodings.search_function function is kept alive by PyInterpreterState.codec_search_path list. The function by _PyCodec_Register() in encodings/__init__.py: codecs.register(search_function).
For example, unregistering the search function prevents the leak:
import encodings
import _codecs_jp
encodings._cache['cp932'] = _codecs_jp.getcodec('cp932')
import codecs
codecs.unregister(encodings.search_function)
The PyInterpreterState.codec_search_path list is cleared at Python exit by interpreter_clear().
The weird part is that the _codecs_jp.getcodec('cp932') codec object *is* deleted. I checked and multibytecodec_dealloc() is called with the object stored in the encodings cache.
A _multibytecodec.MultibyteCodec instance (MultibyteCodecObject* structure in C) is a simple type: it only stores pointer to C functions and C strings. It doesn't contain any Python object. So I don't see how it could be part of a reference cycle by itself. Moreover, again, it is deleted.
Calling gc.collect() twice works around the issue, which sounds like a missing traverse function somewhere.
diff --git a/Python/pystate.c b/Python/pystate.c
index c791b23999..66bbe1bf7d 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -321,6 +321,7 @@ interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
/* Last garbage collection on this interpreter */
_PyGC_CollectNoFail(tstate);
+ _PyGC_CollectNoFail(tstate);
_PyGC_Fini(tstate);
/* We don't clear sysdict and builtins until the end of this function.
New changeset e542d417b96077d04aec089505eacb990c9799ae by Victor Stinner in branch 'master':
bpo-42866: Fix refleak in CJK getcodec() (GH-24165)
Don't you need to free memory using PyObject_GC_Del when you allocate using PyObject_GC_New?
Ref.
> Don't you need to free memory using PyObject_GC_Del when you allocate using PyObject_GC_New?
My PR uses the generic tp->tp_free which PyObject_GC_Del().
typo: My PR uses the generic tp->tp_free which *is* PyObject_GC_Del().
Ah, thanks! I also found that info in the docs:
New changeset 11ef53aefbecfac18b63cee518a7184f771f708c by Victor Stinner in branch 'master':
bpo-42866: Add traverse func to _multibytecodec.MultibyteCodec (GH-24166)
Ok, it's now fixed.
To make sure that a heap type can be deleted, it must by a GC type, has a traverse function, and it must track its instances. We should take this in account when we convert static types to heap types. In practice, deleting a type is mostly an issue when we check for reference leak and an instance is kept alive until the last GC collection, at the end of Py_EndInterpreter(). | https://bugs.python.org/issue42866 | CC-MAIN-2022-05 | refinedweb | 782 | 51.55 |
The QHostAddress class provides an IP address. More...
#include <qhostaddress.h>
List of all member functions.
This class contains an IP address in a platform and protocol independent manner. It stores both IPv4 and IPv6 addresses in a way that you can easily access on any platform.
QHostAddress is normally used with the classes QSocket, QServerSocket and QSocketDevice to set up a server or to connect to a host.
Host addresses may be set with setAddress() and retrieved with ip4Addr() or toString().
See also QSocket, QServerSocket, QSocketDevice, and Input/Output and Networking.
ip6Addr must be a 16 byte array in network byte order (high-order byte first).
Use toIPv4Address() instead.
Use isIPv4Address() instead.
Set the IPv6 address specified by ip6Addr.
ip6Addr must be a 16 byte array in network byte order (high-order byte first).
Sets the IPv4 or IPv6 address specified by the string representation address (e.g. "127.0.0.1"). Returns TRUE and sets the address if the address was successfully parsed; otherwise returns FALSE and leaves the address unchanged.
For example, if the address is 127.0.0.1, the returned value is 2130706433 (i.e. 0x7f000001).
This value is only valid when isIp4Addr() returns TRUE.
See also toString().
Q_IPV6ADDR addr = hostAddr.ip6Addr(); // addr.c[] contains 16 unsigned characters for (int i = 0; i < 16; ++i) { // process addr.c[i] }
This value is only valid when isIPv6Address() returns TRUE.
See also toString().
For example, if the address is the IPv4 address 127.0.0.1, the returned string is "127.0.0.1".
See also ip4Addr().
This file is part of the Qt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved. | http://idlebox.net/2007/apidocs/qt-x11-free-3.3.8.zip/qhostaddress.html | CC-MAIN-2014-15 | refinedweb | 275 | 70.8 |
Lab 4: Lists, and Data Abstraction
Due at 11:59pm on Friday, 07/12/2019.
Starter. = [[3, [5, 7], 9]]______x[0][1][1]
What would Python display? If you get stuck, try it out in the Python interpreter!
>>> lst = [3, 2, 7, [84, 83, 82]] >>> lst[4]______Error>>> lst[3][0]______84
Q2: Couple1, s2): """Return a list that contains lists with i-th elements of two sequences coupled together. >>> s1 = [1, 2, 3] >>> s2 = [4, 5, 6] >>> couple(s1, s2) [[1, 4], [2, 5], [3, 6]] >>> s3 = ['c', 6] >>> s4 = ['s', '1'] >>> couple(s3, s4) [['c', 's'], [6, '1']] """ assert len(s1) == len(s2)"*** YOUR CODE HERE ***"return [[s1[i], s2[i]] for i in range(0, len(s1))]
Use Ok to test your code:
python3 ok -q couple
Q3: Enumerate
Implement
enumerate, which pairs the elements of a sequence with their indices,
offset by a starting value.
enumerate takes a sequence
s and a starting value
start. It returns a list of pairs, in whichthe i-th element is
i + start
paired with the i-th element of
s. For example:
>>> enumerate(['maps', 21, 47], start=1) >>> [[1, 'maps'], [2, 21], [3, 47]]
Hint: Consider using
couplefrom Question 2!
Hint 2: You may find the built in range function helpful.
def enumerate(s, start=0): """Returns a list of lists, where the i-th list contains i+start and the i-th element of s. >>> enumerate([6, 1, 'a']) [[0, 6], [1, 1], [2, 'a']] >>> enumerate('five', 5) [[5, 'f'], [6, 'i'], [7, 'v'], [8, 'e']] """"*** YOUR CODE HERE ***"return couple(range(start, start+len(s)), s)
Use Ok to test your code:
python3 ok -q enumerate
City4: Distance1, city2): """ >>> city1 = make_city('city1', 0, 1) >>> city2 = make_city('city2', 0, 2) >>> distance(city1, city2) 1.0 >>> city3 = make_city('city3', 6.5, 12) >>> city4 = make_city('city4', 2.5, 15) >>> distance(city3, city4) 5.0 """"*** YOUR CODE HERE ***"lat_1, lon_1 = get_lat(city1), get_lon(city1) lat_2, lon_2 = get_lat(city2), get_lon(city2) return sqrt((lat_1 - lat_2)**2 + (lon_1 - lon_2)**2) # Video walkthrough:
Use Ok to test your code:
python3 ok -q distance
Q5: Closer city use your
distancefunction to find the distance between the given location and each of the given cities? ***"new_city = make_city('arb', lat, lon) dist1 = distance(city1, new_city) dist2 = distance(city2, new_city) if dist1 < dist2: return get_name(city1) return get_name(city2) # Video walkthrough:
Use Ok to test your code:
python3 ok -q closer_city
Q_abstraction
The
make_check.
Optional Question
This question can be found in
lab04_extra.py.
Q7: Squares only
Implement the function
squares, which takes in a list of positive integers.
It returns a list that contains the square roots of the elements of the original
list that are perfect squares. Try using a list comprehension.
You may find the
roundfunction useful.
>>> round(10.5) 10 >>> round(10.51) 11
def squares(s): """Returns a new list containing square roots of the elements of the original list that are perfect squares. >>> seq = [8, 49, 8, 9, 2, 1, 100, 102] >>> squares(seq) [7, 3, 1, 10] >>> seq = [500, 30] >>> squares(seq) [] """"*** YOUR CODE HERE ***"return [round(n ** 0.5) for n in s if n == round(n ** 0.5) ** 2]
It might be helpful to construct a skeleton list comprehension to begin with:
[sqrt(x) for x in s if is_perfect_square(x)]
This is great, but it requires that we have an
is_perfect_square
function. How might we check if something is a perfect square?
- If the square root of a number is a whole number, then it is a perfect square. For example,
sqrt(61) = 7.81024...(not a perfect square) and
sqrt(49) = 7(perfect square).
Once we obtain the square root of the number, we just need to check if something is a whole number. The
is_perfect_squarefunction might look like:
def is_perfect_square(x): return is_whole(sqrt(x))
- One last piece of the puzzle: to check if a number is whole, we just need to see if it has a decimal or not. The way we've chosen to do it in the solution is to compare the original number to the round version (thus removing all decimals), but a technique employing floor division (
//) or something else entirely could work too.
We've written all these helper functions to solve this problem, but they are actually all very short. Therefore, we can just copy the body of each into the original list comprehension, arriving at the solution we finally present.
Video walkthrough:
Use Ok to test your code:
python3 ok -q squares
Q8: Key of Min Value
The built-in
min function takes a.
def key_of_min_value(d): """Returns the key in a dict d that corresponds to the minimum value of d. >>> letters = {'a': 6, 'b': 5, 'c': 4, 'd': 5} >>> min(letters) 'a' >>> key_of_min_value(letters) 'c' """"*** YOUR CODE HERE ***"return min(d, key=lambda x: d[x])
Use Ok to test your code:
python3 ok -q key_of_min_value | https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab04/ | CC-MAIN-2020-29 | refinedweb | 820 | 68.91 |
Creating a CloudWatch Graph with a Search Expression
On the CloudWatch console, you can access search capability when you add a graph to a dashboard, or by using the Metrics view.
To add a graph with a search expression to an existing dashboard
Open the CloudWatch console at.
In the navigation pane, choose Dashboards and select a dashboard.
Choose Add widget.
Choose either Line or Stacked area and choose Configure.
On the Graphed metrics tab, choose Add a math expression.
For Details, enter the search expression that you want. For example,
SEARCH('{AWS/EC2,InstanceId} MetricName="CPUUtilization" ', 'Average', 300)
(Optional) To add another search expression or math expression to the graph, choose Add a math expression
(Optional) After you add a search expression, you can specify a dynamic label to appear on the graph legend for each metric. Dynamic labels display a statistic about the metric and automatically update when the dashboard or graph is refreshed. To add a dynamic label, choose Graphed metrics and then Dynamic labels.
By default, the dynamic values you add to the label appear at the beginning of the label. You can then click the Label value for the metric to edit the label. For more information, see Using Dynamic Labels.
(Optional) To add a single metric to the graph, choose the All metrics tab and drill down to the metric you want.
(Optional) To change the time range shown on the graph, choose either custom at the top of the graph or one of the time periods to the left of custom.
(Optional) Horizontal annotations help dashboard users quickly see when a metric has spiked to a certain level or whether the metric is within a predefined range. To add a horizontal annotation, choose Graph options and then Add horizontal annotation:
For Label, enter a label for the annotation.
For Value, enter box in the left column for that annotation.
To delete an annotation, choose x in the Actions column.
(Optional) Vertical annotations help you mark milestones in a graph, such as operational events or the beginning and end of a deployment. To add a vertical annotation, choose Graph options and then Add vertical annotation:
For Label, enter a label for the annotation. To show only the date and time on the annotation, keep the Label field blank.
For Date, specify the date and time where the vertical annotation appears.
For Fill, specify whether to use fill shading before or after a vertical annotation or between two vertical annotations. For example, choose
Beforeor
Afterfor the corresponding area to be filled. If you specify
Between, another
Datefield appears, and the area of the graph between the two values is filled.
Repeat these steps to add multiple vertical annotations to the same graph.
To hide an annotation, clear the check box in the left column for that annotation.
To delete an annotation, choose x in the Actions column.
Choose Create widget.
Choose Save dashboard.
To use the Metrics view to graph searched metrics
Open the CloudWatch console at.
In the navigation pane, choose Metrics.
In the search field, enter the tokens to search for: for example,
cpuutilization t2.small.
Results that match your search appear.
To graph all of the metrics that match your search, choose Graph search.
or
To refine your search, choose one of the namespaces that appeared in your search results.
If you selected a namespace to narrow your results, you can do the following:
To graph one or more metrics, select the check box next to each metric. To select all metrics, select the check box in the heading row of the table.
To refine your search, hover over a metric name and choose Add to search or Search for this only.
To view help for a metric, select the metric name and choose What is this?.
The selected metrics appear on the graph.
(Optional) Select one of the buttons in the search bar to edit that part of the search term.
(Optional) To add the graph to a dashboard, choose Actions and then Add to dashboard. | https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-search-expression.html | CC-MAIN-2019-35 | refinedweb | 675 | 64.51 |
My PowerShell prompt
3 min read
Today I took some time to work on my PowerShell configuration. Here is what it looks like now:
In case you already know about customizing the PowerShell, you can get the file here. If not, read on.
Shortening The Prompt
This is the default git shell prompt. As you can see, the path takes about 75% of the prompt’s width. Let’s change that.
Admittedly, until today I didn’t know a lot about PowerShell. So, after a bit research, I found an article on prompt shortening. The following two functions need to be placed into
%USERPROFILE%\Documents\WindowsPowerShell\GitHub.PowerShell_profile.ps1
function shorten-path([string] $path) { $loc = $path.Replace($HOME, '~') # remove prefix for UNC paths $loc = $loc -replace '^[^:]+::', '' # make path shorter like tabs in Vim, # handle paths starting with \\ and . correctly return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2') } function prompt { # write status string (-n : NoNewLine; -f : ForegroundColor) write-host 'PS' -n -f White write-host ' {' -n -f Yellow write-host (shorten-path (pwd).Path) -n -f White write-host '}' -n -f Yellow return ' ' }
shorten-path() takes care of shortening the path in a GVim manner and replacing the user profile path with a
~.
prompt() is a built-in function that is used to format the prompt.
Putting It Together
While this was working, it turned out that this got rid of the branch status. Luckily, someone wrote an article about displaying git data in the prompt. I spent a good hour playing around with the code and eventually I got PowerShell to display the data again.
function prompt { if(Test-Path .git) { # retrieve branch name $symbolicref = (git symbolic-ref HEAD) $branch = $symbolicref.substring($symbolicref.LastIndexOf("/") +1) # retrieve branch status $differences = (git diff-index HEAD --name-status) $git_mod_count = [regex]::matches($differences, 'M\s').count $git_add_count = [regex]::matches($differences, 'A\s').count $git_del_count = [regex]::matches($differences, 'D\s').count $" -n -f Yellow } else { # write status string write-host 'PS' -n -f White write-host ' {' -n -f Yellow write-host (shorten-path (pwd).Path) -n -f White write-host ">" -n -f Yellow } return " " }
##PowerShell Properties
If you right-click on the PowerShell menu bar, you will find a menu called
Properties. In there, you can change a few things that will make your work with the PowerShell a little easier.
Here are the properties I changed:
BufferSize: 500 QuickEditMode: true Font: Lucidas Console Font Size: 14 Screen Buffer Width: 100 Screen Buffer Height: 1000 Window Width: 100 Window Height: 54 | https://phansch.net/2012/10/01/my-powershell-prompt/ | CC-MAIN-2019-09 | refinedweb | 413 | 57.77 |
Google Chrome Drops H264 Support
The Google Chromium blog discussed the HTML Video Codec Support in Chrome, and announced that the WebM/VP8 codec will be part of HTML5's <video> tag support as well as Theora. However, the bombshell comment was:
Though H.264 plays an important role in video, as our goal is to enable open innovation, support for the codec will be removed and our resources directed towards completely open codec technologies.
The HTML5 specification cannot agree on a standard for video on the web, as open source foundations (like Mozilla) cannot afford the H264 licensing fees for the code, whilst Chrome supports both open-source and licensed software. Meanwhile, Apple is driving H264 adoption with its hardware and software choices and has no interest in supporting an open-source codec which may have patent issues surrounding it.
Until recently, Chrome was seen as best-of-both since the HTML5 video tag would support both WebM and H264 video. Unlike existing objects (which use a plug-in architecture to allow extension after the fact), the HTML5 video tag does not permit additional codecs to be installed. As a result, Firefox, Opera and (in the future) Chrome will be unable to see H264 encoded videos.
The reverse is also true; users of Safari or iPhone/iPod devices won't be able to see WebM encoded content – but since H264 is a widely used standard (it's the encoding used under the covers for Flash as well as Blu-Ray discs) the balance of video encoding is heavily in the H264 camp. Since there is less video available in WebM, there's less of a pressing reason to encode for it, which is why Chrome is making this change.
The hope is, by making Chrome only understand WebM encoded videos for the video tag (like Mozilla and Opera), Google will switch the balance of power to encourage the wider adoption of the WebM codec. The comments are highly polarised on the matter, with more against the move than for it:
-
This is a really poor decision for users and site designers alike. Right now I can encode video in one codec, H.264 and serve it to all modern browsers and mobile platforms, using either the video tag or a Flash wrapper.
If Chrome drops H.264 support from the video tag, then Chrome users will just get H.264 with a Flash wrapper. I'm not encoding in another codec. Peace.
- As a content publisher and developer using HTML , I'm taking this opportunity to make the necessary changes to my sites so that Chrome also gets the Flash plugin fallback that IE and Firefox get. Bandwidth is expensive, and h.264 is a miracle-worker in that regard.
-
Interesting move. IE9 will ship with h264 and webm support, while safari, flash, iOS devices, portable gaming devices, some consoles, and the majority of 3G-capable phones (see 3gpp standard) only handle h264 as a sane web video format.
Every platform which doesn't support h264 either ships with flash preinstalled, or has an install base of over 90%. Clearly, the format which has won is H264 - the single video format every browser supports, everywhere. This remains true until google retracts their recent statement on bundling Flash with Chrome.
The Flash issue is that despite dropping H264 support, Flash is still supported, which is a closed-source. Ironically, Flash is the best way of serving H264 video to browsers that don't have built-in support, so the majority of video publishers are just going to serve the same video content as a Flash object rather than transcoding.
- Let's be realistic here: Chrome is ~10% of the browser market. Their decision to support WebM over h.264 won't kill HTML5 . In fact, once fireFox 4 is released with WebM, the majority of users with non-beta browsers that support HTML5 video will be using WebM.
- It is a mistake to suggest this decision supports some nebulous "open source community". Google is making a choice here that supports the web. Anyone who thinks that h264 is free in any way is mistaken. Google seems to be taking a longer term view here, and should be applauded for accepting some short term pain in exchange for very real, very measurable long-term benefits.
- To those that are saying that it is a stupid move, you are the stupid ones. Me as a user, I want a one universal web browser codec. I don't want to switch to Google Chrome and then see that it cannot play the video that Firefox plays, or Safari. If all the browsers move to OGG Theora codec, it'll be legit, and will teach Apple a thing or two about the cost of licensing H.264 codec.
- The only reason to drop H264 is to hit iOS users in their faces, when Youtube drops H264. The war has already begone.
Whilst H264 is licensed, consumption of the video over the internet is free (and will be for the lifetime of the license), hardware and software decoders have fees associated with it. InfoQ have covered this before and the situation is unlikely to change; hardware device manufacturers will continue to build H264 support into products (since it's required for Blu-Ray players already). The ideological split has no common ground, which is why Chrome tried to appease both groups with dual support initially.
Ars Technica has generated a similar amount of comments on its story on Google removing H264 support from Chrome, though they also note:
Microsoft's substantial browser market share and the popularity of Apple's devices simply can't be ignored by the content producers. It's likely that many content producers will continue using H264 and will simply use Flash instead of the HTML5 video tag to display video content to browsers that don't natively support the H264 codec.
Whatever the outcome, Chrome dropping H264 support is unlikely to change the way producers generate content, even if the way they serve it does change. And with Android devices being able to run Flash, it seems that the hardware standard will remain H264 for some time to come.
This is a content battle, not a technology battle.
by
Clinton Begin
Apple has made some very hard plays. So let's not feel sorry for them here. It's time someone kicked them back.
Apple has dominated the music space and the rich mobile content (apps) space. This is clear. Apple is openly and fiercely competing against Google Android at every turn. And they are winning.
One area they have not yet dominated is video. Google owns social video via YouTube... nothing else comes close. And because the major content providers like Sony, Universal, Disney, Fox, NBC, ABC, CBS and others are so tightly restricted with regulations and copyrights, social video is really all that matters right now. If anything, the mobile carriers will own syndicated television and movie content through their various affiliations.
So this is Google's play to turn YouTube into a feature of Chrome and Android (and inherently PCs etc.). This is their punch in the face. In one move, Google can make it very hard for YouTube content to be available on iOS, iPhone, and iPad. All it would take is to support only Ogg and Flash on Youtube... nothing else. Apple could easily respond by suddenly offering support for either, and they would pretty much have to. This would wrestle away their control over the video codec space.
In a sense this is Google's only play, as Android Apps are finding it difficult to compete with the iTunes App Store, nor do they have any equivalent to iTunes Music Store.
Thus YouTube becomes iTunes for Android, only for social video. This is only step one though... Android has a lot of catching up to do.
The wildcards in this space are Adobe and Microsoft.
Despite all of the bad press Adobe received in the past 12 months, Flash continues to dominate, and is more than just video. The Flash SDKs currently offer a unified platform for Android, Playbook, Web, Desktop Windows, Linux and Mac (AIR) -- it's everything Java ever wanted to be on the client side.
Microsoft on the other hand, dumped their rising and increasingly successful Silverlight on the web to focus it strictly on Windows Mobile 7, and thus left the market wide open for Flash to continue to dominate. Shortly after Microsoft and Adobe seemed to have a lot of talking to do, and IE9 beta came with a preview of Flash with hardware acceleration. It would seem that there's a lot of cooperation between the two. Yet there's no flash on WM7 yet.
To me, although expensive, Adobe is a perfect acquisition target for either Google or Microsoft
Google could easily use it as a replacement platform for the next Android -- migrating Java apps to AS3 apps is fairly straightforward given that the language syntax is very similar and the Android SDK APIs are proprietary (not standard Java) anyway. Furthermore, this could get Google away from Java and thus away from Oracle. Furthermore, Flash seems to be a popular selling point for Android phones and tablets.
On the other hand, Microsoft could use Adobe too. Mostly just because they don't have a dominant play in anything else, and this would give them one, at least for a short time. Most importantly, they would keep it away from Google and Android, and perhaps just use it as leverage to further their Windows Mobile 7 platform, as well as the rich web. Even though Microsoft supports H264, I don't think that's relevant. There's far more at play here than a video codec.
At the end of the day, H264 as a technology doesn't matter. What matters is the content (music, video and apps), who controls it, and how the technology can be used to limit the availability of the content to the advantage of a given platform.
2011 will be an interesting year.
Re: This is a content battle, not a technology battle.
by
chen chuan
1. Flex is hard to learn.
2. Flex is difficault for GUI team to do look and feel design. Change layout messed with changing AS3 code.
3. Flex has so many namespaces to work with, difficault to find which one to use for a novice.
Correct me if I am wrong.
--A novice to Flex.
Re: This is a content battle, not a technology battle.
by
Gavin Siller
1) Learning Flex is not trivial but is definitely worthwhile for a rich UI.
2) Using the "code behind"/ MVP pattern we were able to allow for separation of responsibilities between front end and business logic developers.
3) Reading, coding, making mistakes, reading, fixing. It's what we do for a living.
All that being said, HTML5 is going to change things. Our solution was built a while ago (still in production, latest version of Flex and AIR now) when a very rich UI and an occasionally connected client were critical success factors.
Interesting times (as always)
Re: This is a content battle, not a technology battle.
by
Clinton Begin
But personally I think AS3 - just the language - is better than Java and JavaScript (as in cleaner and more enjoyable to work in).
Flex is better than Swing for sure -- in every conceivable way. It's also on par with WinForms as a desktop application solution, but has the added bonus of being cross platform.
But you can't really compare Flex to HTML, as it should be used to solve almost entirely different problems. Flex is great where you would consider Swing or WinForms, and it compares on that level. But Flex should not be compared to HTML. If your building a web application, and can do it with HTML, you should. The major reason is end-user experience. Flex is not "web like".
That said, regarding Android, I was not talking about Flex... that would be tragic on Android. On Android I think a custom Android UI/component framework specifically for Android could be very successful.
Clinton
Re: This is a content battle, not a technology battle.
by
Kra Larivain
Even though the two languages look close, as3 lacks a few features widely use by java developpers:
- no equals method defined on object. This is a *big* pain to workaround, believe me,
- no method overloading
- no private constructor
- no block level definition of variables.
- flash is single threaded by design. This is very important as it is too easy to block the main ui thread with processing or big request
Porting from one to another is possible, but not straightforward. | http://www.infoq.com/news/2011/01/chrome-h264 | CC-MAIN-2015-11 | refinedweb | 2,133 | 71.14 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, nice to meet you.
Processing 3.2.1. Android Mode 3.0.1
======================================================================
import io.inventit.processing.android.serial.*; //ANDROID Serial myPort; String inString=""; void setup() { myPort = new Serial(this, Serial.list(this)[0], 38400); myPort.bufferUntil(10); } //===========INCOMING DATA FROM THERMOSTAT============= void serialEvent(Serial myPort) { try { inString = myPort.readString(); } catch(RuntimeException e) { } }
====================================================================== **Error msg : **
Answers
What am I doing wrong?
Let me know what went wrong. Help.
I've never used direct otg usb connection, because my kitkat device didn't support it. (only 5.1 and above.) , I only use bluetooth. But ofcourse you are using the same boudrate 38400 in your ino sketch? How do you know that the port really is the the first [0]?
@noel
I think [0] is right. Because there is no other device.
I do not know why the OTG USB library does not work.
What do you mean by > API 6.0? You are aware that this lib only support Api level 21 and above? I don't now how this works in Android, but in Windows it can assign any number far higher then number of devices like 45 or whatever. Isn't there within the lib a function that list the ports in the console?
@noel
1) Api level 21 UP // right
2) In the print statement, there is no serial list at all. | https://forum.processing.org/two/discussion/26750/android-mode-serial-communication-andruino | CC-MAIN-2019-35 | refinedweb | 246 | 78.55 |
.
PySide in FreeCAD with Qt5
FreeCAD was developed to be used with Python 2 and Qt4. As these two libraries became obsolete, FreeCAD transitioned to Python 3 and Qt5. In most cases this transition was done without needing to break backwards compatibility.
Normally, the
PySide module provides support for Qt4, while
PySide2 provides support for Qt5. However, in FreeCAD there is no need to use
PySide2 directly, as a special
PySide module is included to handle Qt5.
This
PySide module is located in the
Ext/ directory of an installation of FreeCAD compiled for Qt5.
/usr/share/freecad/Ext/PySide
This module just imports the necessary classes from
PySide2, and places them in the
PySide namespace. This means that in most cases the same code can be used with both Qt4 and Qt5, as long as we use the single
PySide module.
PySide2.QtCore -> PySide.QtCore PySide2.QtGui -> PySide.QtGui PySide2.QtSvg -> PySide.QtSvg PySide2.QtUiTools -> PySide.QtUiTools
The only unusual aspect is that the
PySide2.QtWidgets classes are placed in the
PySide.QtGui namespace.
PySide2.QtWidgets.QCheckBox -> PySide.QtGui.QCheckBox).
- | https://wiki.freecadweb.org/index.php?title=PySide/cs&oldid=785439 | CC-MAIN-2022-21 | refinedweb | 180 | 55.03 |
- Code: Select all
def cut(path):
newList = []
n = 0
#test = getUnitTest(path)
test =str(foundfiles[n])
for lines in foundfiles[n]:
if not test.endswith('.UnitTests.vbproj'):
print test
n=n+1
else:
if test.endswith('.UnitTests.vbproj'):
del test
n=n+1
return newList
It doesn't go to every item in the list, it stop after about 3 iterations when there are over 25 in the list. The items in the list are as of this format: blah.blah.blah.UnitTests.vbproj with sometimes more after the vbproj part. I just can't get it looping right. any help would be greatly appreciated, and thank you in advance! | http://www.python-forum.org/viewtopic.php?p=3790 | CC-MAIN-2016-36 | refinedweb | 110 | 75.5 |
Name | Synopsis | Interface Level | Parameters | Description | Return Values | Context | Examples | See Also
#include <sys/stream.h> int putnextctl(queue_t *q, int type);
Architecture independent level 1 (DDI/DKI).
Queue to which the message is to be sent.
Message type (must be control, not data type).
The putnextctl() function tests the type argument to make sure a data type has not been specified, and then attempts to allocate a message block. putnextctl() fails if type is M_DATA, M_PROTO, or M_PCPROTO, or if a message block cannot be allocated. If successful, putnextctl() calls the put(9E) routine of the queue pointed to by q with the newly allocated and initialized messages.
A call to putnextctl(q,type) is an atomic equivalent of putctl(q->q_next,type). The STREAMS framework provides whatever mutual exclusion is necessary to insure that dereferencing q through its q_next field and then invoking putctl(9F) proceeds without interference from other threads.
The putnextctl() function should always be used in preference to putctl(9F)
On success, 1 is returned. If type is a data type, or if a message block cannot be allocated, 0 is returned.
The putnextctl() function can be user, interrupt, or kernel context.
The send_ctl routine is used to pass control messages downstream. M_BREAK messages are handled with putnextctl( ) (line 8). putnextctl1(9F) (line 13) is used for M_DELAY messages, so that parm can be used to specify the length of the delay. In either case, if a message block cannot be allocated a variable recording the number of allocation failures is incremented (lines 9, 14). If an invalid message type is detected, cmn_err(9F) panics the system (line 18).
1 void 2 send_ctl(queue_t *wrq, uchar_t type, uchar_t parm) 3 { 4 extern int num_alloc_fail; 5 6 switch (type) { 7 case M_BREAK: 8 if (!putnextctl(wrq, M_BREAK)) 9 num_alloc_fail++; 10 break; 11 12 case M_DELAY: 13 if (!putnextctl1(wrq, M_DELAY, parm)) 14 num_alloc_fail++; 15 break; 16 17 default: 18 cmn_err(CE_PANIC, "send_ctl: bad message type passed"); 19 break; 20 } 21 }
put(9E), cmn_err(9F), datamsg(9F), putctl(9F), putnextctl1(9F)
STREAMS Programming Guide
Name | Synopsis | Interface Level | Parameters | Description | Return Values | Context | Examples | See Also | http://docs.oracle.com/cd/E19082-01/819-2256/6n4icm0un/index.html | CC-MAIN-2017-04 | refinedweb | 359 | 54.42 |
Wikibooks talk:Naming conventions
From Wikibooks, the open-content textbooks collection
I disagree with this system. I much prefer the Book:Title system for naming articles. There shouldn't be that many modules in a book that you'd need a 4X hierarchy. Gentgeen 11:17, 31 Jan 2004 (UTC)
[edit] interwiki
Doesn't the : seperater create a problem for inter wiki? Lets say I write a book on wikipedia, the chapters would be called wikipedia:something. This goes to wikipedia article something insted of the chapter on something. With interwiki growing and the likelyhood of a wiki named the same as a book growing, this may be a bad practice.
Yes, good point. I agree. Dan_AKA_Jack 17:10, 7 Jan 2005 (UTC)
- I agree. We should be using subpages, but they are not enabled on the main namespace. Please, read my opinion about this topic on m:Wikibooks should use subpages. ManuelGR 13:26, 16 Jan 2005 (UTC)
[edit] subpages
Now we have subpages, I recommend using them. ManuelGR 18:17, 29 Jan 2005 (UTC)
- Do we agree on using subpages? If yes, we could put the recommendation on the "about" page itself, placed prominently on top, instead of recommending it only on the "talk" page and listing it as one of many many options. Is there a clear community opinion about this point already? Most of the new books still use the "booktitle:name" convention. I guess newcomers would also be happy about a clear directive for the future. (That does not mean that all existing books should be converted, but some would benefit.)
- I would recomment:
- Booktitle/chapterdescription
- that is, only one layer of subpages, and use the description of the content instead of the chapter number (which would make including new chapters hard) --Andreas 14:13, 12 Mar 2005 (UTC)
- While I am in favor of Sub-Pages I may ask: Is there actualy a way of converting pages without leaving hundreds of move pages. i.E. Ada has about 103 pages - I would not want to convert that by hand. --Krischik 16:06, 12 Mar 2005 (UTC)
- Would using subpages apply just to textbooks or to everything? I wouldn't want to see Cookbook/Rice pudding, for example, but Biology/Chapter 3 is fine. TUF-KAT 16:25, 12 Mar 2005 (UTC)
- I don't see any difference between the two, but I think that the first decission to take is wether to give a clear recommendation for new books to use subpages. I think we should. For current books, that is another issue, probably the best approach is to start promoting subpages and let the authors decide whether to change or maintain their current convention. Only if the new convention is widely accepted then we can regard it as a new policy. ManuelGR 00:09, 13 Mar 2005 (UTC)
- I still think that there may be more benefits to real namespaces for books. Other wiki software packages provide namespace specific recent changes, searches, stylesheets, etc. I can see a lot of benefits for each book operating as its own somewhat independent wiki. The only benefit right now for subpages is the automatic linkback to the main page. I have no objection to them being used, but to suggest that all new pages and books be forced to use them is simply not a good idea. Gentgeen 01:40, 13 Mar 2005 (UTC)
- The mediawiki software currently only allows for 256 different namespaces (it is a TINYINT(2) variable in the SQL database), so the number of books getting the real benefit out of it would be comparatively small. I think, a mixed approach would be best: For the majority of small and medium-sized books subpages are the optimal thing to do, large projects, like "Cookbook:" or "Programming:" could have their own name-space if desired. Let us move the further discussion to Wikibooks:Hierachy_naming_scheme.--Andreas 06:47, 13 Mar 2005 (UTC)
[edit] Real-Namespaces
Just a thought: while 256 Real-Namespaces are not enough for all the books - they would be enough for Bookshelfes.
--Krischik 06:49, 4 August 2005 (UTC)
Adding a new namespace requires minor changes to the software, or at least done on a developer level (developers also tend to be very Wikipedia-centric, and thus developments that would greatly help Wikibooks, eg. a way in the software to tell what book a given module is a part of, are held on the back burner). There was a large movement in the past of moving Cookbook and Programming (among others) to separate namespaces, but that idea largely died out - the idea however did transform into the ":" delimiter in WB:NC. As for bookshelves, part of the bookshelf overhaul was that they'd be moved under the Wikibooks namespace, to reserve the main module space for actual books. The bookshelves merely serve as an informal way of organizing books that exist. There are plans to have bookshelf management placed under the Wikibooks:Card Catalog Office, but this is a very new idea that is in serious need of discussion. KelvSYC 08:04, 4 August 2005 (UTC)
- Using real namespaces would make it more difficult to move books between bookshelves, should the scope of those bookshelves evolve. The current POV in the CCO-project is to use Categories as much as possible. This way we can classify books not only by our bookshelves, but also by Dewey codes and Library of Congress codes (and anything else we might want to add in later). To change a book's classification would be a simple as changing a single parameter of a template to be included on the book's main page. - Aya T C 19:43, 4 August 2005 (UTC)
[edit] Template naming conventions
moved to Wikibooks talk:Naming policy#Template naming conventions
[edit] category guidelines
Are there any tips or guidelines for using category tags? (A category tag starts with "
[[Category:", then the name of the tag, then ends with "
]]". When a reader clicks on the tag, wikibooks automagically makes a list of every module that includes that tag -- this is often much more convenient than manually creating and maintaining such a list.)
Such category guidelines would say something like
- make sure the category tag "
[[Category:Programming]]" is on the "main module" of a programming language book, but no other module of the book. For example, you would put it on "C Programming", but not on "C Programming/Control".
- Put the book-specific category tag on every module and template used in the book. For example, you would put the category tag "
Category:C Programming" on both modules "C Programming" and "C Programming/Control", but not on any modules in any other book.
- make sure the category tag "
[[Category:Programming]]" is on the book-specific category page. For example, you would put it on the "
Category:C Programming" category page.
- It's fine to have a module or template have several different category tags. In particular, if a template is used in multiple books, put the book-specific category tag from each of those books on that template.
Is there a page for holding guidelines like this?
By the way, what is the difference between "
[[:Category:Programming]]" and "
[[:Category:Programming languages]]"?
--DavidCary 18:37, 2 December 2006 (UTC)
- Hi David - you are so right (in my view) to bring this up. It's one that has been lurking in my mind for a while now. I see categories as very important and quite often badly handled. That said you are posting this in quite a remote backwater of Wikibooks which will probably not be seen by many. If you want to go to Category talk:Main page I promise I'll join it the conversation there (tho it will be tomorrow it being late in my timezone!). Browsing Category:Main page will give you some idea how good and bad things can be - personally the Wikijunior section is pretty good but the rest ...
- Hopefully see you there and get some discussion going about an important topic. Regards --Herby talk thyme 19:12, 2 December 2006 (UTC) | http://en.wikibooks.org/wiki/Wikibooks_talk:Naming_conventions | crawl-002 | refinedweb | 1,354 | 60.14 |
MemCache++ is a light-weight, type-safe, simple to use and full-featured Memcache client.
It was developed by Dean Michael Berris who is a C++ fanatic, loves working on network libraries (cpp-netlib.github.com), and currently works at Google Australia. He also is part of the Google delegation to the ISO C++ Committee. You can read more of his published works at deanberris.github.com and his C++ blog at.
Studying the well designed libraries is recommended to master C++ concepts, and the goal of this article is to discover some memcache++ design choices that makes it easy to understand and use.
Let’s discover the memcache++ design by analyzing it with CppDepend.
Namespace Modularity
Namespaces represents a good solution to modularize the application, unfortunately this artifact is not enough used in the C++ projects, just a look at a random open source C++ projects show us this fact.And more than that when We search for C++ namespace definition the common one is like that:
"A namespace defines a new scope. Members of a namespace are said to have namespace scope. They provide a way to avoid name collisions."
Many times the collision is shown as the first motivation, and not the modularity unlike for C# and Java where namespaces are more quoted to modularize the application.
However Some modern C++ libraries like boost use the namespaces to structure well the library and encourage developers to use them.
What about the namespace modularity of memcache++?
Here’s the dependency graph between memcache++ namespaces:
The namesapces are used for two main reasons:
- Modualrize the library.
- Hide details like “memcache::detail” namespace, this approach could be very interesting if we want to inform the library user that he dont need to use directly types inside this namesapce. For C# the “internal” keyword did the job, but in C++ there’s no way to hide public types to the library user.
memcache++ exploit gracefully the namespace concept,however a dependency cycle exist between memcache and memcache::detail.We can remove this dependency cycle by searching types used by memcache::detail from memcache.
For that we can execute the following CQlinq request:
from t in Types where t.IsUsedBy(“memcache.detail”) && t.ParentNamespace.Name==“memcache”
select new { t,t.TypesUsingMe }
Here’s the result after executing the request:
To remove the dependency cycle we can move pool_directive and server_pool_test to memcache.
Generic or OOP?
In the C++ world two schools are very popular : Object Oriented Programming and Generic programming, each approach has their advocates, this article explain the tension between them.
What the approach used by memcache++?
To answer this question Let’s search first for Generic types:
from t in Types where t.IsGeneric && !t.IsThirdParty select t
What about the not generic ones:
from t in Types where !t.IsGeneric && !t.IsGlobal && !t.IsNested && !t.IsEnumeration && t.ParentProject.Name==”memcache”
select t
Almost all not generic types concern exception classes, and to have a better idea of their use proportion, the treemap view is very useful.
The blue rectangles represents the result of the CQLinq query, and as we can see only a minimal part of the libray concern the not generic types.
Finally we can search for generic methods:
from m in Methods where m.IsGeneric && !m.IsThirdParty select m
As we can observe memcache++ use mostly generics, but it’s not sufficient to confirm that it follow the C++ generic approach.To check that a good indicator is the use of inheritence and dynamic polymorphism, indeed OOP use them mostly , however for the generic approach using inheritence is very limited and the dynamic polymorphism is avoided.
Let’s search for types having base classes.
from t in Types where t.BaseClasses.Count()>0 && !t.IsThirdParty && t.ParentProject.Name==“memcache”
select t
It’s normal that exceptions classes use inheritence but what about the other classes? did they use inheritence for dynamic polymorphism purpose? to answer this question let’s search for all virtual methods.
from m in Methods where m.IsVirtual select m
Only exception class has a virtual method, and for the other few classes using inheritence the main motivation is to reuse the code of the base class.
If the dynamic polymorphism is not used, what’s the solution adopted if we need another behavior for a specific classes?
The common solution for the generic approach is to use Policies.Here’s a short definition from wikipedia
memcache++ has many policies inside memcache.policies namespace.
Let’s discover an example from memcache++ to understand better the policy based design.
memcache++ use the type basic_handle to implement all commands like add, set, get and delete from the cache.This class is defined like that:
template <
class threading_policy = policies::default_threading,
class data_interchange_policy = policies::binary_interchange,
class hash_policy = policies::default_hash
>
struct basic_handle
The memcache++ is thread safe and for the multithreaded context have to manage synchronisation, by default the threading_policy is “default_threading” where no special treatement is added, however for multithreading the policy used is “boost_threading”.
Let’s take a look to connect method implementation.
void connect(boost::uint64_t timeout = MEMCACHE_TIMEOUT) {
typename threading_policy::lock scoped_lock(*this);
for_each(servers.begin(), servers.end(), connect_impl(service_, timeout));
};
If threading_policy is “default_threading” , the first line has no effect because the lock constructor did nothing, however if it’s the boost_threading one, lock use boost to synchronize between threads.
Using policies give us more flexibility to implement different behaviors, and it’s not very difficult to understand and use.
Generic Functors
memcache++ implement many commands to interact with the cache like add,get,set and delete.The command pattern is a good candidate for such case.
memcache++ implement this pattern by using generic functors, here’s a CQLinq queries to have all functors:
from t in Types where t.Methods.Where(a=>a.IsOperator && a.Name.Contains(“()”)).Count()>0
select t
Functor encapsulate a function call, with its state, and it can be used to defer call to a later times, and act as callback.Generic functors gives more flexibility to normal functors.
Interface exposed
How the library expose it’s capabilities is very important, it impact its flexibility and its easy of use.
To discover that let’s search for the communication between the test project and the memcache++ library.
from m in Methods where m.IsUsedBy (“test”)
select m
test project use mainly generic methods to invoke memcache++ functionalities. What the benefits using template methods , why not use classes or functions?
For POO approach the library interface is composed of classes and functions, and for well designed ones Abstract classes are used as contracts to enforce low coupling, this solution is very interesting but have some drawbacks:
- The interface become more complicated and can change many times: to explain that let’s take as example the add method exposed by memcache++, if we dont use generic approach many methods must be added, each one for a specific type int,double,string,…
However the generic add method is declared like that add<T> where T is the type, and in this case we need only one method, and even we want to add another type no change requiered in the interface.
- The interface is less flexible: if for example we expose a method like this
calculte(IAlgo* algo).
The user must give a class inhereting from IAlgo , however if we use generic and define it like that calculate<T> , the user have only to provide a class with methods needed and not necessarilly inherit from IAlgo, and if IAlgo change to IAlgo2 because some methods are added , the user of this library will not be impacted.
Ideally the interface exposed by a library must not have any breaking changes, and the user have not to be impacted when changes are introduced in the library. generic approach is the most suitable for such constraints because it’s very tolerent when changes are needed.
External API used
Here are the external types used by memcache++
memcache++ use mostly boost and STL to acheive its needs,here are some boost features used:
- multithreading
- algorithm
- spirit
- asio
- unit testing
and of course the well known shared_ptr for RIIA idiom.
And for STL the containers are mostly used.
So finally what The advantages using the generic approach?
- The first indicator of the efficency of memcache++ design choices is the Line number of code(LOC) where is only arround 600 lines of code, this result is due to two main reasons:
– using generic approach remove boilerplate code.
– using the richness of boost and stl.
- The second force is it’s flexibiliy , and any changes will impact only a minimal portion of code.
Drawbacks of using this kind of approach:
many developers found that the generic approach is very complicated , and understanding the code become very difficult.
What’s to do? use or not the generic approach?
if it’s very difficult to design an application with this appraoch ,but it’s more easy to use librairies using it, like using STL or boost.
So even if we want to avoid the risk of designing the application with the modern approach, it will be a good idea to use libraries like STL or. | http://www.codeproject.com/Articles/463907/MemCacheplusplus-An-example-of-modern-Cplusplus-de | CC-MAIN-2015-35 | refinedweb | 1,533 | 52.39 |
Ever seen a hard-to-parse conditional like this?
def allow_access_to_site? ! (signed_out? && untrusted_ip?) end
Let’s use De Morgan’s Laws to clean it up and see who actually has access to our site.
De Morgan’s Laws
Whoa, who’s this De Morgan guy? Augustus De Morgan, in addition to looking like a 19th-century John C. Reilly, formulated two important rules of logical inference. You can check out the formal definition on the Wikipedia page, but here they are in Ruby code:
# First law !(a && b) == !a || !b # Second law !(a || b) == !a && !b
Well hey, it looks like we can use these on our gnarly conditional above. Let’s try it.
Law-abiding Ruby code
Recall that the original conditional was
! (signed_out? && untrusted_ip?).
Let’s use the first law and puzzle it out.
# Original ! (signed_out? && untrusted_ip?) # Conversion using first law. I've added parentheses for clarity. # a = signed_out? # b = untrusted_ip? (! signed_out?) || (! untrusted_ip?)
Here I notice that
! signed_out? and
! untrusted_ip? are double negatives:
not signed out, not untrusted IP. Now what they’re really trying to say
is: signed in, trusted IP. Let’s simplify further, using better method
names.
# Simplify a: (! signed_out?) == signed_in? (signed_in?) || (! untrusted_ip?) # Simplify b: (! untrusted_ip?) == trusted_ip? (signed_in?) || (trusted_ip?) # Remove parentheses signed_in? || trusted_ip?
These methods,
signed_in? and
trusted_ip?, might exist and they might not.
Creating them is part of this refactoring. You might even end up removing the
signed_out? and
untrusted_ip? methods in favor of these new,
positively-named methods.
And that’s it. We took a hard-to-parse conditional and made it clearer and easier-to-read using De Morgan’s first law.
Before:
def allow_access_to_site? ! (signed_out? && untrusted_ip?) end
After:
def allow_access_to_site? signed_in? || trusted_ip? end
What’s next
If you found this useful, you might also enjoy: | https://robots.thoughtbot.com/clearer-conditionals-using-de-morgans-laws | CC-MAIN-2018-22 | refinedweb | 294 | 69.99 |
Though this problem seems complex, the concept behind this program is straightforward; display the content from the same file you are writing the source code.
In C programming, there is a predefined macro named
__FILE__ that gives the name of the current input file.
#include <stdio.h> int main() { // location the current input file. printf("%s",__FILE__); }
C program to display its own source code
#include <stdio.h> int main() { FILE *fp; int c; // open the current input file fp = fopen(__FILE__,"r"); do { c = getc(fp); // read character putchar(c); // display character } while(c != EOF); // loop until the end of file is reached fclose(fp); return 0; } | https://cdn.programiz.com/c-programming/examples/source-code-output | CC-MAIN-2020-40 | refinedweb | 108 | 71.85 |
Most issues that I see have to do with code organization.
- `using namespace` in non-local scope is a shooting offense. You put it in a HEADER. Code police is on its way. Please assume the position.
- Global variables are a no-no. I could understand global `Objects` but global iterators? Whoa...
- Whenever possible, prefer range-for to iterators when working with std containers. It makes for a much cleaner code and you don't have to keep coming up with a name for each iterator. ;)
- `auto` is your new best friend. Use it wherever possible.
- Consider encapsulating each logical part of the update loop in a "system". A function, f.ex. `doDeadCulling(std::list<GameObject>& objects)` would do the trick.
- Two-phase initialization is not necessary in your case. Have your `Player` and `Enemy` call `GameObjects` constructor with appropriate parameters as the first statement in their respective constructors.
- Base class destructors must be marked virtual, else nasal demons. This applies to every class that will be inherited from. Not just the class at the root of hierarchy. In your case, `GameObjects`'s destructor is in error.
- Your `GameObject` is responsible for way too much. There are two possible ways to deal with this. Classic way would be to split it into various abstract base classes, f.ex. `Drawable` and `Collidable`, and have your `Player` and `Enemy` multiply-inherit from those. Modern approach would be to use a Entity Component System (ECS). It has many advantages over the classic aproach. Your favorite search engine should give you a couple of good hits.
- You lose a game vs. your pants are loose.
I'm happy to expand on these points if you have questions.
Thank you so much!
ive copied your post to my ToDo list and will start working on them later today. | http://www.gamedev.net/user/209243-naughtyusername/?tab=posts&setlanguage=1&langurlbits=user/209243-naughtyusername/&tab=posts&langid=1 | CC-MAIN-2016-30 | refinedweb | 303 | 70.7 |
dynamic, self-adjusting array of char More...
#include <vtkCharArray.h>
dynamic, self-adjusting array of char
vtkCharArray is an array of values of type char. It provides methods for insertion and retrieval of values and will automatically resize itself to hold new data.
Definition at line 38 of file vtkCharArray.h.
Definition at line 41 of file vtkCharAbstractArray.
A faster alternative to SafeDownCast for downcasting vtkAbstractArrays.
Definition at line 58 of file vtkCharArray.h.
Get the minimum data value in its native type.
Definition at line 66 of file vtkCharArray.h.
Get the maximum data value in its native type.
Definition at line 71 of file vtkCharArray.h. | http://www.vtk.org/doc/nightly/html/classvtkCharArray.html | CC-MAIN-2017-30 | refinedweb | 108 | 53.68 |
CPSC 124, Winter 1998
Sample Answers to Lab 4
This page contains sample answers to the exercises from Lab #4 in CPSC 124: Introductory Programming, Winter 1998. See the information page for that course for more information.
Exercise 1: The problem was to add a number of subroutines, and a few other changes, to an existing program. A sample completed program is:public class ThreeNumberCalculator { // The program allows the user to enter a command such as "sum" // followed by three numbers. It then applies the command to // the three numbers and outputs the result. This is repeated // until the user enters "end". // // Supported commands are: sum, mul, max, min, and mid. // // by David Eck static Console console; // Console window for input/output public static void main(String[] args) { console = new Console("Three Number Calculator"); console.putln("Welcome to a simple calculator program that can apply"); console.putln("Several basic operations to three input numbers."); console.putln("This program understands commands consisting of a word"); console.putln("followed by three numbers. For example: sum 3.5 -6 4.87"); console.putln("Commands include:"); console.putln(" sum -- find the sum of three numbers"); console.putln(" prod -- find the product number"); console.putln(" min -- find the smallest number"); console.putln(" max -- find the largest number"); console.putln(" mid -- find the middle number"); console.putln(" end -- quit the program"); while (true) { console.putln(); console.put("COMMAND>> "); String command = console.getWord(); // get command word entered by user if (command.equalsIgnoreCase("end")) break; double firstNum = console.getDouble(); // get three numbers entered by user double secondNum = console.getDouble(); double thirdNum = console.getDouble(); console.getln(); // read the end-of-line if (command.equalsIgnoreCase("sum")) { // do "sum" command printSum(firstNum, secondNum, thirdNum); } else if (command.equalsIgnoreCase("prod")) { // do "prod" command printProduct(firstNum, secondNum, thirdNum); } else if (command.equalsIgnoreCase("min")) { // do "min" command printMin(firstNum, secondNum, thirdNum); } else if (command.equalsIgnoreCase("max")) { // do "max" command printMax(firstNum, secondNum, thirdNum); } else if (command.equalsIgnoreCase("mid")) { // do "mid" command printMiddle(firstNum, secondNum, thirdNum); } else { console.putln("Sorry, I can't understand \"" + command + "\"."); } } // end of while loop console.putln(); console.putln("Bye!"); console.close(); } // end of main() static void printSum(double x, double y, double z) { // This method computes the sum of its three parameters, // x, y, and z. It outputs the answer to the console. double sum; // The sum of the three parameters. sum = x + y + z; console.putln("The sum of " + x + ", " + y + ", and " + z + " is " + sum); } // end of printSum() static void printProduct(double x, double y, double z) { // This method computes the product of its three parameters, // x, y, and z. It outputs the answer to the console. double prod; // The product of the three parameters. prod = x * y * z; console.putln("The product of " + x + ", " + y + ", and " + z + " is " + prod); } // end of printProduct() static void printMax(double x, double y, double z) { // This method finds the largest of its three parameters, // x, y, and z. It outputs the answer to the console. double max; // The largest of the three parameters. max = x; if (y > max) max = y; if (z > max) max = z; console.putln("The maximum of " + x + ", " + y + ", and " + z + " is " + max); } // end of printMax() static void printMin(double x, double y, double z) { // This method finds the smallest of its three parameters, // x, y, and z. It outputs the answer to the console. double min; // The smallest of the three parameters. min = x; if (y < min) min = y; if (z < min) min = z; console.putln("The minimum of " + x + ", " + y + ", and " + z + " is " + min); } // end of printMin() static void printMiddle(double x, double y, double z) { // This method finds the median of its three parameters, // x, y, and z. It outputs the answer to the console. double mid; // The median of the three parameters. if ( (x <= y && y <= z) || (x >= y && y >= z) ) mid = y; else if ( (y <= x && x <= z) || (y >= x && x >= z) ) mid = x; else mid = z; console.putln("The median of " + x + ", " + y + ", and " + z + " is " + mid); } // end of printMiddle() } // end of class ThreeNumberCalculator
Exercise 2: The exercise was to write a program to find the maximum number of divisors for any number between 1 and 10000, and to print out all the numbers that have that maximum number of divisors. The answer is that the number of divisors is 64. The numbers in the range 1 to 10000 that have 64 divisors are 7560 and 9240. Here is a sample solution:public class ConsoleApplication { // This program will count the number of divisors for each integer // between 1 and MAX (where MAX is the constant given below). It will // find the maximum number of divisors. It will then print out the // maximum and all the numbers, N, between 1 and MAX that have that // maximum number of divisors. // // by David Eck static final int MAX = 10000; // upper limit on numbers for which // divisors will be counted static Console console = new Console(); // window for I/O public static void main(String[] args) { int maxDivisors = 1; // maximum number of divisors seen for (int N = 2; N < MAX; N++) { // check number of divisors of N int divisors = numberOfDivisors(N); if (divisors > maxDivisors) maxDivisors = divisors; } // at this point, maxDivisors is the maximum number of divisors for // any number between 1 and MAX. console.putln("For numbers between 1 and " + MAX + ","); console.putln("the maximum number of divisors is " + maxDivisors); console.putln("It occurs for:"); // Now go through all the numbers, N, between 1 and MAX, and output // N if the number of divisors of N is equal to the maximum number for (int N = 2; N < MAX; N++) { int d = numberOfDivisors(N); if (d == maxDivisors) { console.putln(" N = " + N); } } console.close(); } // end main() static int numberOfDivisors(int N) { // This routine counts the number of integers of integers, D, between // 1 and N such that D evenly divides N. int ct = 0; // The number of divisors found. for (int D = 1; D <= N; D++) if (N % D == 0) ct++; return ct; } // end numberOfDivisors() } // end class ConsoleApplication
Exercise 3: "Subroutines are components of programs that can be developed, written, and tested separately."
Because a subroutine is a black box, it interacts with the rest of the program only though its "interface," that is, its name and parameter list. The inside of the subroutine, its "implementation," is dependent of the main program. The subroutine has a certain task to perform. As long as it accomplishes that task correctly, the particulars of how it is written don't really matter.
This means that the problem of writing the main program is separate from the problem of writing the subroutines used by the main program. And each subroutine is its own, independent problem. The overall design of the main program tells you what the subroutine has to do. You can write a subroutine to perform that test, and test the subroutine by calling it from a very simple main program whose only purpose is to test the subroutine. Once the subroutine is written, it can be incorporated into the rest of the program.
The importance of this is that in place of one large, complex problem (writing the whole program), you have a number of smaller, less complex problems that can be tackled independently. For example, if you try to test an entire program, it might be hard to pin down exactly what part of the program is responsible for any error that occurs. If you test a small subroutine independently, it should be easier to figure out the cause of any error.
David Eck, 10 February 1998 | http://math.hws.edu/eck/cs124/labs98/lab4/answers.html | crawl-001 | refinedweb | 1,256 | 56.86 |
The
Can we control which runtime the automatically created manifest will reference? I would like my old VC++ 2008 projects to keep using the crt and mfc dlls of the RTM version and only use the new runtimes when I have new projects which use the new functionality.
--
SvenC
Great ! looking forward to try it out.
There is just a couple of things I cant find any information about.
If we Install this Feature Pack.
- How will this effect existing MFC application ? Can I still build apps to the MFC that currently is in VS2008 ?
- If we are already using BCGSoft's BCGControlBar library. Will we get any conflict ?
- Is it possible to just use the new STL (tr1) stuff and keep the standard vs2008 MFC ?
I would like to deploy dynamically linked apps using Installshield. I will need merge modules for the new library files.
Are they available?
I think that this is an exciting release, but it should be made available to Express edition users as well. Maybe the MFC components can't be released to the Express edition, but the TR1 stuff definitely should be.
This is great news Kudos to the team. Now what I'd really like to see is a couple of MSDN Magazine articles that cover the new MFC additions (TR1 stuff I can find from 'Standards' sources).
I use BCG Pro in my app years ago,
but with this update how can i upgrade it ? any tutorial to do so ?
Great! Thanks!
Is it planned to release a Feature Pack for WinForms? It would be great to add a Ribbon to a WinForm application as well.
Visual C++ Team Blog : Visual C++ 2008 Feature Pack Released! Download details Visual C++ 2008 Feature).
TR1 does look useful, so thanks for that. It's great to see things being added to the C++ support quickly now.
¿Recordáis esta entrada mía: Visual C++ 2008 Feature Pack ? Pues ya es oficial, ya está en la calle la
Does anyone know exactly what has changed since the pre-released Feature Pack?
Congratulations! Now at last, with both gcc and MSVC providing TR1 official implementations, we can consider TR1 to be mainstream.
Now back to waiting for C++09 - I sure hope you guys will roll out that one soon after the spec is finalized!
Some components from BCG are missing, /*always Microsoft forget some thing of interting in the lib*/. What about the Grid, the Calender and other intertings things, i can't use this feautre pack unless it's complete (and i guess that others do the same).
Hi Nacereddine,
what do you think would become of BCG when Microsoft would include the complete library? Nobody would buy it anymore and they would be dead. So ofcourse BCG will sell an advanced version of the library with more controls.
And I would say you are bit thankless: Microsoft is giving you extra controls for free and you say "Uhh, that is not enough, give me more!"
If you want more, than buy the product from BCG or its competitors (codejock, prof-uis). They are not that expensive.
Using the feature pack, developers can still develop application with the older look & feel of MFC.
Ayman Shoukry
Hi Tom,
We are targeting to have MSDN articles released soon.
Hi, unfortunately installation fails on an English language system which have different regional settings. I've English Vista x64 and an English language VS2008 Team Developer Edition. My user account's regional settings are set to German. Setup fails with an error message after extracting file, but before showing the setup GUI. It works after switching Vista's regional settings to en-us.
Hi,
I'm afraid that installation crashes on a german vista with an english VS2008. Can anybody help?
[Mathias]
> Is it possible to just use the new STL (tr1) stuff and keep the standard vs2008 MFC ?
Yes - there is no interaction between TR1 and MFC. Using TR1 doesn't force you to use the updated MFC (or MFC, period).
No - you can't patch TR1 without also patching MFC.
[TomC]
> I would like to deploy dynamically linked apps using Installshield. I will need merge modules for the new library files.
> Are they available?
They are indeed part of the Feature Pack.
[Dave Johansen]
> I think that this is an exciting release, but it should be made available
> to Express edition users as well. Maybe the MFC components can't be
> released to the Express edition, but the TR1 stuff definitely should be.
TR1 is integrated into VC9 SP1 and VC10.
[Jared]
> Does anyone know exactly what has changed since the pre-released Feature Pack?
Lots and lots of bugfixes. For example, in the Beta, linking together two source files that each included <tuple> would fail with "multiply defined symbols". We fixed that thanks to Beta feedback.
Stephan T. Lavavej
Visual C++ Libraries Developer
Sorry, forgot to mention: Installation crashes before showing setup UI. Switching regional settings to en-us (thanks Martin!) won't work either. It seems that there is a problem of loading a resource dll. The exact error message is: Unable to load UI satellite DLL SPInstallerResources.1031.dll
Thanks!
Chris
not worth to get happy. those such libraries make improve GUI only, not the inside quality.
bad job of MS.
The feature pack is missing updates to the IA64 libraries. The odd thing is that an updated vcredist_IA64.exe is available.
"The Feature Pack is available free of charge to any Visual Studio 2008 Standard or above customer."
Is not. Read the page: 'Support for systems with non-English versions of Visual Studio 2008 installed will be available in Visual Studio 2008 Service Pack 1.' Now will that come out this year?
I've installed the Feature Pack and noticed that in the redist folder, my manifest files didn't get updated.
For example, in the following folder:
E:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.MFC
The manifest file Microsoft.VC90.MFC.manifest contains version 9.0.21022.8 and is dated last November (when I install VS 2008). However, mfc90.dll details property page contains:
9.0.30304.0
Seems to me that this is a problem and you can't use the redist packages as is.
Anyone else notice this?
One other (possibly important) detail:
Prior to loading this feature pack, I installed VS patches from KB944899 and KB946581.
Where can I download the documentation for this feature pack, I don't want to always use the online help when I am need help for this new stuff.
There was a promise back in time that this feature pack was to be made available for Visual Studio 2005 as well. Is this still true?
Installation doesn't work here (VS2008 Pro English, Vista x64 German), but I could send an error report. Fails with unknown error even after a fresh reboot.
What about completing the ISO C 99 support?
Answering couple of the questions:
1) The feature pack is focused on x86 & x64
2) We are investigating the installation issues, some folks tried changing the locale to English and the installation then worked ( might help).
==================================
> If we are already using BCGSoft's BCGControlBar library. Will we get any conflict ?
No, you will not get any conflict. All of the classes have been renamed so there should
be no name conflicts with any of the BCGSoft classes.
[Nacereddine]
> I use BCG Pro in my app years ago,
> but with this update how can i upgrade it ? any tutorial to do so ?
We do not have a tutorial on upgrading from using the BCGSoft libraries to using MFC.
In many cases you just need to change the class names--many of the method names remain
the same. We may look into providing a mapping from BCGSoft to MFC class names.
[Leo Davidson]
>).
MFC will continue to wrap any new Windows controls, so if Windows includes controls that have similar
functionality to the MFC controls, there will be wrappers available so you can choose between using
the Windows control and the MFC control.
[John]
> The feature pack is missing updates to the IA64 libraries.
> The odd thing is that an updated vcredist_IA64.exe is available.
The IA64 versions of the MFC libraries and runtimes are still at the RTM level.
They do not include the feature pack updates to MFC.
[Mikael Pahmp]
> There was a promise back in time that this feature pack was to be made available for Visual Studio 2005 as well.
> Is this still true?
I don't know of any plans to release a feature pack for VS2005 that would include this new support.
Pat Brenner
Visual C++ Libraries Development
What about the offline documentation for this feature pack? Any plans or release dates for this? It would be very helpful! Thanks...
For documentation, for the feature pack, the docs will be online. Once we roll the features into SP, the offline docs will include such info.
I am still interested in my initial question: can we control what kind of manifest will be generated, so that our executables can either have manifests for the RTM version of the crt, mfc or the new runtimes of the feature pack.
I found no documentation if after installing the feature pack we can still build executables which run with the rtm version of crt and mfc.
Re: Monday, April 07, 2008 9:28 PM by lviolette
# Redistributables not updated correctly in Feature Pack.
The workaround is to change the manifest version from 9.0.21022.8 to 9.0.30304.0 (on my machine found under C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\redist) in the *.manifest files for MFC and CRT.
Thanks
George and Damien Finally we get
It seems that you also need to have administrator privileges in order to install this. The error message is a bit cryptic: 0x80070643
> MFC will continue to wrap any new Windows controls, so if Windows includes controls that have
> similar functionality to the MFC controls, there will be wrappers available so you can choose
> between using the Windows control and the MFC control.
I was asking for the opposite. :) I don't want to be forced to use MFC to get these new controls. I find that MFC makes very easy projects slightly easier (and I use it for throwing together very simple GUI apps), but for anything complex MFC actually gets in the way and makes things more difficult, not less.
If the Visual C++ team are going to invest in GUI controls it would be nice if they were available to all Visual C++ developers, not just those using MFC. Of course, it's easy to turn a Win32 control into an MFC object so you can please both groups of people by writing/buying Win32 controls and wrapping them in MFC. With an MFC-only control, however, it's not easy to convert it into a non-MFC control.
Of course, anything is better than nothing; I'm just saying that controls like these would be useful to many more people if they were not tied to MFC. I also understand that the controls were bought from a 3rd party and maybe there simply were no non-MFC alternatives.
I'd very much like to use this, but I have some concerns about the licensing. If I install the feature pack, will I have to agree to the Fluent UI licensing terms? If not, is it clear which features of the feature pack do and do not require additional licensing, so that I don't inadvertently use a feature that then imposes extra licensing requirements on me?
I wish to update my current MFC 8.0 project and replace some 3rd-party code with Feature Pack CMFC* classes.
But there's one question, Can it be deployed to Win 2000 after my upgrade? a more general question is: what OSes are supported by applications developed with MFC9.0+Power Pack?
Thanks.
You can deploy to Win 2000 after upgrading your project to the Feature Pack. The OS support is the same as VS2008. However the new features are not avaiable on the IA64 platform. TR1 will be available on the IA64 platform in VS2008 SP1.
[S. Colcord]
> If I install the feature pack, will I have to agree to the Fluent UI licensing terms?
You only have to agree to the Fluent UI licensing terms if you are creating an application that uses the Fluent UI components (aka the ribbon UI) in MFC.
[Pat Brenner]
> You only have to agree to the Fluent UI licensing terms if you are creating an application that uses the Fluent UI components (aka the ribbon UI) in MFC.
Thanks, Pat. Our application is an MFC app, so I'm trying to make sure that a developer can't easily use a Fluent UI component without intending to. Are the classes comprising the Fluent UI components denoted as such, by being in a separate namespace, or requiring a special compiler flag or #include to use?
Installation package is a peace of crap. After 10 minutes and progress bar frozen somewhere at 75% it returned with "fatal error"
From the log file:
MSI (c) (C8:F8) [22:25:12:187]: MainEngineThread is returning 1603
-------------------------------------------
VS Team: you have no rights to release such a junk even if junk is just an installation routine but not the content.
There was a question earlier about adding MFC to the Express edition. While we won't be able to do this in the short term, our goal is to include MFC into the next major release of Express.
Bill Dunlap
Get this error in 32-bit compiles with the TR1 update installed:
1>c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\intrin.h(204) : error C2373: '_InterlockedCompareExchange' : redefinition; different type modifiers
1> c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\include\memory(994) : see declaration of '_InterlockedCompareExchange'
Ouch! The newer Windows SDK caused some problems like this with VC++ 2005, but 2008 fixed them. Now it happens again, but within VC++ itself!
you can reproduce the bug by compiling your project with __fastcall.
this occurs because <memory> declares it as __cdecl while intrin.h doesn't specify.
quick fix? remove the __CLRCALL_PURE_OR_CDECL bit from line 994.
Cory Nelson:
Thanks for reporting this. I've added your repro to our internal bug "<memory> should include <intrin.h>".
I installed the release version on top of beta. Now, I get compile errors in New Controls project (I haven't tried others yet). Following are a few of many. Seems like the sample files are not updated based on changes to the release version.
c:\program files\microsoft visual studio 9.0\samples\c++\mfc\visual c++ 2008 feature pack\newcontrols\customproperties.cpp(288) : error C2065: 'm_bValueIsTrancated' : undeclared identifier
c:\program files\microsoft visual studio 9.0\samples\c++\mfc\visual c++ 2008 feature pack\newcontrols\customproperties.cpp(338) : error C2065: 'globalData' : undeclared identifier
c:\program files\microsoft visual studio 9.0\samples\c++\mfc\visual c++ 2008 feature pack\newcontrols\customproperties.cpp(338) : error C2228: left of '.clrTextHilite' must have class/struct/union
Hi Mr.MFC,
I just tried the sample myself and it seems to compile with no errors. Have you tried installing after uninstalling the beta?
Let me know if the sample still doesn't compile with you.
[Mr.MFC]
>I installed the release version on top of beta. Now, I get compile errors in New Controls project.
Did you make sure to un-ZIP the new versions of the sample source? The samples are installed as a ZIP file which you have to un-ZIP.
thank you! I've been using BCG for years and years, love it. This is nice for those apps that don't need *all* the bcg features. A step in the right direction for sure. Much appreciated!
>Are the classes comprising the Fluent UI components denoted as such, by being in a separate namespace, or requiring a special compiler flag or #include to use?
No, there is no separation via namespace. Basically, if you are not using any of the CMFCRibbon* classes, you are probably not using the fluent UI.
Note that the license is a no-cost, royalty-free licence which is obtained via a simple click-through agreement on the Office UI site.
> No, there is no separation via namespace. Basically, if you are not using any of the CMFCRibbon* classes, you are probably not using the fluent UI.
Thanks, Pat. FWIW, I think that without such a separation, a lot of developers will use those classes without realizing the legal implications. The above guideline is helpful, but I think that company lawyers are going to want something more definite.
To clarify why this is a concern, Microsoft is saying "If you use the Fluent UI, you need a license", but I haven't found an clear definition of what constitutes "Using the Fluent UI". Without a clear definition, the license requirements create a lot of FUD, since a developer can't tell whether they need a license or not.
> Note that the license is a no-cost, royalty-free licence which is obtained via a simple click-through agreement on the Office UI site.
The issue isn't the cost; it's that the license incorporates the Fluent UI design guidelines as legal requirements. Depending on the application, the costs of making it conform to those requirements could be prohibitive.
Re: Monday, April 07, 2008 9:17 AM by SvenC
# re: Visual C++ 2008 Feature Pack Released!
[Updated: a more accurate answer than the previous posting]
Yes, you can control it:
By default any projects depend on RTM bits. To make them depend on the feature pack set _BIND_TO_CURRENT_CRT_VERSION to 1 and /or _BIND_TO_CURRENT_MFC_VERSION to 1
If you have been using the Boost libraries then you will probably not see anything major that's not already
>Did you make sure to un-ZIP the new versions of the sample source? The samples are installed as a ZIP file which you have to un-ZIP.
Thanks, I didn't realize that. I also changed globalData to afxGlobalData, in older examples with success.
On other issues:
I had posted during beta testing about a bug in menu button and got a response from a VC team member that they added to the bug list. The release version still has the same problem of not disabling an item of the menu button. I do the following and expect the specified item to be disabled and no notifications of click:
m_menu.LoadMenu(IDR_MENU1);
CMenu *pSubMenu=m_menu.GetSubMenu(0);
if(pSubMenu)
{
pSubMenu->EnableMenuItem(1,FALSE);
m_btnMenu.m_hMenu = pSubMenu->GetSafeHmenu();
}
Since a Grid class is not supplied, I requested for some suggestion on Somasegar's blog. Perhaps I should have posted it here:
>Hi Pat/VC++ Team,
>Could you recommend some third party Grid controls that are easy to work with in MFC? I have been using the MSFlexgrid ActiveX control since VS97, but is not supplied with VS 2008.
Sri
I'm very happy to see the new BCG controls. But I'm trying to test out the random number generation that is part of TR1, and no dice.
If I create a new MFC project from scratch, accept the default settings, then use
#include <random>
anywhere, I get 117 errors and 6 warnings, (listed at the end). Since I'm doing all this from scratch with the default settings, I think this is a bug.
errors/warning beginning with:
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : warning C4229: anachronism used : modifiers on data are ignored
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : error C2365: 'operator new' : redefinition; previous definition was 'function'
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : error C2491: 'new' : definition of dllimport data not allowed
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : error C2078: too many initializers
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : error C2440: 'initializing' : cannot convert from 'int' to 'void *'
1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : error C2143: syntax error : missing ';' before '('
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(32) : error C2226: syntax error : unexpected type 'size_t'
1>c:\program files\microsoft visual studio 9.0\vc\include\xdebug(33) : error C2059: syntax error : ')'
Ok, so I installed a fresh copy of VS2008, followed by the MFC Feature Pack. Everything installs fine (though it took forever and a day).
I run through the new MFC app wizard, and make a few basic style decisions, etc. I'm just looking to see how the BCGSoft classes run, after all (compared to the CodeJock libs we've been using). So I hit F5 to compile and run, and....
It doesn't work. Immediately, I get assertions in one of the new MFC/BCGSoft Ribbon classes, followed by a "failed to create empty document" error. I haven't added a single line of code, mind you - just the default output from the MFC wizard.
Terribly impressive.
Hi Big E,
Could you let us know what kind of changes you made so that we can reproduce the issue on our side.
Feel free to send me the project straight ahead at aymans at microsoft dot com
[Big E]
> It doesn't work. Immediately, I get assertions in one of the new MFC/BCGSoft Ribbon classes...
Sorry to hear that the wizard is not creating a viable application for you. Rest assured that we tried to make the wizard as robust as possible, but there are literally hundreds or thousands of combinations of options. Can you let me know specifically which combinatino of options you selected in the wizard so I can reproduce the problem and fix it? Thanks!
> Could you let us know what kind of changes you made so that we can reproduce the issue on our side.
I'm actually not touching anything when this happens. As I stated originally, I'm just running through the MFC app wizard.
I'm choosing almost all the default values, with the exception of the first page of the wizard. There, I choose the following:
Application type: Single document
Document / View architecture: enabled
Resource language: English
Use unicode libs: enabled
Project sytle: Office
Visual style and colors: Office 2007 (Blue theme)
Enable visual style switching: enabled
Use of MFC: Use MFC in a static lib
On every subsequent page of the wizard, I just go with the default values. Once complete, I build the application (rebuild all) and hit F5.
This results in an assertion firing on line 3891 of afxribbonbar.cpp, which is this line:
ENSURE(str1.LoadString(AFX_IDS_ONEPAGE));
The ENSURE macro then throws an unhandled exception that terminates the app.
I haven't yet tried any other project types.
Hope that helps.
[Rebecca]
> But I'm trying to test out the random number
> generation that is part of TR1, and no dice.
When you create a new MFC project, it "helpfully" adds "#define new DEBUG_NEW" (see ).
However, this is incompatible with the Standard (and TR1) headers. Paragraph 17.4.3.1.1/2 [lib.macro.names] of the C++ Standard states:
"A translation unit that includes a header shall not contain any macros that define names declared or defined in that header. Nor shall such a translation unit define macros for names lexically identical to keywords."
(When the Standard says "header", it means the Standard headers like <vector>. The Standard uses "source file" to refer to everything else, including files that end with .h or .hpp and that get #included. This is different from ordinary terminology.)
What 17.4.3.1.1/2 is saying is very reasonable - you're not allowed to stomp on the Standard headers with macros. Unfortunately, that's exactly what "#define new DEBUG_NEW" does. The result is horrible compiler errors.
Within an MFC project, you can include <random> (and other Standard and TR1 headers), as long as you do so from "clean" source files - that is, source files that don't define "macros for names lexically identical to keywords" (and so forth) either before OR after the Standard/TR1 headers are included. (Be careful of PCHs that drag in such macros.)
Thanks, Stephan - I appreciate the info. Works now.
'When you create a new MFC project, it "helpfully" adds "#define new DEBUG_NEW" (see ).
However, this is incompatible with the Standard'
My questions here are academic until VS2008 SP1 comes out, but please say if I understand correctly.
(1) A workaround is to delete the line "#define new DEBUG_NEW".
(2) This is a bug in the wizard which might be a fix or might be a won't fix for VS2008 SP1.
By the way, is there a target yet for which year most language versions of VS2008 SP1 might be released?
[Norman Diamond]
> (1) A workaround is to delete the line
> "#define new DEBUG_NEW".
Yes, insofar as that stops stomping on the Standard/TR1 headers. I'm not sure how that affects the MFC side of things. (The danger here is presumably using the MFC leak tracking in some translation units and not in others, leading to heap corruption when they pass pointers to each other. It does appear that the MFC leak tracking is optional, according to MSDN - the new project wizard is simply enabling it by default. So, if you really get rid of all occurrences of this macro, you should be fine.)
> (2) This is a bug in the wizard which might be a
> fix or might be a won't fix for VS2008 SP1.
According to my understanding, the wizard has always done this, and it's always opened up the 17.4.3.1.1/2 can of worms - TR1 just happens to trigger actual breakage.
(IIRC, other Standard Library headers attempt to defend themselves against "new" being macro-ized - but if you ask me, we should actually detect and #error when any keywords are macros, rather than defending against it. We do defend against "min" and "max" being macros, but that's because <windows.h> defines them.)
"#define new DEBUG_NEW" is operating by design, and the wizard is enabling it by design. The design just happens to be extremely unfriendly to the Standard headers. (As co-maintainer of the headers being stomped on, this is not my favorite macro.)
> By the way, is there a target yet for which year
> most language versions of VS2008 SP1 might be
> released?
I'm not sure what you're asking. VC9 SP1 (any language) has not yet been released, and I don't think we've talked about release dates yet (although we certainly have them in mind).
I can say that it is not yet too late to get fixes for Horrible TR1 (and MFC) Bugs into VC9 SP1, *if* they are reported promptly enough (and the bugs are horrible enough, and the fixes safe enough, etc.).
Stephan T. Lavavej, Visual C++ Libraries Developer
>> By the way, is there a target yet for which year most language versions of VS2008 SP1 might be released?
> I'm not sure what you're asking. VC9 SP1 (any language) has not yet been released
The English language version of VS2008 SP1 might not be urgent, I don't know. Other language versions are comparatively more urgent, because of the promise that the VC++2008 Feature Pack will not be released until SP1. Therefore I asked if there's any target on what year we'll get them.
Hi Norman,
I don't believe there were any dates published yet regarding VS2008 SP1. I will make sure to post those dates as soon as I have them.
> I'm actually not touching anything when this happens. As I stated originally, I'm just running through the MFC app wizard.
Thanks for clarifying the repro steps for the wizard bug you've been seeing. We did find this in our testing, but too late for the Feature Pack release.
There is a simple work-around, which is to include afxprint.rc along with afxribbon.rc in the RC file for your wizard-generated project.
I've tried running the Boost regression tests against the release feature pack, and while a lot of the problems from the Beta have
been fixed, there are still a few left:
-Random:
One of the Random tests is failing () because of a missing "seed(integer-type s)" member function in xor_combine.
When i mentioned this on the Boost list, it was thought that this was a 'bug' in TR1 due to Table 16 saying that all random number
engines should have that member, but the description of xor_combine not mentioning it.
However, the TR1 spec is also missing this seed member from discard_block, and i see that the feature pack implementation contains it
anyway. So, is the missing function from xor_combine an oversight?
-Regex:
One of the Regex tests is failing () due to a problem with a char_class_type typedef.
When i asked about this on the Boost list, the response was that it looks like a feature pack bug:
-Bind:
There are some Bind failures () due to a missing member result_type definition.
Anyone got any thoughts?
I can raise bugs on Connect if they are considered bugs on the feature pack side.
Richard Webb
I have been using the beta release of the service pack for the last few months and have successfully update my VC 6.0 programs. I like the new looks.
HoweverI just downloaded and installed the new service pack and now I am getting compile errors such as:
afxcontrolbar.h(25) : error C2084: function 'BOOL IsStandardCommand(UINT)' already has a body
afxcontrolbarutil.h(24) : see previous definition of 'IsStandardCommand'
afxcontrolbar.h(54) : error C2011: 'CMemDC' : 'class' type redefinition
afxcontrolbarutil.h(54) : see declaration of 'CMemDC'
afxbasetabbedpane.h(108) : error C2143: syntax error : missing ';' before '*'
afxbasetabbedpane.h(108) : error C2433: 'CBaseTabbedPane::CMFCAutoHideBar' : 'virtual' not permitted on data declarations
It seems like the new service pack did not install properly over the beta. Any suggestions on how to correct this without completely reinstalling Visual Studio 08 and then running the feature pack install? This would take hours. Is it possible to uninstall the feature packs only?
Thanks
[Richard Webb]
> I've tried running the Boost regression tests
> against the release feature pack
Awesome! Your bug reports from running the tests against the Feature Pack Beta were really helpful.
> So, is the missing function from xor_combine an
> oversight?
That appears to be the case. (It doesn't help when the TR1 spec contains thinkos.)
We're trying to conform to TR1 + obvious thinko fixes + selected C++0x backports, and this appears to fall under "obvious thinko fix". Please file a Connect bug for this.
> One of the Regex tests is failing
> () due to a problem with a
> char_class_type typedef.
Our std::tr1::regex_traits<T>::char_class_type is a typedef for int. TR1 7.2/4 requires that char_class_type be a bitmask type, and [lib.bitmask.types] C++03 17.3.2.1.2/1 explains that "Each bitmask type can be implemented as an enumerated type that overloads certain operators, as an integer type, or as a bitset".
Can you explain what the conformance problem is here? I don't understand what the Boost test is complaining about.
> There are some Bind failures
> () due to a missing member
> result_type definition.
This is a known bug, but it was discovered too late (Feb 7) to be fixed in the Feature Pack. The internal bug number is Dev10.391723.
Feel free to E-mail me directly (stl@microsoft.com) if you encounter any other issues.
> Please file a Connect bug for this.
Done ().
>Can you explain what the conformance problem is here?
Theres a confirmation on whats happening @
Basically, the Boost test is using the VC9 basic_regex along with a Boost traits class, and it's failing because the traits class uses a bitset for char_class_type, which the VC9 basic_regex can't handle.
The same post also contains a simple example of an apparent problem in tr1::result_of.
The code:
typedef int (&func_ref)(float, double);
typedef std::tr1::result_of<func_ref(float,double)>::type result_type;
Doesnt compile with the feature pack result_of, but is fine with the Boost version.
Using the Feature Pack in Visual Studio 2008 (<regex> library) I am getting the following linker error:
error LNK2019: unresolved external symbol "void __cdecl std::tr1::_Destroy(class std::tr1::_Node_base *,enum std::tr1::_Node_type)" (?_Destroy@tr1@std@@YAXPAV_Node_base@12@W4_Node_type@12@@Z) referenced in function "public: virtual __thiscall std::tr1::_Node_assert::~_Node_assert(void)" (??1_Node_assert@tr1@std@@UAE@XZ)
When I was using the beta distribution of the Feature Pack I was getting no linker errors.
If I comment out the following line, the linker error disappears:
using std::tr1::regex;
using std::tr1::regex_replace;
...
//regex rgx("[^\\d]*");
So, this is associated with the regex constructor which takes a const string. If I use the default constructor, the linker error disappears, also.
[John Shroe]
> error LNK2019: unresolved external symbol "void __cdecl std::tr1::_Destroy(
Somehow, you're using the Feature Pack Beta headers with the Feature Pack RTW (Release To Web, i.e. final) binaries. std::tr1::_Destroy() in Beta was renamed to std::tr1::_Destroy_node() in RTW, in order to fix a memory leak.
Installing the Feature Pack RTW over the Feature Pack Beta isn't supported. You have to uninstall the Feature Pack Beta (which I am told is robust) before installing the Feature Pack RTW.
We are very excited to announce that Microsoft Visual Studio 2008 SP1 Beta is now available for download.
once I compiled the program use vc2008 mfc, it will use .net framework 3.5 and will installed about more 50MB .net framework library. It's very bad and anoyed.
I test it in vista platform, it also need install .net framework 3.5!
Microsoft should deploy .net framework 3.5 themselves or don't need .net framework 3.5 if I compiled use vc2008 mfc.
How can I remove the .net framework 3.5 depend library, I hate to install more 50MB files.
Also missing much class in vc2008, like catlregexp, cdllcache etc.
I don't know why missing them, and if I need it, where can I get those class files?
Today we are pleased to announce that Microsoft Visual Studio 2008 Service Pack 1 (SP1) is now available
Nachdem meine Ankündigung gestern eher spartanisch ausgefallen ist, möchte ich heute noch ein paar Links | http://blogs.msdn.com/vcblog/archive/2008/04/07/visual-c-2008-feature-pack-released.aspx | crawl-002 | refinedweb | 5,818 | 65.32 |
Im trying to use strptime to convert a day and time into a DateTime field. That is, convert input like "Friday 3:00 PM" to a datetime field. The event this is for takes place over three consecutive days, so I know that Friday will be a specific day in February, and so on.
My question, is how do I go about doing this? How do I convert, for example, Friday 3:00 PM into 2017-02-24 15:00:00?
What I have right now in my Django project, in views.py is:
new_request.start = time.strptime(form.cleaned_data['start'], '%A %I:%M %p')
You can adapt the example below to achieve what you want exactly:
import time time.strftime("%Y-%d-%m %H:%M:%S", time.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p')) # Output: '2017-03-02 15:00:00'
If year and month are fixed to 2017 and February like you mentioned then "Friday 3:00 PM" can be converted as follows:
time.strftime("2017-%d-2 %H:%M:%S", time.strptime('Friday 3 3:00PM', '%A %d %I:%M%p')) # Output: '2017-03-2 15:00:00'
If you want to get
datetime object use the following:
from datetime import datetime datetime.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p') # Output: datetime.datetime(2017, 2, 3, 15, 0) | https://codedump.io/share/Gnhd2Trzjz72/1/converting-from-ltdaygt-lttimegt-to-datetime-in-python-and-django-and-back | CC-MAIN-2018-17 | refinedweb | 235 | 75.1 |
#include <GovSteamFV2.h>
Steam turbine governor with reheat time constants and modeling of the effects of fast valve closing to reduce mechanical power.
(Dt).
Fraction of the turbine power developed by turbine sections not involved in fast valving (K).
Alternate Base used instead of Machine base in equipment model if necessary (MWbase) (>0). Unit = MW.
(R).
Governor time constant (T1).
Reheater time constant (T3).
Time after initial time for valve to close (Ta).
Time after initial time for valve to begin opening (Tb).
Time after initial time for valve to become fully open (Tc).
Initial time to begin fast valving (Ti).
Time constant with which power falls off after intercept valve closure (Tt).
(Vmax).
(Vmin). | https://cim.fein-aachen.org/libcimpp/doc/IEC61970_17v23/classIEC61970_1_1Dynamics_1_1StandardModels_1_1TurbineGovernorDynamics_1_1GovSteamFV2.html | CC-MAIN-2020-16 | refinedweb | 115 | 68.36 |
jQuery 1.4 Released: The 15 New Features you Must:
1. Passing Attributes to jQuery(…)
Pre 1.4, jQuery supported adding attributes to an element collection via the useful "
attr" method, which can be passed both an attribute name and value, or an object specifying several attributes. jQuery 1.4 adds support for passing an attributes object as the second argument to the jQuery function itself, upon element creation.
Let's say you need to create an anchor element with several attributes. With 1.4 it's as simple as:
jQuery('<a/>', { id: 'foo', href: '', title: 'Become a Googler', rel: 'external', text: 'Go to Google!' });
You may have noticed the "
text" attribute— you'll probably be wondering what that's doing there, after all there's no "
text" attribute for anchors! Well, jQuery 1.4 utilises its very own methods when you pass certain attributes. So the "text" attribute specified above would cause jQuery to call the "
.text()" method, passing "Go to Google!" as its only argument.
A better example of this in action:
jQuery('<div/>', { id: 'foo', css: { fontWeight: 700, color: 'green' }, click: function(){ alert('Foo has been clicked!'); } });
The "id" is added as a regular attribute, but the "css" and "click" properties trigger calling of each respective method. The above code, before the 1.4 release, would have been written like this:
jQuery('<div/>') .attr('id', 'foo') .css({ fontWeight: 700, color: 'green' }) .click(function(){ alert('Foo has been clicked!'); });
Read more about jQuery(…)
2. Everything "until"!
Three new methods have been added to the DOM traversal arsenal in 1.4, "
nextUntil", "
prevUntil" and "
parentsUntil". Each of these methods will traverse the DOM in a certain direction until the passed selector is satisfied. So, let's say you have a list of fruit:
<ul> <li>Apple</li> <li>Banana</li> <li>Grape</li> <li>Strawberry</li> <li>Pear</li> <li>Peach</li> </ul>
You want to select all of items after "Apple", but you want to stop once you reach "Strawberry". It couldn't be simpler:
jQuery('ul li:contains(Apple)').nextUntil(':contains(Pear)'); // Selects Banana, Grape, Strawberry
Read more about: prevUntil, nextUntil, parentsUntil
3. Binding Multiple Event Handlers
Instead of chaining a bunch of event binding methods together, you can lump them all into the same call, like so:
jQuery('#foo).bind({ click: function() { // do something }, mouseover: function() { // do something }, mouseout: function() { // do something } })
This also works with "
.one()".
4. Per-Property Easing
Instead of just defining one easing function for a single animation, you can now define a different easing function for each property that you're animating. jQuery includes two easing functions, swing (the default) and linear. For other ones you'll need to download them separately!
To specify an easing function for each property simply define the property as an array, with the first value being what you want to animate that property to, and the second being the easing function to use:
jQuery('#foo').animate({ left: 500, top: [500, 'easeOutBounce'] }, 2000);
You can also define per-property easing functions in the optional options object as property name-value pairs in the "specialEasing" object:
jQuery('#foo').animate({ left: 500, top: 500 }, { duration: 2000, specialEasing: { top: 'easeOutBounce' } });
Editor's Note - The author of this article, James Padolsey, is being modest. This new feature was his idea!
Read more about per-property easing
5. New Live Events!
jQuery 1.4 adds support for delegating the "submit", "change", "focus" and "blur" events. In jQuery, we use the "
.live()" method to delegate events. This is useful when you have to register event handlers on many elements, and when new elements may be added over time (using "
.live()" is less-costly than re-binding continually).
But, be careful! You must use the event names, "focusin" and "focusout" if you want to delegate the "focus" and "blur" events!
jQuery('input').live('focusin', function(){ // do something with this });
6. Controlling a Function's Context
jQuery 1.4 provides a new "
proxy" function under the jQuery namespace. This function takes two arguments, either a "scope" and a method name, or a function and the intended scope. JavaScript's "this" keyword can be quite tricky to keep a hold of. Sometimes you won't want it to be an element, but instead an object that you've previously created.
For example, here we've got an "
app" object which has two properties, a "
clickHandler" method and a config object:
var app = { config: { clickMessage: 'Hi!' }, clickHandler: function() { alert(this.config.clickMessage); } };
The "
clickHandler" method, when called like "
app.clickHandler()" will have "
app" as its context, meaning that the "
this" keyword will allow it access to "
app". This works quite well if we simply call:
app.clickHandler(); // "Hi!" is alerted
Let's try binding it as an event handler:
jQuery('a').bind('click', app.clickHandler);
When we click an anchor it doesn't appear to work (nothing is alerted). That's because jQuery (and most sane event models) will, by default, set the context of the handler as the target element,- that is, the element that's just been clicked will be accessible via "
this". But we don't want that, we want "
this" to be set to "
app". Achieving this in jQuery 1.4 couldn't be simpler:
jQuery('a').bind( 'click', jQuery.proxy(app, 'clickHandler') );
Now whenever an anchor is clicked, "Hi!" will be alerted!
The proxy function returns a "wrapped" version of your function, with "
this" set to whatever you specify. It's useful in other contexts too, such as passing callbacks to other jQuery methods, or to plugins.
Read more about
jQuery.proxy
7. Delay an Animation Queue
You can now add a delay to your animation queues. In fact, this works on any queue, but its most common use case will probably be with the "fx" queue. This allows you to pause between animations without having to mess with callbacks and calls to "
setTimeout". The first argument to "
.delay()" is the amount of milliseconds you want to delay for.
jQuery('#foo') .slideDown() // Slide down .delay(200) // Do nothing for 200 ms .fadeIn(); // Fade in
If you want to delay a queue other than the default "fx" queue, then you'll need to pass the queue name as the second argument to "
.delay()".
Read more about
.delay(…)
8. Check if an Element Has Something
jQuery 1.4 makes it easy to check if an element (or collection) "
.has()" something. This is the programmatic equivalent to jQuery's selector filter, "
:has()". This method will select all elements in the current collection that contain at least one element that complies with the passed selector.
jQuery('div').has('ul');
That would select all DIV elements that contain UL elements. In this situation you'd probably just use the selector filter ("
:has()"), but this method is still useful when you need to filter a collection programmatically.
jQuery 1.4 also reveals the "
contains" function under the jQuery namespace. This is a low-level function that accepts two DOM nodes. It'll return a boolean indicating whether the second element is contained within the first element. E.g.
jQuery.contains(document.documentElement, document.body); // Returns true - <body> is within <html>
Read more about:
.has(…),
jQuery.contains(…)
9. Unwrap Elements!
We've had the "
.wrap()" method for a while now. jQuery 1.4 adds the "
.unwrap()" method which does the complete opposite. If we assume the following DOM structure:
<div> <p>Foo</p> </div>
We can unwrap the paragraph element like so:
jQuery('p').unwrap();
The resulting DOM structure would be:
<p>Foo</p>
Essentially, this method simply removes the parent of any element.
Read more about
.unwrap(…)
10. Remove Elements Without Deleting Data
The new "
.detach()" method allows you to remove elements from the DOM, much like the "
.remove()" method. The key difference with this new method is that it doesn't destroy the data held by jQuery on that element. This includes data added via "
.data()" and any event handlers added via jQuery's event system.
This can be useful when you need to remove an element from the DOM, but you know you'll need to add it back at a later stage. Its event handlers and any other data will persist.
var foo = jQuery('#foo'); // Bind an important event handler foo.click(function(){ alert('Foo!'); }); foo.detach(); // Remove it from the DOM // … do stuff foo.appendTo('body'); // Add it back to the DOM foo.click(); // alerts "Foo!"
Read more about
.detach(…)
11. index(…) Enhancements
jQuery 1.4 gives you two new ways to use the "
.index()" method. Previously, you could only pass an element as its argument and you'd expect a number to be returned indicating the index of that element within the current collection.
Passing no arguments now returns the index of an element amongst its siblings. So, assuming the following DOM structure:
<ul> <li>Apple</li> <li>Banana</li> <li>Grape</li> <li>Strawberry</li> <li>Pear</li> <li>Peach</li> </ul>
When a list item is clicked you want to find out the index of the clicked element amongst all the other list items. It's as simple as:
jQuery('li').click(function(){ alert( jQuery(this).index() ); });
jQuery 1.4 also allows you to specify a selector as the first argument to "
.index()", doing so will give you the index of the current element amongst the collection produced from that selector.
You should note that what's returned from this method is an integer, and it will return -1 if the selector/element passed cannot be found in the document.
Read more about
.index(…)
12. DOM Manipulation Methods Accept Callbacks
Most of the DOM manipulation methods now support passing a function as the sole argument (or second, in the case of "
.css()" & "
.attr()"). This function will be run on every element in the collection to determine what should be used as the real value for that method.
The following methods have this capability:
- after
- before
- append
- prepend
- addClass
- toggleClass
- removeClass
- wrap
- wrapAll
- wrapInner
- val
- text
- replaceWith
- css
- attr
- html
Within the callback function, you'll have access to the current element in the collection via "
this" and its index via the first argument.
jQuery('li').html(function(i){ return 'Index of this list item: ' + i; });
Also, with some of the above methods you'll also get a second argument. If you're calling a setter method (like "
.html()" or "
.attr('href)") you'll have access to the current value. E.g.
jQuery('a').attr('href', function(i, currentHref){ return currentHref + '?foo=bar'; });
As you can see, with the "
.css()" and "
.attr()" methods, you would pass the function as the second argument, since the first would be used to name the property you wish to change:
jQuery('li').css('color', function(i, currentCssColor){ return i % 2 ? 'red' : 'blue'; });
13. Determine the Type of Object
jQuery 1.4 adds two new helper functions (stored directly under the jQuery namespace) that help you determine what type of object you're dealing with.
First, there's "
isEmptyObject", this function returns a boolean indicating whether or not the the passed object is empty (devoid of properties - direct and inherited). Second, there's "
isPlainObject", which will return a boolean indicating whether the passed object is a plain JavaScript object, that is, one created via "
{}" or "
new Object()".
jQuery.isEmptyObject({}); // true jQuery.isEmptyObject({foo:1}); // false jQuery.isPlainObject({}); // true jQuery.isPlainObject(window); // false jQuery.isPlainObject(jQuery()); // false
Read more about:
isPlainObject(…),
isEmptyObject(…)
14. Closest(…) Enhancements
jQuery's "
.closest()" method now accepts an array of selectors. This is useful when you want to traverse the ancestors of an element, looking for (more than one) closest elements with certain characteristics.
In addition, it now accepts a context as the second argument, meaning that you can control just how far or how close you want the DOM traversed to. Both of these enhancements accommodate rare use cases but they are used internally to great effect!
Read more about
.closest(…)
15. New Events! focusIn and focusOut
As mentioned, to delegate the "focus" and "blur" events you must use these new events, called "focusin" and "focusout". These events allow you to take action when an element, or a descendant of an element, gains focus.
jQuery('form') .focusin(function(){ jQuery(this).addClass('focused'); }); .focusout(function(){ jQuery(this).removeClass('focused'); });
You should also note that both of these events do not propagate ("bubble"); they are captured. This means that the outermost (ancestor) element will be triggered before the causal "target" element.
Read more about the
focusIn and
focusOut events.
Enjoy jQuery 1.4, the most anticipated, most feature-rich, best performing release of jQuery yet!
Well, that's it! I've tried to cover the changes which I think will have an impact on you!
If you haven't already, you should check out the "14 days of jQuery", an awesome online event marking the release of jQuery 1.4, and jQuery's fourth birthday!
And don't forget to checkout the new API documentation!_0<<
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
| http://code.tutsplus.com/tutorials/jquery-14-released-the-15-new-features-you-must-know--net-8590 | CC-MAIN-2014-52 | refinedweb | 2,182 | 66.94 |
Member
2 Points
Jul 14, 2010 11:36 AM|nitcoolish|LINK
i donot have any intentions till now of uploading my web project and just started working on MS VS9.0
I made a simple Linq based project (CODE BEHIND used)
AS i compiled it i got
Parser Error: Could not load type '_Default'.
I figured out 2 solutions for this(WHICH I CUDNT FIND IN MANY FORUMS). But nt sure...why doing them solves the problem.
SOL 1)
The easy way out is to uncheck "place the code in the seperate file" while adding an item.
and then adding the statement <%@ Import Namespace="System.Linq" %> on top of ur aspx as in:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Linq" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
---FURTHER CODE----
Sol2)
If we deal whith the CODE behind technique....and have already used "USING System.Linq; in the definition,
I found a funny solution to the problem.
In ur default page...the top line is
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="<namespace>.<class>" %>
Now if i change the keyword from CodeBehind to CodeFile as in:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="<namespace>.<class>" %>
voila the error is gone!!! btw if u add a new webform now...it will automatically display the keyword CodeFile.
Please clear my concepts :)
Ps: hope it helps a few newbies lyk me :P
Nitish Mahajan
code behind .net 3.5 c sharp Parser Erro Could not load type .'_Default'
Member
414 Points
Aug 31, 2010 01:23 PM|AmruthaRaghavan|LINK.
Sep 01, 2010 08:39 PM|Programor|LINK
99% of the time this has to do with a bad reference, look at your paths carefully.
If you are loading the page's class from a dll then you don't need the CodeFile attribute or CodeBehind. Just set the inherits attribute.
2 replies
Last post Sep 01, 2010 08:39 PM by Programor | http://forums.asp.net/t/1578816.aspx?Strange+Parser+Error+Could+not+load+type+_Default+ | CC-MAIN-2014-42 | refinedweb | 327 | 68.36 |
Am I doing modulus wrong? Because in Java
-13 % 64 is supposed to evaluate to
-13 but I get
51.
Both definitions of modulus of negative numbers are in use – some languages use one definition and some the other.
If you want to get a negative number for negative inputs then you can use this:
int r = x % n; if (r > 0 && x < 0) { r -= n; }
Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:
int r = x % n; if (r < 0) { r += n; }
Since “mathematically” both are correct:
-13 % 64 = -13 (on modulus 64) -13 % 64 = 51 (on modulus 64)
One of the options had to be chosen by Java language developers and they chose:
the sign of the result equals the sign of the dividend.
Says it in Java specs:
Are you sure you are working in Java? ’cause Java gives -13 % 64 = -13 as expected. The sign of dividend!
Your result is wrong for Java.
Please provide some context how you arrived at it (your program, implementation and version of Java).
From the Java Language Specification
15.17.3 Remainder Operator %
[…]
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
15.17.2 Division Operator /
[…] Integer division rounds toward 0.
Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.
you can use
(x % n) - (x < 0 ? n : 0);
Your answer is in wikipedia:
modulo operation
It says, that in Java the sign on modulo operation is the same as that of dividend. and since we’re talking about the rest of the division operation is just fine, that it returns -13 in your case, since -13/64 = 0. -13-0 = -13.
EDIT: Sorry, misunderstood your question…You’re right, java should give -13. Can you provide more surrounding code?
Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.
I wasn’t able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.
x = x + m = x - m in modulus
m.
so
-13 = -13 + 64 in modulus
64 and
-13 = 51 in modulus
64.
assume
Z = X * d + r, if
0 < r < X then in division
Z/X we call
r the remainder.
Z % X returns the remainder of
Z/X.
To overcome this, you could add
64 (or whatever your modulus base is) to the negative value until it is positive
int k = -13; int modbase = 64; while (k < 0) { k += modbase; } int result = k % modbase;
The result will still be in the same equivalence class.
The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. So in your case of
-13 % 64
the largest integer multiple of 64 that does not exceed -13 is -64. Now, when you subtract -13 from -64 it equals 51
-13 - (-64) = -13 + 64 = 51
In my version of Java JDK 1.8.0_05 -13%64=-13
you could try -13-(int(-13/64))
in other words do division cast to an integer to get rid of the fraction part
then subtract from numerator
So numerator-(int(numerator/denominator)) should give the correct remainder & sign
In Java latest versions you get
-13%64 = -13. The answer will always have sign of numerator.
According to section 15.17.3 of the JLS, “The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a.
This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0).”
Hope that helps.
I don’t think Java returns 51 in this case. I am running Java 8 on a Mac and I get:
-13 % 64 = -13
Program:
public class Test { public static void main(String[] args) { int i = -13; int j = 64; System.out.println(i % j); } } | https://exceptionshub.com/how-does-java-do-modulus-calculations-with-negative-numbers.html | CC-MAIN-2021-21 | refinedweb | 734 | 61.36 |
The term chroot jail was first used in 1992, in an article by a prominent security researcher, Bill Cheswick, (which is interesting if you’re into that sort of thing, you can find the article here). Chroot jails started appearing in 2003, with applications like IRC and FTP. In 2005, Sun introduced its "Containers" technology called Zones, which in turn was a precursor to the concept of namespaces, which is a core technology used with containers.
Chroot basics
Chroot allows an administrator to control access to a service or filesystem while controlling exposure to the underlying server environment. The two common examples you might encounter are during the boot sequence and the "emergency shell" on Red Hat/CentOS/Fedora systems, and in Secure FTP (SFTP).
The command looks like this:
chroot <newroot> [[command][arguments]]
Similar to the
sudo command, the
chroot command changes the environment of the following command. In other words, it will change you to the
newroot directory, and also makes that directory the "working" directory. The
command then executes in that location, which is useful for things like rescuing a system that won’t boot.
Unlike
sudo, you will be "in" the directory. This practice, again, is useful if you are booting from external media but need to access a "local" filesystem or command to do work.
The other common use of
chroot is to restrict a service or user by using a wrapper to hide the rest of the filesystem, therefore restricting a remote user’s view of other users’ data. A popular implementation using this approach SFTP.
Example
Before you start working through this example, you should make sure you have backups. In this case, back up the
/etc/ssh/sshd_config file because you’ll be making changes to that one specifically:
[root@showme1 ~]# cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
For now, you will only restrict SFTP users to their home directories on the server. This requirement means that you’ll need to add users and put them in a group:
[root@showme1 ~]# useradd -g sftpusers -s /sbin/nologin -p nick nick
Note that doing this will assign
nick an account with no login shell. This technique is both practical and a good security practice: If he’s just using SFTP, he shouldn’t have login privileges. I’ll discuss providing a shell to remote users in the next article.
Now, you need to tell the
ssh service what to do when SFTP users log in. Open the
/etc/ssh/sshd_config file and add the following at the end:
Subsystem sftp internal-sftp Match Group sftpusers ForceCommand internal-sftp ChrootDirectory /home X11Forwarding no AllowTcpForwarding no
It’s important that you add these settings as a separate set of entries, and that you use the
Match syntax to indicate that this section only applies to users in this group. If you made the changes to the existing entries, they would apply to all SSH users, which could break remote access.
The configuration lines break down as follows:
- The
ForceCommandmakes
sshchoose its built-in facility to provide SFTP service (which you can control independently).
ChrootDirectorytells
sshdwhere to restrict the user to.
Subsystem sftp internal-sftptells
sshdto load the internal
sftpservice and make it available.
You might need to make sure that this
Subsystem is not defined already by commenting out this line earlier in the config file:
# override default of no subsystems # Subsystem sftp /usr/libexec/openssh/sftp-server
Once you’ve made the changes and checked the spelling, go ahead and save the changes. Then, restart
sshd:
[root@showme1 ~]# systemctl restart sshd
Test the new user:
[skipworthy@milo ~]$ sftp nick@showme nick@showme's password: Connected to nick@showme. sftp> ls accounting ansible fred jason kenny lisa nick sftp> pwd Remote working directory: / sftp> exit
Oops, hang on just one minute: It looks like you can see all of the other users’ directories as well. However, you can’t navigate to those directories:
sftp> cd fred sftp> ls remote readdir("/fred"): Permission denied
You can direct the chrooted user to their own home directory by changing the
ChrootDirectory line in the
sshd_config file like this:
ChrootDirectory /
This quick change makes it look to Nick as though he’s in his own home directory, and he won’t be able to see any other user’s files:
sftp> pwd Remote working directory: /home/nick sftp> sftp> exit [skipworthy@milo ~]$ touch test.txt [skipworthy@milo ~]$ sftp nick@showme nick@showme's password: Connected to nick@showme. sftp> put test.txt Uploading test.txt to /home/nick/test.txt test.txt 100% 0 0.0KB/s 00:00 sftp> ls test.txt sftp>
Where did it go? Check this out:
[root@showme1 ~]# ls /home/nick test.txt
Note that a
chroot jail is not considered to be an adequate security restriction by itself. While it prevents a user from changing out of a restricted directory, there are ways around this (the general idea is referred to in the
chroot(2) man page, which you should take a look at if you are considering using this trick in a production- or business-critical context.)
Wrapping up (for now)
So, you can see that
chroot can be a pretty useful tool. In part 2, I’ll look more at assigning specific directories to users, and providing a shell environment to a remote user without exposing the rest of the server.
New to containers? Download the Containers Primer and learn the basics of Linux containers. | https://www.redhat.com/sysadmin/set-linux-chroot-jails | CC-MAIN-2020-45 | refinedweb | 915 | 50.97 |
18 May 2012 02:19 [Source: ICIS news]
KUALA LUMPUR (ICIS)--Increasing polyethylene (PE) exports from ?xml:namespace>
"Exports from
"While the volumes are marginal in the context of overall
Lacklustre demand in
Widening sanctions against
As of yet, there are no signs of an emerging demand recovery in
"The first sign of a recovery would be in the form of [plastic] converters coming back into the market, but this is not happening. There is not much of a spread between [feedstock] naphtha and PE at the moment," Razak said.
The struggles of converters, most of which are small to mid-size enterprises (SMEs), are illustrated in the China Manufacturing Purchasing Managers Index (PMI) compiled by global investment bank HSBC, he pointed out.
This index, which reflects the activity of SMEs rather than larger companies, has been on an overall downtrend in the past several months.
The China Manufacturing PMI in April rose to 49.3 from 48.3 in March, but still indicated a decline in activity. Any reading above 50 indicates expansion while under 50 indicates contraction.
The figures are in stark contrast to the China Manufacturing PMI released by the China Federation of Logistics and Purchasing (CFLP), where the April PMI rose to 53.3 - up for 5 consecutive months.
By: Joseph Chang | http://www.icis.com/Articles/2012/05/18/9560912/apic-12-iran-pe-exports-weigh-on-weak-china-market-nexant.html | CC-MAIN-2014-52 | refinedweb | 216 | 53.81 |
If an interface member method is implemented in your class without an access modifier, it is by default private.
But methods have to be either public so that they can be called through the interface, or they need to be explicit. Let us assume your interface is implemented as follows:
public interface ITest { bool IsTest(); }
To change the visibility, you can either change the interface from public to internal.
..or you can do explicit interface implementation. Explicit implementation hides the class member so it can only be accessed through the interface. All you have to do is prefix the member with the interface name, as demonstrated here:
public class Test: ITest { bool ITest.IsTest() { return true; } }
..in which case this method will be available only via the interface ITest. This way to implement the method explicitly also hides these methods from intellisense.
Please note that this requirement is only in C# where it requires that implicit interface implementations must be public. In VB.NET you do not require an explicit accessibility keyword.
Tweet | https://www.devcurry.com/2015/03/c-cannot-implement-interface-member.html | CC-MAIN-2021-49 | refinedweb | 173 | 55.74 |
whichItem = Random.Range(0, 2);
var myObj = Instantiate(myStuff[whichItem]) as GameObject;
TestScript mything = myObj.GetComponent<TestScript>();
mything.theString = "woof";
So the above all works fine when tested in Unity (TestScript.cs is attached to the prefab that I am instantiating) but Visual Studio is showing red error lines underneath TestScript. When I mouse over the warnings it shows: The type or namespace name 'TestScript' could not be found (are you missing a using directive or assembly reference?) I've read others say to ignore the warnings but I'd like to know that there isn't something else I should be addressing whether it compiles fine or not.
Hello,
I dont know exactly but it is happening because visual studio can not load all the project files.
restart visual studio once then check it.
hope it helps you to solve the problem.
Thanks Mehul but I tried that too but the red warning lines still show up.
Hi It may be your script is conflicting with predefined or declared scripts.you can try to change the name of the script or , add your script inside a package. For eg
namespace Abc
{
public class A: MonoBehaviour
{
}
}
Is TestScript.cs actually showing in the solution window in VS?
And how are you opening VS? (you need to do it using the "open c# project" in Unity, to get Unity to create the project & solution files)
Thanks Bonfire-Boy. Yes, I am opening it as you said and Unity builds the solution. *but still the red warning lines show up.
TestScript.cs is showing in the VS solution explorer - it's in my Scripts folder - the same folder as my GameRoutine.cs script. To further expand on this: TestScript.cs is attached to my prefab(s) that I am instantiating. GameRoutine.cs is attached to an empty sprite that is in my hierarchy (on the stage) named gamectrlobj. It is simply a fresh test project too so there isn't anything complex going on with assets, structure, etc. Just the two scripts, the gamectrlobj and the 3 identical (other than in name) prefabs. The prefabs are in a folder called Prefabs. The scripts are in a folder called Scripts. Here is my GameRoutine.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameRoutine : MonoBehaviour {
public int numToSpawn = 5;
public GameObject[] myStuff;
private int numSpawned = 0;
public static int whichItem;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (numToSpawn > numSpawned) {
SpawnRandomObject();
}
}
void SpawnRandomObject() {
//spawns item in array position between 0 and 2 as there are three prefabs to pick from
whichItem = Random.Range(0, 2);
var myObj = Instantiate(myStuff[whichItem]) as GameObject;
//get the thing component on your instantiated object
TestScript mything = myObj.GetComponent<TestScript>();
mything.theString= "woof";
Debug.Log(mything.theString);
numSpawned++;
}
}
And here is my TestScript.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour {
public string theString = "meow";
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
Answer by Cuttlas-U
·
Oct 27, 2017 at 06:56 AM
hi;
close unity and try deleting sln and charp files that are in root of your project so unity will creat them again and it may fix your problem ;
also did u install vs tools for unity ?
Answer by tjPark
·
Aug 30, 2018 at 04:16 PM
in my case, I set the mode from debug->release and worked fine(and returned to debug). its next to the play button in VS editor.
Excellent! Thank you!
Answer by AlienNova
·
Oct 26, 2017 at 09:30 PM
It's a bug. It's one of the downsides to not using a supported development environment
Thanks AlienNova. I kind of wondered. Is this confirmed by Unity or anywhere else? If so, I will mark your answer as such. Are there any workarounds to this?
In the absence of any evidence or even explanation, I would be sceptical about this answer. Unity ships with VS these days. Has anyone else reported this as a bug?
They do? This is news to me,
Answer by dawitabraham
·
Aug 03 at 09:28 PM
This worked for me!
Open the project in Visual Studio.
At the bottom of the Solution Explorer, you'll see the list of assembly references.
Select all disabled once -> Right Click -> Reload.
Checking if object intersects?
1
Answer
How to make instantiated buttons permanent in hierarchy?
1
Answer
Material[] Object reference not set when instantiating
2
Answers
Can't assign instantiated object to a variable
1
Answer
changing material color through C# script
0
Answers | https://answers.unity.com/questions/1425994/unity-compiles-fine-but-visual-studio-showing-red.html | CC-MAIN-2020-45 | refinedweb | 771 | 66.13 |
A Little C Primer/C String Function Library
The string-function library requires the declaration:
#include <string.h>
The most important string functions are as follows:.
Contents
strlen()[edit]
The "strlen()" function gives the length of a string, not including the NUL character at the end:
/* strlen.c */ #include <stdio.h> #include <string.h> int main() { char *t = "XXX"; printf( "Length of <%s> is %d.\n", t, strlen( t )); }
This prints:
Length of <XXX> is 3.
strcpy()[edit]
The "strcpy" function copies one string from another. For example:
/* strcpy.c */ #include <stdio.h> #include <string.h> int main() { char s1[100], s2[100]; strcpy( s1, "xxxxxx 1" ); strcpy( s2, "zzzzzz 2" ); puts( "Original strings: " ); puts( "" ); puts( s1 ); puts( s2 ); puts( "" ); strcpy( s2, s1 ); puts( "New strings: " ); puts( "" ); puts( s1 ); puts( s2 ); }
This will print:
Original strings: xxxxxx 1 zzzzzz 2 New strings: xxxxxx 1 xxxxxx 1
Please be aware of two features of this program:
- This program assumes that "s1" has enough space to store the final string. The "strcpy()" function won't bother to check, and will give erroneous results if that is not the case.
- A string constant can be used as the source string instead of a string variable. Using a string constant for the destination, of course, makes no sense.
These comments are applicable to most of the other string functions.
strncpy()[edit]
There is a variant form of "strcpy" named "strncpy" that will copy "n" characters of the source string to the destination string, presuming there are that many characters available in the source string. For example, if the following change is made in the example program:
strncpy( s2, s1, 5 );
-- then the results change to:
New strings: xxxxxx 1 xxxxxz 2
Notice that the parameter "n" is declared "size_t", which is defined in "string.h". Because strncpy does not add '\0' after coping 5 charecters
strcat()[edit]
The "strcat()" function joins two strings:
/* strcat.c */ #include <stdio.h> #include <string.h> int main() { char s1[50], s2[50]; strcpy( s1, "Tweedledee " ); strcpy( s2, "Tweedledum" ); strcat( s1, s2 ); puts( s1 ); }
This prints:
Tweedledee Tweedledum
strncat()[edit]
There is a variant version of "strcat()" named "strncat()" that will append "n" characters of the source string to the destination string. If the example above used "strncat()" with a length of 7:
strncat( s1, s2, 7 );
-- the result would be:
Tweedledee Tweedle
Again, the length parameter is of type "size_t".
strcmp()[edit]
The "strcmp()" function compares two strings:
/* strcmp.c */ #include <stdio.h> #include <string.h> #define ANSWER "blue" int main() { char t[100]; puts( "What is the secret color?" ); gets( t ); while ( strcmp( t, ANSWER ) != 0 ) { puts( "Wrong, try again." ); gets( t ); } puts( "Right!" ); }
The "strcmp()" function returns a 0 for a successful comparison, and nonzero otherwise. The comparison is case-sensitive, so answering "BLUE" or "Blue" won't work.
There are three alternate forms for "strcmp()":
strncmp()[edit]
- A "strncmp()" function which, as might be guessed, compares "n" characters in the source string with the destination string:
"strncmp( s1, s2, 6 )".
stricmp()[edit]
- A "stricmp()" function that ignores case in comparisons.
strnicmp()[edit]
- A case-insensitive version of "strncmp" called "strnicmp".
strchr()[edit]
The "strchr" function finds the first occurrence of a character in a string. It returns a pointer to the character if it finds it, and null if not. For example:
/* strchr.c */ #include <stdio.h> #include <string.h> int main() { char *t = "MEAS:VOLT:DC?"; char *p; p = t; puts( p ); while(( p = strchr( p, ':' )) != NULL ) { puts( ++p ); } }
This prints:
MEAS:VOLT:DC? VOLT:DC? DC?
The character is defined as a character constant, which C regards as an "int". Notice how the example program increments the pointer before using it ("++p") so that it doesn't point to the ":" but to the character following it.
strrchr()[edit]
The "strrchr()" function is almost the same as "strchr()", except that it searches for the last occurrence of the character in the string.
strstr()[edit]
The "strstr()" function is similar to "strchr()" except that it searches for a string, instead of a character. It also returns a pointer:
char *s = "Black White Brown Blue Green"; ... puts( strstr( s, "Blue" ) );
strlwr() and strupr()[edit]
The "strlwr()" and "strupr()" functions simply perform lowercase or uppercase conversion on the source string. For example:
/* casecvt.c */ #include <stdio.h> #include <string.h> int main() { char *t = "Hey Barney hey!"; puts( strlwr( t ) ); puts( strupr( t ) ); }
-- prints:
hey barney hey! HEY BARNEY HEY!
These two functions are only implemented in some compilers and are not part of ANSI C. | http://en.wikibooks.org/wiki/A_Little_C_Primer/C_String_Function_Library | CC-MAIN-2015-18 | refinedweb | 759 | 75.61 |
Performance issues with simple test on Qt5 vs Qt4 on ARM device without GPU
Hello!
I've been running some simple tests on Qt5.4.1 and Qt4.8.6 on an ARM processor without a GPU (so on Qt5, the program uses linuxfb, and on Qt4, it uses the QWS). I expected Qt5 to be faster because it won't have the overhead of the QWS, but my tests show otherwise.
Here is what I used to test it:
//lines.h #pragma once #include <QWidget> class Lines : public QWidget { Q_OBJECT public: Lines(QWidget *parent = 0); public slots: void animate(); protected: void paintEvent(QPaintEvent *event); void drawLines(QPainter *qp); int frameCounter; }; //lines.cpp #include "lines.h" #include <QPainter> #include <stdio.h> #include <QTimer> #include <QTime> #define NUMSHAPES 1000 QTime t; Lines::Lines(QWidget *parent) : QWidget(parent) { frameCounter = 0; QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(animate())); #ifndef QT4USED timer->setTimerType(Qt::PreciseTimer); #endif timer->start(10); t.start(); } void Lines::paintEvent(QPaintEvent *e) { Q_UNUSED(e); QPainter qp(this); drawLines(&qp); double a = t.restart(); fprintf(stderr,"time: %lf fps: %lf\n", a, 1000.0/a); } void Lines::animate() { frameCounter++; //repaint(); update(); } void Lines::drawLines(QPainter *qp) { for ( int c = 0; c < NUMSHAPES; c++ ) { QPen pen(Qt::red, 1, Qt::SolidLine); qp->setPen(pen); int xbegin, xend, ybegin, yend ; xbegin = xend = frameCounter*10; ybegin = 0; yend= 250; qp->drawLine( xbegin, ybegin, xend, yend ); } } //main.cpp #include "lines.h" #include <QApplication> #include <stdio.h> int main(int argc, char *argv[]) { QApplication app(argc, argv); Lines window; window.resize(640, 480); window.setWindowTitle("Lines"); window.show(); return app.exec(); }
In summary, the code starts a timer with an interval of 10 msecs, and calls update() on the Lines widget. The widget itself paints a 1000 drawLines() every frame, and then outputs the time taken between each frame to stderr.
This program causes 100% cpu usage on both Qt5 and Qt4, but Qt5 takes an average of 55 msecs per frame, while Qt4 takes 50. While this isn't too different, does anyone have a clue why Qt5 is actually slower? Shouldn't it be at least as fast because the QWS is out of the picture?
But the bigger problem is the CPU usage when the widget paints a 100 lines every frame instead of 1000. On Qt5, it paints a frame every 13 milliseconds, and the CPU usage is still 100%, but on Qt4, it paints a frame every 10 milliseconds and the CPU usage is about 85%. Any ideas why Qt5 seems to be underperforming?
- sierdzio Moderators
Interesting. Could you try running both "versions" through callgrind or some other profiling tool? Maybe that will help somewhat.
The only code difference you add here (between Qt 4 and 5) is timer precision - but that should not make much difference (please check, though).
The only thing I can think of right now is that QPainter's handling of thin lines and antialiasing has been slightly changed when going from Qt 4 to Qt 5. So perhaps Qt 5 is using more time to properly draw the line. Or the reason could be completely different: maybe linuxfb painting is slower on your device?
@sierdzio Thanks a lot for the reply!
I'll try running it through a profiler, and looking through the QPainter source. Out of curiosity, I also tried painting absolutely nothing in the paint event, so that all the timer will do is call update() every 10 milliseconds. In Qt4, that gave me a 100% idle cpu, but in Qt5, it was about 15% idle. So I changed the update() call to a repaint() call, and saw that the Qt4 idle time dropped to 33%, but the Qt5 one had no change(still 15% idle)...Were there any major changes to how Qt updates/repaints between 4 and 5?
- sierdzio Moderators
Hm. You would have to ask Qt developers (on IRC, or development mailing list) to get a definite answer. In Qt4->5 transition, the whole painting architecture was changed, so it is understandable there are differences in performance. What is not so good is that (from your data, and sporadic reports I see in other places) the performance of Qt5 is worse instead of better. | https://forum.qt.io/topic/52556/performance-issues-with-simple-test-on-qt5-vs-qt4-on-arm-device-without-gpu | CC-MAIN-2017-39 | refinedweb | 708 | 73.27 |
A.M. Kuchling and Moshe Zadka
A new release of Python, version 2.0, hass is in the file Misc/unicode.txt in the Python source distribution; it's also available on the Web at.is a string naming the encoding to use. The
errorsparameter, unicodedata, provides an interface to Unicode
character properties. For example,
unicodedata.category(u'A')
returns the 2-character string 'Lu', the 'L' denoting it's a letter,
and 'u' meaning that it's uppercase.
u.bidirectional(u'\x0660') returns 'AN', meaning that U+0660 is
an Arabic number.
The codecs module contains functions to look up existing encodings
and register new ones. Unless you want to implement a
new encoding, you'll most often use the
codecs.lookup(encoding) function, which returns a
4-element tuple:
(encode_func,
decode_func, stream_reader, stream_writer).
(string, length). string is an 8-bit string containing a portion (perhaps all) of the Unicode string converted into the given encoding, and length tells you how much of the Unicode string was converted.
(ustring, length), consisting of the resulting Unicode string ustring and the integer length telling how much of the 8-bit string was consumed. string module, with the arguments reversed. In other
words,
s.join(seq) is equivalent to the old
string.join(seq, s). "-without-cycle-gc" switch when running the''.
Various minor changes have been made to Python's syntax and built-in functions. None of the changes are very far-reaching, but they're handy conveniences.
A new syntax makes it more convenient to call a given function
with a tuple of arguments and/or a dictionary of keyword arguments.
In Python 1.5 and earlier, you'd use the apply()
built-in function:
apply(f, args, kw) calls the
function f() with the argument tuple args and the
keyword arguments in the dictionary kw. repr() of its argument. This was
also added from symmetry considerations, this time for symmetry with
the existing '.; inital support for it is in Python 2.0. Dynamic loading works, if you specify ``configure -with-dyld -with-suffix=.x''. Consult the README in the Python source distribution for more instructions.
An attempt has been made to alleviate one of Python's warts, the often-confusing, Misc/find_recursionlimit.py. .append() and .insert().
In earlier versions of Python, if
L is a list,
L.append(
1,2 ) appends the tuple
(1,2) to the list. In Python 2.0 this
causes a AttributeError exception has a more friendly error message,
whose text will be something like
'Spam' instance has no attribute 'eggs'.Gb; this made the tell()
method of file objects return a long integer instead of a regular
integer. Some code would subtract two file offsets and attempt to use
the result to multiply a sequence or slice a string, but this raised 'L' character, though: PyModule_AddObject(), PyModule_AddIntConstant(), and. PyOS_getsig() gets a signal handler and PyOS_setsig() will set a new handler. adminstering a Python installation something of a chore.
The SIG for distribution utilities, shepherded by Greg Ward, has
created the Distutils, a system to make package installation much
easier. They form the setup.py script. For the simple case, when the software contains only .py files, a minimal setup.py can be just a few lines long:
from distutils.core import setup setup (name = "foo", version = "1.0", py_modules = ["module1", "module2"])
The .pkg files are in various stages of
development.
All this is documented in a new manual, Distributing Python Modules, that joins the basic set of Python documentation.:.
A number of new modules were added. We'll simply list them with brief descriptions; consult the 2.0 documentation for the details of a particular module.
sys.exitfuncdirectly should be changed to use the atexit module instead, importing atexit and calling atexit.register() with the function to be called on exit. (Contributed by Skip Montanaro.)
IDLE is the official Python cross-platform IDE, written using Tkinter. Python 2.0 includes IDLE 0.6, which adds a number of new features and improvements. A partial list:, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.. | http://www.python.org/download/releases/2.0/new-python | crawl-002 | refinedweb | 679 | 60.11 |
#include "orconfig.h"
#include "lib/log/util_bug.h"
#include "lib/malloc/malloc.h"
Go to the source code of this file.
Macros for C weak-handle implementation.
A 'handle' is a pointer to an object that is allowed to go away while the handle stays alive. When you dereference the handle, you might get the object, or you might get "NULL".
Use this pattern when an object has a single obvious lifespan, so you don't want to use reference counting, but when other objects might need to refer to the first object without caring about its lifetime.
To enable a type to have handles, add a HANDLE_ENTRY() field in its definition, as in:
struct walrus { HANDLE_ENTRY(wlr, walrus); // ... };
And invoke HANDLE_DECL(wlr, walrus, [static]) to declare the handle manipulation functions (typically in a header):
// opaque handle to walrus. typedef struct wlr_handle_t wlr_handle_t; // make a new handle struct wlr_handle_t *wlr_handle_new(struct walrus *); // release a handle void wlr_handle_free(wlr_handle_t *); // return the pointed-to walrus, or NULL. struct walrus *wlr_handle_get(wlr_handle_t *). // call this function when you're about to free the walrus; // it invalidates all handles. (IF YOU DON'T, YOU WILL HAVE // DANGLING REFERENCES) void wlr_handles_clear(struct walrus *);
Finally, use HANDLE_IMPL() to define the above functions in some appropriate C file: HANDLE_IMPL(wlr, walrus, [static])
Definition in file handles.h.
Definition at line 60 of file handles.h. | https://people.torproject.org/~nickm/tor-auto/doxygen/handles_8h.html | CC-MAIN-2019-39 | refinedweb | 227 | 56.55 |
README
expeditious-engine-memoryexpeditious-engine-memory
An in memory engine for expeditious. Cache entries are - you guessed it - stored in the node.js process memory. This cache engine will lose everything stored if your process restarts, and could lead to memory bloat and slow garbage collections if you're not careful with the size and volume of entries!
UsageUsage
You can use this module standalone or with expeditious which is the recommended approach since it simplifies interactions and allows you to easily switch cache engines.
var expeditious = require('expeditious'); var countries = expeditious({ // Use the expeditious memory engine engine: require('expeditious-engine-memory')(), // Prefix all entries with 'countries' namespace: 'countries', // Auto parse json entries objectMode: true, // 1 hour timeout for entries defaultTtl: (60 * 1000 * 60), }); countries.set({ key: 'ireland', value: { population: '4.595 million', capital: 'Dublin' } }, function (err) { if (!err) { console.error('failed to add "ireland" to the cache'); } else { console.log('add "ireland" to the cache'); } });
APIAPI
Each API function takes a callback function as the last parameter and it receives up to two arguments as per node.js convention, error err and an optional result, res.
set(key, value, expire, callback)set(key, value, expire, callback)
Set a key (String) in the cache with a given (String) value. expire must be a Number greater than 0.
get(key, callback)get(key, callback)
Get a specific item from the cache. Returns null if the entry is not found.
del(key, callback)del(key, callback)
Delete a specific item from the cache. Callback receives only an error parameter.
keys(callback)keys(callback)
List all keys that this engine instance contains.
ttl(key, callback)ttl(key, callback)
Get the time left before key expires. Returns null as res if the entry is not found.
flush(callback)flush(callback)
Flush all items from the engine instance. | https://www.skypack.dev/view/expeditious-engine-memory | CC-MAIN-2022-33 | refinedweb | 303 | 50.02 |
Hi Todd,
I check my github , reload it , and didn't find that bug.
Does the code works at least now.
Daniel
Code: Select all
git clone
Hi Daniel (came here from the other post: ... 9&start=50).Hi Daniel (came here from the other post: ... 9&start=50).danjperron wrote:It is now possible to program the PIC12F1840 using the RapsberryPi without any transistor or resistor.
I just add the application , in python, into my Pic A/D converter Git repository. search for 'burnLVP.py'.
Daniel
Yes, CONFIRMED, it do not work on 12F1822 and 16F1825 and 16F1829...Yes, CONFIRMED, it do not work on 12F1822 and 16F1825 and 16F1829...danjperron wrote:Thanks Valter again,
Could you confirm that the bulk erase doesn't work with the pic12F1822 and the other ones you specify when the LVP config flag is set before programming.
Daniel
I will run some tests using a MOSFET (2N7000) as bidirectional 3v3 to 5v and will report the results here...I will run some tests using a MOSFET (2N7000) as bidirectional 3v3 to 5v and will report the results here...danjperron wrote:Thanks Valter again,
Next thing to check will be the 3.3V . Use a sparkfun voltage converter and try 5V instead.
Daniel
YES, the 1822 is Rev06... YES for the 16F1825 too, Rev00 (affected)...YES, the 1822 is Rev06... YES for the 16F1825 too, Rev00 (affected)...danjperron wrote:Hi Valter,
could you confirm that the pic12F1822 is revision A6?
This is a problem for people with old PIC cpu. The row erase doesn't touch the config and if everything is lock, you are out of luck.
Daniel
Yes, CONFIRMED. I have more 1822 parts with Rev 8 here... tested, works (right now I am using the level converter)!Yes, CONFIRMED. I have more 1822 parts with Rev 8 here... tested, works (right now I am using the level converter)!danjperron wrote:Hi Valter,
I did check my pic16F1823 and it is revision 8. This is why I never find that problem.
Even if I buy the pic12f1822 , they will work since they will be revision 8.
At least we know why and it shouldn't be a problem on brand new i.c.
Daniel
Code: Select all
def Pic12F1822_BulkErase(): Release_HVP() sleep(0.1) Set_HVP() ###SendMagic() print "Bulk Erase Program", SendCommand(C_LOAD_CONFIG) LoadWordPlus(0x3FFF) SendCommand(C_BULK_ERASE_PROGRAM) sleep(0.1) print ", Data.", SendCommand(C_BULK_ERASE_DATA) sleep(0.1) print ".... done." Release_HVP() sleep(0.1) Set_HVP() ###SendMagic()
{Co-uController}{Co-uController}danjperron wrote:...You can't be sure that the RPi will be always in time. Adding real time driver into the kernel is also time consuming...
Then why not using an other cpu to do the stuff! I know you could use the Pollolu serial servo but it is for one part maybe to rigid. So I decide to use a very small cpu , the Microchip pic12F1840...
Daniel
Return to “Automation, sensing and robotics” | https://www.raspberrypi.org/forums/viewtopic.php?f=37&t=41245&start=25 | CC-MAIN-2019-39 | refinedweb | 489 | 77.13 |
On Tue, Oct 23, 2012 at 01:46:46PM -0400, Laine Stump wrote: > This is a repost of > > > > with PATCH 03/12 squashed into 01/12. There are no other changes. > > ************************************ > > PATCH 01/11 defines a couple new macros/functions to simplify > inserting/deleting items in the middle of an array. The remaining > patches switch over various pieces of existing code to use these new > macros rather than directly calling memmove, etc. > > There are several other places where these macros could *almost* be > used, except that they use the model of pre-allocating the larger > array, then performing a bunch of operations (that may fail) and then > finally move items around in the array and adjust its count. I'm > wondering if I should add a flags arg to these to allow for specifying > a "Don't realloc" flag - when it was given, the memory allocation > operation would be presumed already done (in the case of insert) or to > be done after return (for delete). Any opinions on that? (such as > maybe "that's too many options!") I haven't reviewed the patches in detail, but I have to say that I like the addition of these array helpers. Daniel -- |: -o- :| |: -o- :| |: -o- :| |: -o- :| | https://www.redhat.com/archives/libvir-list/2012-October/msg01398.html | CC-MAIN-2014-15 | refinedweb | 204 | 68.91 |
Mathematical construct, the extension of a predicate, that is, all things with a given property. Given a predicate A(x), we can write { x | A(x)} to mean "The class of all x such that A(x) is true."
An object is an element of a class if it satisfies the predicate that defines it. Classes may not be considered as elements of classes or sets; only sets may be. If a given set has the same elements as a given class, then the set is said to represent the class; a large portion of set theory is dedicated to determining which classes are represented by sets.
Some examples of classes include:
In the early 1900s, several paradoxes arose which cast the validity of set theory into question. The most famous of these is Russell's Paradox, which occurs if you allow the class of all sets which do not contain themselves as elements to be represented by a set. The class of all sets cannot be represented by a set, otherwise the class that results in Russell's paradox would have to be. In general, if {x|A(x)} is represented by a set, then {x|~A(x)} cannot be, otherwise, the union of those two sets would be a set representing the class of all sets. Of course, this does not exhaust the classes that are not represented by sets!
Bertrand Russell and Alfred North Whitehead, in their Principia Mathematica, introduced a system known as type theory which avoided these paradoxes. However this system was unsatisfyingly complex. And so type theory was eventually simplified into the distinction between classes and sets.
In four years of undergraduate education, I have never before been asked to or needed to
apply such mental energy to schoolwork as this final exam is asking me to.
And that's the point of it, according to Professor Ken Safir. I've never had a better professor. He
doesn't just teach, he explains. He builds up paradigms of thought bit by bit until everyone in the class
is bouncing in their seats with expectation because they've all figured out on their own what's coming
next. He makes things make sense. And he doesn't assign busywork. Even the final exam is intended
to teach us something -- he informed us outright that much of the material on the final was never
discussed in class -- "but some deep thinking should allow you to synthesize what you need for the
solution."
Why can't all classes be like this? It bothers me that universities don't draw distinctions between
"hard" and "easy" classes.
I'm expecting to earn a B+ in this class -- and I do mean earn. I've struggled with the material,
and overcome it, and burned new and useful pathways into my cognitive machinery. I learned in this
class. Time and again, poring over the week's material until finally a light went on and I Understood.
On the other hand, I'm expecting to receive an A in Social Psychology. I went to class twice the entire
semester. The tests are open-notes, multiple-choice. It's a 300-level, 3-credit class, just like Syntax.
My "academic standing", whatever that is, will be raised more by Social Psych -- a class I didn't
attend and received no benefit from -- than by Syntax, a class that caused me to do more deep thinking
than any other I've ever taken.
There must be a better way.
Class members are divided into three groups: public, private, and protected.
For example:
class A
{
public:
int GetValue();
int SetValue();
private:
int nValue;
};
class A
{
public:
int GetValue();
int SetValue();
private:
int nValue;
};
int GetValue();
int SetValue();
private:
int nValue;
};
Most Western countries have a class system, to one degree or another. If your parents are poor you will probably be poor too, but you might improve your situation through hard work or luck. Likewise, you might be better able to provide for your children.
In a caste system, the social group you are born into is the caste you will die in, period. I believe India still has a caste system, which is closely tied to their religion. They believe that if you do well in life, then in the next life, you may be reincarnated into a more prestigious caste. This belief helps provide stability to a social system that would otherwise be weakened by the great number of people in low castes who are helpless to do anything about it within their culture.
The acronym for Custom Local Area Signalling Service. This is the SS7 service that allows automatic call return (*69) and repeat dialing (*66). For *69 the person recieving the call does not answer. The recipiant then picks up the phone and dials *69. The SSP serving them initiates a query on the last number to call the line to an SCP. The SCP does a lookup to find out where the calling number resides and launches a query to the SCP responsible for that area. This SCP then determines the end SSP and notifies it of the request to initiate a call to the originating number. The SSP then sends a response to the SSP that originated the CLASS query and a normal ISUP call is started.
A 1983 book by essayist, historian, sociologist, and literary critic Paul Fussell which attempts to detail and analyze the structure of the American status system. It became a personal favorite years ago, and still greatly influences the way I perceive fellow Americans.
Fussell's cruelty is somewhat mitigated by its equality: he has unabashed disdain for all classes. Though we, as readers, may wince when we find our values, beliefs, and cultural artifacts singled out for ridicule, there is a comfort in the knowledge that his analyses will soon pass to less sensitive targets (i.e. our neighbors).
The American status system is divided into nine classes:
Fussell goes to great lengths to clarify that it is not riches alone that define class, but rather a combination of wealth, style, taste, awareness, manners and traditions which generally persist from birth to death. There is a tendency for class drift, but fundamental markers of class designation are unlikely to change even through radical changes in income. For it isn't that the three classes at the top don't have money. Rather, money alone doesn't define them, for the way that they have their money is largely what matters.
The name of the "top out-of-sight" class comes from an interview with a Boston blue-collar worker, who when asked about wealth said, "When I think of a really rich man, I think of one of those estates where you can't see the house from the road." For Fussell, the top class. They tend to be removed from scrutiny, escaping the down-to-earth calculations of sociologists, poll-takers, and consumer researchers. It's not commonly studied because it's literally out of sight.
The next class down, the upper class, differs from the top-out-of-sights in two main ways. First, although it inherits a good bit of money, it earns quite a bit too, typically from some attractive (if slight) work without which it would feel bored or vaguely ashamed. They tend to make money owning banks, controlling think tanks or foundations, running the more historic corporations, and busying themselves with things such as universities, the Committee for Economic Development, or the Executive branch of the government. But more importantly, the upper class is visible, often ostentatiously so. Fussell claims that while the out-of-sights have spun away from Veblen's theory of conspicuous consumption, the mere upper class have been left to carry on instead. When you pass a house with an impressive facade visible from the street, you know it is occupied by a member of the upper class.
While Fussell's cruelty may be equally distributed, it seems at times that he reserves an especially acute edge for the middle class. The middle class is distinguishable by its earnestness and psychic insecurity rather than by its middle income. Rich people who remain terrified at what others think of them, who are obsessed with doing everything right so as to avoid criticism, are stubbornly middle class. The middle class is the place where table manners assume an awful importance and mouthwashes and deodorants abound. The middle class is ascribed a certain "status panic" and continually looks to borrow status from higher elements. There is no latitude for individuality and eccentricity; you are nothing if not "part of the team.".
The middles lust for the illusion of weight and consequence, seeking heraldic validation ("This beautiful embossed certificate will show your family tree") and issuing annual family newsletters announcing the more recent triumphs in the race to become "professional". Nervous lest she be considered nobody, the middle-class wife is careful to dress way up when she goes shopping. Correctness and doing the right thing become obsessions, prompting thank-you notes for the most ordinary dinner parties. The desire to belong overwhelms. The middle-class man, according to Fussell, is scared. He is always somebody's man, be it the corporation's, the government's, or the army's.
The young men of the middle class are, in Fussell's words, "chips off the old block." You can see them on airplanes, being forwarded from one corporate training program to another. They consume John T. Molloy's books, hoping to break into the upper-middle class by formulas and mechanisms. Their talk is of the bottom line, and for no they are likely to say no way.
The disappearance of the lower-middle class is an area of concern for Fussell, one that forced him to delete that class entirely, and replace it with varying degrees of proletariat. The inflation of the 60's and 70's and the social demolition that resulted pauperized the true lower middle class, a class whose solid high-school education and addiction to saving and planning maintained it in a position above the pure working class. The former low white-collar people are now simply working machines, and the wife usually works as well as the husband.
The kind of work and the sort of anxiety that besets one as a result provide the main delineations of the proletariat for Fussell. The high proles are the skilled workers and craftsmen, such as printers. The mid-proles are the operators - think Ralph Cramden, the bus drivers. The low proles are unskilled labor, like longshoremen. The special anxiety of the high proles is fear about loss or reduction of status: you're proud to be a Master Carpenter, and you want the world to know the difference between you and a laborer. The special anxiety of the mid-proles is fear of losing the job. And of the low proles, the "gnawing perception that you're probably never going to make enough or earn enough freedom to have and do the things you want."
Encapsulation is key to the idea of classes, and OOP. Ideally, classes should be a representation of some object in the real world that we can directly relate to - for instance, a Rectangle class should be able to define its position, size - everything about it we would expect to know in the real world - and allow us to manipulate it as we would in the real world.
Classes contain two main things to allow them to do this: data members and member functions. The data members are the bits of memory that store the information a class needs to do its job, and the member functions are the actual operations that provide the functionality of the class.
Objects communicate with each other by calling each other's member functions (also known as "sending a message" to that object). It is considered very bad form to direct manipulate another objects' data members, so classes should provide what are commonly known as "Get/Set" functions (because, say, for a data member called Size, they will usually be called GetSize() and SetSize()) to manipulate the data. This is very important for one main reason: consistency of state.
If an object is allowed to directly manipulate another object's data members, then its member functions essentially "lose track" of these data members. Imagine a Rectangle class that only allows itself to be 200 pixels wide. If another object sets its width to 250 pixels, it is likely the class will start to behave incorrectly. The whole idea of OOP is that an object gets to decide for itself how things are done, and that every other class in the system doesn't really need to know how these things are done. If objects are going to start messing around with each other's internal data, this whole system falls down.
Now for a little programmerese (as if the above wasn't enough!) Classes, in general, can either exist in solution space or implementation space. Remember how I said a class represents some concept in the real world? That's a class in solution space - it represents an object that exists as part of our solution, such as letters, words and fonts in a word processor. These types of classes are often referred to as abstract types (but this is also a more general term, so don't get too wrapped up with it).
Classes in implementation space are classes representing objects that exist in the implementation of a program and have a relevence to it, but aren't immediately obvious as part of the solution. These are often concrete types. As an example, in implementing a word processor, I might use a linked list or a deque to store sentences, but this isn't immediately obvious from problem. Linked lists are needed to implement the program, but they cannot be directly mapped to an object or concept in the problem.
One of the main tasks of Object Oriented Design is what's called "Finding the classes", which is to say, deciding what classes should be used in a system to represent and build the solution.
Also, a state of grace, stylishness, or cool; possessing je ne sais quoi. Slang, probably derivative of a desire to emulate the higher ranks in society; classy;
a class act
a classy broad
"Ain't ya got no class?"
With respect to the zephyr messaging system, a class functions as a cross between a BBS and a chatroom. Each zephyr has a class and an instance. Standard personal zephers are class "message", instance "personal", but a user can send a message to any class or instance.
To get messages sent to a class, a user subscribes to that class. Users may subscribe to all instances of a class by using a wildcard, or to specific instances. Users may not, however, use a wildcard to subscribe to all classes. This allows the existence of private zephyr classes, with unpublished names.
Certain zephyr classes and instances are well-known and high traffic, such as MIT's class help. On many such public classes, it is conventional and good manners to use the instance of your zephyr to denote your topic, to enable many parallel conversations.
There.
Class (?), n. [F. classe, fr. L. classis class, collection, fleet; akin to Gr. a calling, to call, E. claim, haul.], gemera,.
© Webster 1913.
Class (?), v. t. [imp. & p. p. Classed (?); p. pr. & vb. n. Classing.] [Cf. F. classer. See Class, n.]
To arrange in classes; to classify or refer to some class; as, to class words or passages.
⇒ In scientific arrangement, to classify is used instead of to class.
Dana.
To divide into classes, as students; to form into, or place in, a class or classes.
Class, v. i.
To grouped or classed.
The genus or famiky under which it classes.
Tatham.
Log in or register
to write something here or to contact authors. | http://everything2.com/title/CLASS | CC-MAIN-2013-48 | refinedweb | 2,671 | 60.65 |
React Events & Forms: Build a Real-time Input
One of the trickiest parts of learning React is understanding forms and events. In this short tutorial we will create a form and output its content, in real-time, to the webpage. You should already have
create-react-app installed.
To start, create a new React app and change into its directory.
$ create-react-app realtime-input $ cd realtime-input $ npm start
The final command will start the server and open a webpage at.
The only file we need to change is
App.js. In your text editor, remove much of the default text and add a basic input form.
import React, { Component } from 'react'; class App extends Component { render() { return ( <div> Change name: <input type="text" /> </div> ) } } export default App;
Now we want a way to access the event payload of our input which we can do with
onChange, a React synthetic event. We need to capture the payload and store it in our local state. In React data flows down in a unidirectional way from parent to child components. In this case we’re sending data up from a component to the state so we must use a callback function.
Callbacks are a core part of JavaScript and allow us to pass in functions as arguments. We’ll create a handler callback function
handleChange which will “handle” the result of our event payload. Then we need to bind this new method to our
App component and update the state with
setState().
Here is the updated code.
import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = { username: 'wsvincent' }; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({ username: e.target.value }); } render() { return ( <div> Hello {this.state.username} <br /> Change name: <input type="text" value={this.state.username} onChange={this.handleChange} /> </div> ); } } export default App;
If you try webpage at now you’ll see that whatever is typed in the input form is then outputted above.
To review:
- we created an input and then used
onChangeto capture the event payload in a callback function called
handleChange
- added a
valueto make our input a controlled component
- wrote a
handleChangemethod and accessed the event payload
eto update
usernamewith the value of the input
- bound
handleChangeto our
Appcomponent
- set an initial value for
username
Once you internalize how callback functions work with forms and events, much of React makes a lot more sense.
Want to learn more React? I have a list of recommended React books and JavaScript books. | https://wsvincent.com/react-realtime-input/ | CC-MAIN-2020-05 | refinedweb | 422 | 64.1 |
I have a function that counts how often a list of items appears in
rows
def count(pair_list):
return float(sum([1 for row in rows if all(item in row.split() for item in pair_list)]))
if __name__ == "__main__":
pairs = [['apple', 'banana'], ['cookie', 'popsicle'], ['candy', 'cookie'], ...]
# grocery transaction data
rows = ['apple cookie banana popsicle wafer', 'almond milk eggs butter bread', 'bread almonds apple', 'cookie candy popsicle pop', ...]
res = [count(pair) for pair in pairs]
len(rows)
10000
18000
pairs
count()
from multiprocessing.dummy import Pool as ThreadPool
import multiprocessing as mp
threadpool = ThreadPool(processes = mp.cpu_count())
res = threadpool.map(count, pairs)
count()
threadpool.map
1) The overall complexity of calculations is enormous, and it comes from different sources:
a) You split row on low level of calculation, so python has to create new row split for every iteration. To avoid this, you can pre-calculate rows. Something like this will do the job (with minor changes in "count" function):
rows2 = [row.split() for row in rows]
b) You compare list items one by one, even though you only need to check existence of word in another list. Here we can tweak it more (and use rows3 instead of rows2 in "count" function):
rows3 = [set(row.split()) for row in rows] def count(pair_list): return float(sum([1 for row in rows3 if all(item in row for item in pair_list)]))
c) You check every word in pairs with every word in rows. Calculation takes 2*len(row)*len(rows) iterations per call of "count" function for original version, while it can take less. For option b) it can be down to 2*len(rows) in good case, but it's possible to make one set lookup per pair, not 2. The trick is to make preparation of all possible word*word combinations for every row and check if corresponding tuple exists in this set. So, in main function you create complex immutable search structure:
rows4 = [set((a, b) for a in row for b in row) for row in rows2]
And now "count" will look different, it takes tuple instead of list:
def count2(pair): return float(len([1 for row in rows4 if(pair in row)]))
So you call it a bit different: res = [count2(tuple(pair)) for pair in pairs]
Note that search structure creation takes len(row.split())^2 per row in time and space, so if your row can be long, it's not optimal. After all, option b) can be better.
2) You can predict number of calls for "count" - it's len(pairs). Count calls of "count" function and make debug print in it for, say, every 1000 calls. | https://codedump.io/share/ZZBtq6bp5a79/1/parallelism-inside-of-a-function | CC-MAIN-2017-30 | refinedweb | 445 | 68.91 |
Opened 7 years ago
Closed 6 years ago
Last modified 6 years ago
#12812 closed (fixed)
Inheriting from comments breaks comment moderation
Description
I created a new kind of comment called TreeComment which (ultimately) subclasses Comment (in contrib.comments)
Essentially, I have a TreeCommentBase which subclasses Comment and is an abstract class. Then TreeComment subclasses TreeCommentBase. This is all in a custom app called treecomments.
Now in the moderation code, we have:
signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
which relies on get_model() which is defined in the init.py file in comments. This causes a wrong model to be sent (my model is TreeComment, not Comment).
If I replace it with treecomments.get_model() (and create that function under init.py - I needed it for something else anyway), then it all works.
Am I doing something wrong? Is there a more proper way of subclassing? For now I'll just subclass Moderator and customize to fix this...
Change History (10)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
comment:3 Changed 7 years ago by
Thanks for pointing it out, but it still didn't work.
In my settings.py file, I put:
I had already created the get_model() in init.py for treecomments.
Yet, it doesn't work if I simply subclass CommentModerator and import moderator from django.contrib.comments.moderation. The funny thing is that if I simply copy and paste the moderation.py file into my models.py file, everything works fine: It correctly detects the new comments app. Could I be handling some imports incorrectly?
comment:4 Changed 7 years ago by
I cannot recreate any problem with the proper model being used in the above-noted moderation signal connections by following the documented method pointed to above. You haven't really provided enough information to recreate whatever you are seeing, and at this point the problem seems better suited to django-users than a ticket. As near as I can tell there is documented way to do what you are asking to do, and in my testing it works. There is also a test of
comments.get_model() returning the correct model in the comment tests, and that is passing.
If you'd like to pursue this further please follow up on django-users with enough specifics of your models and settings to allow someone to recreate the issue, and also indicate how you are observing the wrong model being returned by
comments.get_model(). I tested it by putting a breakpoint in my custom comment
app get_model() and observing that it was hit twice when I entered:
from django.contrib.comments.moderation import moderator
from a manage.py shell. From the stack trace I could see it was hit once for each of those signal connection lines noted above.
comment:5 Changed 6 years ago by
Reopening because I stumbled upon the exact same problem. Basically, it is almost like a race condition. When the django.contrib.comments.moderation module is imported, the Moderator class is instantiated which causes the connect() method to be called. The connect() method calls comments.get_model() which returns an instance of django.contrib.comments.models.Comment which causes the bug. It happens before python has evaluated your init.py file which contains the get_model() function definition. So the signal connection code has to be somehow delayed until after Python has evaluated init.py.
comment:6 Changed 6 years ago by
A brief review tells me that you're subclassing the wrong thing. Like kmtracey said, please raise this issue on django-users, if you haven't already. Feel free to re-open the ticket if you've confirmed there that it's a bug.
comment:7 Changed 6 years ago by
I think there's something up here. I've created a testcase that's as simple as I can make it to demonstrate the situation I've come across that seems to cause this error.
This project is an extremely simple weblog, with comments that are extended from django.contrib.comments:
As it is, the moderation works fine - if enable_comments on an Entry is set to false, then posting a comment is prevented.
But if you add "from weblog.models import Entry" to either customcomments/forms.py or customcomments/models.py, then moderation is ignored, and comments can always be posted. (Why would you add this? Because you might want to extend the comment class to use something from the Entry model.)
Checking what's happening in django/contrib/comments/init.py's get_model() function, in the first case it's returning a CommentWithTitle class. But in the second case, when moderation isn't working, it's returning a standard Comment class.
I'm too new to Django to know how to proceed with this, and whether this really is a bug or it's something I've done, but after a couple of days of poking at this (and posting to django-users today), I'm stumped.
comment:8 Changed 6 years ago by
Thank you for the example project philgyford. I have confirmed your reported (mis)behaviour.
When
contrib.comments attempts to import your custom comments app and check for its
get_model attribute, for example, your custom
__init__.py imports the custom
models.py/
forms.py -- if either of those import something from weblog.models, you're then back to importing moderation, so the custom comments app imports with only
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] -- no
get_model or
get_form. Which means the moderator defaults to the standard
Comment model, etc.
For now I'll fix this by adding documentation warning developers to avoid cyclic imports involving moderation when developing custom comment apps. When smarter registration mechanisms (e.g.
startup.py) land, cyclic moderation-registration imports should be quite easily avoided.
This page:
appears to document the correct way to get your own model returned by that | https://code.djangoproject.com/ticket/12812 | CC-MAIN-2017-04 | refinedweb | 994 | 58.48 |
External Flash lose files
- serafimsaudade last edited by
Hi,
I have install in 2019 11 wipy 3. And used flash to save some configs. Everything has runs ok until December 2020, when all the 11 wipy became offline. I bring them to the office to check the problem.
The firmware installed on the devices didn't find the configs files saved into the flash.
So I checked the flash on a FTP client, and seemed formated.
I sended the configs files again over FTP and reboot the wipy and the firmware didn't boot because of missing config files. Then I opened the flash over FTP client and the flash has empty again.
All the 11 wipy got the same problem. This is every concern.
I'm afraid that the external memory flash are faulty on all the 11 wipy.
I used the LFS on all devices.
Best regards,
Luís Santos
@robert-hh Many thanks for this detailed analysis and testing. The results are promising, based on your tests and also information from others I think it is clear that enabling wear-leveling does not have any significant negative effect.
@Géza-Husi I had a test running with that setting on three devices:
- LoPy4, 7.4 Million cycles, ~350_000 cycles/day
- FiPy, 4 Million cycles, ~200_000 cycles/day
- Genuine ESP32 with WiPy3 firmware, 10 Million cycles, ~180_000 cycles/day
The test consisted of writing the same 2k = 1 block sized file over and over again. The test code was set up to continue the test after a reboot.
Reboots had to be forced by pushing reset about every seconds day due to WiFi loss. The devices were not connected to a computer and I looked into the REPL once a day using telnet.
At no time there were file system corruptions. No file increase, no noticeable decrease in free file space. At the ESP32 with 1024 blocks I see still 1007 free blocks. 11 are used by the file system. 6 blocks used by the super block structure. That adds to 1024. So LFS performed really well.
It seemed that the ESP32 got a little bit slower over time from about 200_000 cycles/day down to 180_000 cycles/day. But the first number were taken when connected to a PC with REPL open, the second when running detached with just a power supply at USB, talking to no one.
No clue why the LoPy4 was so much faster. Most likely a faster flash chip.
@tuftec, @robert-hh : May I ask that have you found any issues (except the LED/Heartbeat topic) when enabled wear-leveling ? E.g. corrupted FS, reduced power-loss resilience capability, increased size of the files ? Thanks in advance !
@robert-hh good to hear. Thanks for the update.
I am continuing, although slowly, with my developments. No other issues to speak of at this point. Peter.
@tuftec Test finished.
The WiPy3 stopped as planned after 10 Million write cycles without problems using LFS with wear leveling ENABLED. I had to reboot it a few times manually since it lost WIFi connection. That relates to my AP.
I stopped the test with LoP4 after 7.5 Million cycles, and with FiPy after 4 Million cycles. None of them had an issue with writing. The FiPy was in the game, because it had Core dumps caused by some interaction with the heartbeat flash every ~100_000 cycles. After changing code, that went well for 3 Million cycles.
@robert-hh Thanks. All good. I have tidied up my code and incorporated your suggestions. Seems to be working now with reliable lte and lfs. I will leave it run for some time to confirm. I can now move on to the next level of test and debug. Tanks again.
@serafimsaudade @Gijs @tuftec OK. This thread is overloaded now with the discussion of three different topics:
a) Flash wear. For that I made a PR: Tests are still running well, with two devices beyond 4 Million writes of a single short file. All well. I will continue up to 10 Million writes.
b) During that wear levelling test, I had core dumps at about every 50_000 writes. They were related to the heartbeat flash. I made a PR which changed that heartbeat timing a little bit. After that, the crashes disappeared, at least in that test. I am not 100% confident that the change cured the initial problem, which could also be a Core-0/Core-1 collision. But the change is also not intrusive and saves a few clock cycles. PR here:
c) There was a core dump when one attempted to close a file twice using littlefs. Even if that is a bad practice, it should not crash the firmware. I copied over the mechanism used by Damien George to ignore the succeeding closes. PR here:
Maybe some of that will eventually find it's way into the official build.
@robert-hh thanks
@tuftec The editor is here: with a README and a doc-file.
I typically import it in boot.py or main.py with:
from pye_mp import pye
and call it with:
pye(file_name)
The upysh module is here (more or less):
I usually import it with:
from upysh import *
which creates a list of names with commands. Then there is a
mancommand, which lists all available commands, something like
lsor
ls("name"), rm, mv, mkdir, rmdir, cat, cp, head.., Unix like commands.
Note: Loading files to the editor is not fast. Your DipApp.py takes a while to load. And the file size is limited by RAM. With SPIRAM, that should not be the limiting issue. Not all keystrokes of the editor are available with all terminal emulators. It works best with Linux and picocom, or tio, or screen. On Windows, you may use Putty or TeraTerm.
@robert-hh thanks for the pointers.i will rework my code to see if I can get it to work reliably with lfs.
I will provide feedback on my progress.
As an aside, how do you use editor and other frozen bits that you typically add to your builds? Is there a user document somewhere?
Thanks again.
@tuftec You may work with global variables. Or you can use classes and its bound variables. It is just a matter of preference. Only you have to avoid double close of files. Even if the latter should not hurt, there seem to be a special problem with micropython here, which as to be addressed separately.
About files:
- remove the isolated close statements. You do not need them.
- for cases when you open a file for reading/writing, better use something like:
with open('DipConfig.json','w') as f: fp.write(json.dumps(dipconfig)) time.sleep(1)
- I have only seen one open where the close did not immediately follow, and that is in line 657. That one may be obsolete.
- There is an open with a following load in line 830. It looks as of you could close the file there (or better use the with.... structure, which will take care of the close).
Yes, I understand that you have to communicate with a timer module. So the global variables. But structure of the whole thing seems overly complicated, with redundant definitions and imports.
@robert-hh i do not have enough experience with micropython. Is there a defined technique for how to share variables between modules. I have a timer that I share in an attempt to work out runtime for instance. I also found that I had to make some variables global so that my program would work correctly after coming out of deepsleep.
I am probably doing something wrong but making variables truely global seemed to stop micropython from complaining.
@robert-hh thanks for looking at this.
Yes, i suspected the multiple closes might be an issue. I might need to find a way to test a file for open before closing. It does seem a bit pointless though. There are multiple entry points in some areas and i need to ensure the files are closed correctly bwfore going to deepsleep.
Yes, i struggled with the global local thing. I need to be able to access variables at the highest level and even between modules (DipBoot and DipApp as examples) without the inefficiencies of having to pass parameters.
Maybe I can just catch the close error (assuming there is one and it doesnt just crash).
As long as this is known and then well documented we can probably work around it. Although it would be nice if the behaviour was the same as for FAT.
What would yousuggest next? Clearly I need to use lfs to maximise flash life.
Thanks.
@tuftec OK. I can replicate the crash with a simple test at global level, pasted into repl or executed as a small module:
f = open("test", "w") f.write("Nonsense") f.close() f.close()
The same happens is you write for instance
f = Noneinstead
global f.
What cause the crash in your code is:
a) defining fp and nvfp as global in line 40, or more to say, defining variables as global at module level is strange.
b) trying to close files twice. Even without the global definition you would get an error at the second close, albeit not a crash.
@tuftec I found an inconsistency in DipApp.py:
At line 1044, you close nvfp. The file seems to be closed already, and so lfs goes haywire about it. FAT seems not to care.
Edit. There are quite a few single fp.close() and nvfp.close() calls in the app. As far as I could see, these are not required, since all open's are followed by close calls. Anyhow, it's better to use the with statement, which will take carte of the close, even in case of an error.
Edit2: Using a simple test case, double close is not an issue. mmhh? So it's not clear why it fails here.
@tuftec More questions:
a) The imports are case senstitive. Tha got lost on download and had to be adapted
b) DipConfig.py must be DipConfig.json and NNvar.py must be NVvar.json.
I started with erasing a FiPy module first.
Then I uploaded a flash image with lfs2.3 enabled.
Then I uploaded your files, name corrected.
Then, after reboot, the code starts, flashes blue-yellow-blue & stops soon after without any error message. What is the code expecting?
Edit: OK. Got it. P16 must be pulled high to start the code and get the crash
@robert-hh possibly. My interest is in wear levelling to get the best life from the flash. If the lfs is not reliable then it is kind of pointless.
@tuftec Maybe you should open a new thread for this discussion, because this one was initially about flash wear. | https://forum.pycom.io/topic/6734/external-flash-lose-files | CC-MAIN-2022-33 | refinedweb | 1,806 | 76.32 |
Opened 10 years ago
Closed 10 years ago
Last modified 7 years ago
#7927 closed (worksforme)
Form Field not rendered
Description
from django import forms from django.utils.translation import ugettext_lazy class SearchForm(forms.Form): realm = forms.CharField(max_length = 100, required = True, widget = forms.TextInput(attrs = {' title': ugettext_lazy("lblSearchRealm") }))
If ugettext_lazy("lblSearchRealm") returns a value containing an umlaut, the "realm" fields is totally absent from the generated output for the page.
Change History (2)
comment:1 Changed 10 years ago by
comment:2 Changed 7 years ago by
Milestone 1.0 beta deleted
Note: See TracTickets for help on using tickets.
Ran the code, both through shell and a rendered template, with and without fixing the space in ' title':, with lblSearchRealm set to "myfürm" in the appropriate mo/po, and I got the input field in every case.
Template:
And Shell:
Results in:
Works for me. | https://code.djangoproject.com/ticket/7927 | CC-MAIN-2018-17 | refinedweb | 146 | 65.01 |
How to: Enable XML IntelliSense in Visual Basic
XML IntelliSense in Visual Basic provides word completion for elements that are defined in an XML schema. To enable XML IntelliSense in Visual Basic, you must do the following:
Obtain the XML schema (XSD) file or files for the XML files that your application will read from or write to.
Include the XML schema files in your project.
Import the target namespace or namespaces into your code file or project. A target namespace is identified by the targetNamespace or tns attribute of your XSD schema.
To import a target namespace, use the Imports statement, or add a namespace for all code files in a project by using the References page of the Project Designer.
For more information on the capabilities of XML IntelliSense in Visual Basic, see XML IntelliSense in Visual Basic. For more information on importing XML namespaces, see Imports Statement (XML Namespace) or References Page, Project Designer (Visual Basic).
For a video version of this topic, see Video How to: Enable XML IntelliSense in Visual Basic. For a related video demonstration, see How Do I Enable XML IntelliSense and Use XML Namespaces?.
If you have an XML file but you do not have an XSD schema file for it, in SP1 you can create an XSD schema file by using the XML to Schema Wizard. You can also use schema inference in the Visual Studio XML Editor.
To create an XSD schema file for an XML file by using the XML to Schema Wizard (requires SP1)
In your project, click Add New Item on the Project menu.
Select the Xml to Schema item template from either the Data or Common Items template categories.
Provide a file name for the File Explorer, click Add from File.
To add an XML document from an HTTP address, click Add from Web.
To copy or type the contents of an XML document into the wizard, click Type or paste XML.
When you have specified all the XML document sources from which you want to infer the XML schema set, click OK to infer the XML schema set. The schema set is saved in your project folder in one or more XSD files. (For each XML namespace in the schema, a file is created.)
To create an XSD schema file for an XML file by using schema inference in the Visual Studio XML Editor
Edit the XML file in the Visual Studio XML Designer.
When the cursor is somewhere in the XML file, the XML menu appears. Click Create Schema on the XML menu. An XSD file is created from XSD schema inferred from the XML file.
Save the XSD schema file.
To include an XSD schema file
By default, you cannot see XSD files in Visual Basic projects. If your XSD file is already included in the folders for your project, click the Show All Files button in Solution Explorer. Locate the XSD file in Solution Explorer, right-click the file, and click Include File in Project.
If your XSD file is not already part of your project, in Solution Explorer, right-click the folder in which you want to store the XSD file, point to Add, and then click Existing Item. Locate your XSD file and then click Add.
To import an XML namespace in a code file
Identify the target namespace from your XSD schema.
At the beginning of the code file, add an Imports statement for the target XML namespace, as shown in the following example.
To import an XML namespace as the default namespace, that is, the namespace that is applied to XML elements and attributes that do not have a namespace prefix, add an Imports statement for the target default XML namespace. Do not specify a namespace prefix. Following is an example of an Imports statement.
To import an XML namespace for all files in a project
An XML namespace imported in a code file applies to that code file only. To import an XML namespace that applies to all code files in a project, open the Project Designer by double-clicking My Project in Solution Explorer.
On the References tab, in the Imported namespaces box, type the target XML namespace in the form of a full XML namespace declaration (for example, <xmlns:). If the target XML namespace does not specify a namespace prefix, the namespace will be the default XML namespace for the project.
Click Add User Import. | http://msdn.microsoft.com/en-us/library/bb531402(v=vs.110).aspx | CC-MAIN-2014-52 | refinedweb | 740 | 69.72 |
Hello people, this will be the last article which we will solve a simple question in CodeWars, in the next chapter we will start our next python project. In this chapter, we will solve one of the questions in CodeWars and the question goes like this.
Given a number, find the reverse order’s numbers of that number until one and put them in a list. For example, number 6 will make the method to return a list of reverse numbers up until 1, [6,5,4,3,2,1]. Below is the solution.
def reverse_seq(n): list_ = [] while(n > 0): list_.append(n) n -= 1 return list_
So we have solved that simple question on CodeWars and we have received 2 kyu from our hard work. With that, we have temporary concluded the question solving chapter and will start our next python project in the next chapter. | https://www.cebuscripts.com/2019/03/17/codingdirectional-return-a-reverse-order-list-for-a-number-with-python/ | CC-MAIN-2019-13 | refinedweb | 148 | 79.3 |
peculiar docker problem
Hi there, I am seeing some strange issues when using opencv (opencv-python==4.3.0.36) in a docker container. First the base image is python:3-slim I have a very simple python file that does something like this:
import cv2
def main(): .... cap = cv2.VideoCapture(video_src) // for the purpose of checking if cap.isOpened(): print("open") else: print("closed")
so if run my container which calls the script (the call looking like python python_file_name.py -f path_to_video_file
I get the following error:
OpenCV(4.3.0) /tmp/pip-req-build-6amqbhlx/opencv/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): /sample_video/hkk_video_demo.avi in function 'icvExtractPattern'
and the cap.isOpened() returns false
I have researched this error and many have resolved it being installing some sort of ffmpeg codec. However this is where (for me at least) it gets strange.
When i docker exec -it imageID /bin/bash into the container and run the same command above it runs fine and the cap.isOpened() returns true.
I have tried restructuring the calling mechanism into a few different ways but nothing seems to work when calling from the Dockerfile. I created a script to be called at [ENTRYPOINT] in the Dockerfile with the shebang set to /bin/bash and thought but that might work, but seeing as I am writing this you can guess not.
If anyone has any ideas i would appreciate some feedback. Thanks in advance, wil | https://answers.opencv.org/question/235639/peculiar-docker-problem/ | CC-MAIN-2022-40 | refinedweb | 257 | 65.83 |
Setting up tables in SQLite with a primary key on a Xamarin Forms app
SQLite has two API's available, the synchronous and the asynchronous API's. It's easy to set a primary key with the synchronous API because you'll be typing the SQL yourself, however the asynchronous API is much easier to use for people with less SQL knowledge and requires much less code. It's just hard sometimes to get your head around the initial setup, as is the case when setting a primary key. You'll kick yourself when you find out how.
I won't go into installing SQLite into your project in this post, but I just wanted to provide another place on the web that points you in the right direction for the simple yet sometimes hard to find things when creating an app with Xamarin and setting up your database in Xamarin Forms also requires you to do some native work in the separate projects for each device, but when it comes down to it, you'll be using an SQLiteConnection object, in this post, i'll refer to that object as 'the database'.
So say you have a model for an object you want to store in the local database, you'll need to create said database and add a table for the items defined by your model, here's my model:
public class EventItem { public Int32 DBId { get; set; } public Int32 Id { get; set; } public String Title { get; set; } public String Summary { get; set; } public String Body { get; set; } public DateTime Date { get; set; } public String Address { get; set; } public EventItem() { } }
And here's the code to create the table in the database.
objDatabase.CreateTable();
You'll notice I've got a DBId and an Id variable, say I want to use the DBId as the primary key for the database table and Id as the Id given to me by a web service I'm using to get these Event items. I'll need to tell SQLite that this is what I intend, so I make the model look like this:
public class EventItem { [PrimaryKey, AutoIncrement] public Int32 DBId { get; set; } [Indexed] public Int32 Id { get; set; } public String Title { get; set; } public String Summary { get; set; } public String Body { get; set; } public DateTime Date { get; set; } public String Address { get; set; } public EventItem() { } }
I've added a parameter to the DBId variable telling SQLite to use DBId as my primary key and that it should also automatically increment the value. Since I've also got another id given to me from a web service, chances are I'll be running queries to find items by that id too, so I've added the Indexed parameter to the Id variable. This should speed up queries.
To insert items into that table, use this handy method:
public Int32 InsertEventItem(EventItem objEventItem) { return objDatabase.Insert(objEventItem); }
And to get them, use this:
public EventItem GetEventItemByDBId (Int32 intDBId) { return objDatabase.Table().FirstOrDefault(x => x.DBId == intDBId); }
Then finally, to delete them, use this:
public int DeleteEventItem(Int32 intDBId) { return objDatabase.Delete(intDBId); }
That's it. On a side note, if you don't set a primary key, you won't be able to delete from the table, since it requires the primary key value to find the correct record.
If you wan't a full example of all the functions, go here: It'll give you some nice examples to follow.
If you want to find out more about the attributes available in SQLite, check my other post.
Published at 25 Feb 2016, 14:36 PM
Tags: Xamarin,SQLite
| https://lukealderton.com/blog/posts/2016/february/setting-up-tables-in-sqlite-with-a-primary-key-on-a-xamarin-forms-app/ | CC-MAIN-2022-40 | refinedweb | 608 | 56.22 |
For those who aren’t regular readers: as a followup to this post, there are four posts detailing the basic four methods of proof, with intentions to detail some more advanced proof techniques in the future. You can find them on this blog’s primers page.
Do you really want to get better at mathematics?
Remember when you first learned how to program? I do. I spent two years experimenting with Java programs on my own in high school. Those two years collectively contain the worst and most embarrassing code I have ever written. My programs absolutely reeked of programming no-nos. Hundred-line functions and even thousand-line classes, magic numbers, unreachable blocks of code, ridiculous code comments, a complete disregard for sensible object orientation, negligence of nearly all logic, and type-coercion that would make your skin crawl. I committed every naive mistake in the book, and for all my obvious shortcomings I considered myself a hot-shot programmer! At least I was learning a lot, and I was a hot-shot programmer in a crowd of high-school students interested in game programming.
Even after my first exposure and my commitment to get a programming degree in college, it was another year before I knew what a stack frame or a register was, two more before I was anywhere near competent with a terminal, three more before I fully appreciated functional programming, and to this day I still have an irrational fear of networking and systems programming (the first time I manually edited the call stack I couldn’t stop shivering with apprehension and disgust at what I was doing).
In a class on C++ programming I was programming a Checkers game, and my task at the moment was to generate a list of all possible jump-moves that could be made on a given board. This naturally involved a depth-first search and a couple of recursive function calls, and once I had something I was pleased with, I compiled it and ran it on my first non-trivial example. Low and behold (even having followed test-driven development!), I was hit hard in the face by a segmentation fault. It took hundreds of test cases and more than twenty hours of confusion before I found the error: I was passing a reference when I should have been passing a pointer. This was not a bug in syntax or semantics (I understood pointers and references well enough) but a design error. And the aggravating part, as most programmers know, was that the fix required the change of about 4 characters. Twenty hours of work for four characters! Once I begrudgingly verified it worked (of course it worked, it was so obvious in hindsight), I promptly took the rest of the day off to play Starcraft.
Of course, as every code-savvy reader will agree, all of this drama is part of the process of becoming and strong programmer. One must study the topics incrementally, make plentiful mistakes and learn from them, and spend uncountably many hours in a state of stuporous befuddlement before one can be considered an experienced coder. This gives rise to all sorts of programmer culture, unix jokes, and reverence for the masters of C that make the programming community so lovely to be a part of. It’s like a secret club where you know all the handshakes. And should you forget one, a crafty use of awk and sed will suffice.
“Semicolons of Fury” was the name of my programming team in the ACM collegiate programming contest. We placed Cal Poly third in the Southern California Regionals, and in my opinion our success was due in large part to the dynamics of our team. I (center, in blue) have since gotten a more stylish haircut.
Now imagine someone comes along and says,
“I’m really interested in learning to code, but I don’t plan to write any programs and I absolutely abhor tracing program execution. I just want to use applications that others have written, like Chrome and iTunes.”
You would laugh at them! And the first thing that would pass through your mind is either, “This person would give up programming after the first twenty minutes,” or “I would be doing the world a favor by preventing this person from ever writing a program. This person belongs in some other profession.” This lies in stark opposition to the common chorus that everyone should learn programming. After all, it’s a constructive way to think about problem solving and a highly employable skill. In today’s increasingly technological world, it literally pays to know your computer better than a web browser. (Ironically, I’m writing this on my Chromebook, but in my defense it has a terminal with ssh. Perhaps more ironically, all of my real work is done with paper and pencil.)
Unfortunately this sentiment is mirrored among most programmers who claim to be interested in mathematics. Mathematics is fascinating and useful and doing it makes you smarter and better at problem solving. But a lot of programmers think they want to do mathematics, and they either don’t know what “doing mathematics” means, or they don’t really mean they want to do mathematics. The appropriate translation of the above quote for mathematics is:
“Mathematics is useful and I want to be better at it, but I won’t write any original proofs and I absolutely abhor reading other people’s proofs. I just want to use the theorems others have proved, like Fermat’s Last Theorem and the undecidability of the Halting Problem.”
Of course no non-mathematician is really going to understand the current proof of Fermat’s Last Theorem, just as no fledgling programmer is going to attempt to write a (quality) web browser. The point is that the sentiment is in the wrong place. Mathematics is cousin to programming in terms of the learning curve, obscure culture, and the amount of time one spends confused. And mathematics is as much about writing proofs as software development is about writing programs (it’s not everything, but without it you can’t do anything). Honestly, it sounds ridiculously obvious to say it directly like this, but the fact remains that people feel like they can understand the content of mathematics without being able to write or read proofs.
I want to devote the rest of this post to exploring some of the reasons why this misconception exists. My main argument is that the reasons have to do more with the culture of mathematics than the actual difficulty of the subject. Unfortunately as of the time of this writing I don’t have a proposed “solution.” And all I can claim is a problem is that programmers can have mistaken views of what mathematics involves. I don’t propose a way to make mathematics easier for programmers, although I do try to make the content on my blog as clear as possible (within reason). I honestly do believe that the struggle and confusion builds mathematical character, just as the arduous bug-hunt builds programming character. If you want to be good at mathematics, there is no other way.
All I want to do with this article is to detail why mathematics can be so hard for beginners, to explain a few of the secret handshakes, and hopefully to bring an outsider a step closer to becoming an insider. And I want to stress that this is not a call for all programmers to learn mathematics. Far from it! I just happen to notice that, for good reason, the proportion of programmers who are interested in mathematics is larger than in most professions. And as a member of both communities, I want to shed light on why mathematics can be difficult for an otherwise smart and motivated software engineer.
So read on, and welcome to the community.
Travelling far and wide
Perhaps one of the most prominent objections to devoting a lot of time to mathematics is that it can be years before you ever apply mathematics to writing programs. On one hand, this is an extremely valid concern. If you love writing programs and designing software, then mathematics is nothing more than a tool to help you write better programs.
But on the other hand, the very nature of mathematics is what makes it so applicable, and the only way to experience nature is to ditch the city entirely. Indeed, I provide an extended example of this in my journalesque post on introducing graph theory to high school students: the point of the whole exercise is to filter out the worldly details and distill the problem into a pristine mathematical form. Only then can we see its beauty and wide applicability.
Here is a more concrete example. Suppose you were trying to encrypt the contents of a message so that nobody could read it even if they intercepted the message in transit. Your first ideas would doubtlessly be the same as those of our civilization’s past: substitution ciphers, Vigenere ciphers, the Enigma machine, etc. Regardless of what method you come up with, your first thought would most certainly not be, “prime numbers so big they’ll make your pants fall down.” Of course, the majority of encryption methods today rely on very deep facts (or rather, conjectures) about prime numbers, elliptic curves, and other mathematical objects (“group presentations so complicated they’ll orient your Mobius band,” anyone?). But it took hundreds of years of number theory to get there, and countless deviations into other fields and dead-ends. It’s not that the methods themselves are particularly complicated, but the way they’re often presented (and this is unavoidable if you’re interested in new mathematical breakthroughs) is in the form of classical mathematical literature.
Of course there are other examples much closer to contemporary fashionable programming techniques. One such example is boosting. While we have yet to investigate boosting on this blog, the basic idea is that one can combine a bunch of algorithms which perform just barely better than 50% accuracy, and collectively they will be arbitrarily close to perfect. In a field dominated by practical applications, this result is purely the product of mathematical analysis.
And of course boosting in turn relies on the mathematics of probability theory, which in turn relies on set theory and measure theory, which in turn relies on real analysis, and so on. One could get lost for a lifetime in this mathematical landscape! And indeed, the best way to get a good view of it all is to start at the bottom. To learn mathematics from scratch. The working programmer simply doesn’t have time for that.
What is it really, that people have such a hard time learning?
Most of the complaints about mathematics come understandably from notation and abstraction. And while I’ll have more to say on that below, I’m fairly certain that the main obstacle is a familiarity with the basic methods of proof.
While methods of proof are semantical by nature, in practice they form a scaffolding for all of mathematics, and as such one could better characterize them as syntactical. I’m talking, of course, about the four basics: direct implication, proof by contradiction, contrapositive, and induction. These are the loops, if statements, pointers, and structs of rigorous argument, and there is simply no way to understand the mathematics without a native fluency in this language.
So much of mathematics is built up by chaining together a multitude of absolutely trivial statements which are amendable to proof by the basic four. I’m not kidding when I say they are absolutely trivial. A professor of mine once said,
If it’s not completely trivial, then it’s probably not true.
I can’t agree more with this statement. Of course, there are many sophisticated proofs in mathematics, but an overwhelming majority of (very important) facts fall in the trivial category. That being said, trivial can be sometimes relative to one’s familiarity with a subject, but that doesn’t make the sentiment any less right. Drawing up a shopping list is trivial once you’re comfortable with a pencil and paper and you know how to write (and you know what the words mean). There are certainly works of writing that require a lot more than what it takes to write a shopping list. Likewise, when we say something is trivial in mathematics, it’s because there’s no content to the proof outside of using definitions and a typical application of the basic four methods of proof. This is the “holding a pencil” part of writing a shopping list.
And as you probably know, there are many many more methods of proof than just the basic four. Proof by construction, by exhaustion, case analysis, and even picture proofs have a place in all fields of mathematics. More relevantly for programmers, there are algorithm termination proofs, probabilistic proofs, loop invariants to design and monitor, and the ubiquitous NP-hardness proofs (I’m talking about you, Travelling Salesman Problem!). There are many books dedicated to showcasing such techniques, and rightly so. Clever proofs are what mathematicians strive for above all else, and once a clever proof is discovered, the immediate first step is to try to turn it into a general method for proving other facts. Fully flushing out such a process (over many years, showcasing many applications and extensions) is what makes one a world-class mathematician.
An entire book dedicated to the probabilistic method of proof, invented by Paul Erdős and sown into the soil of mathematics over the course of his lifetime.
Another difficulty faced by programmers new to mathematics is the inability to check your proof absolutely. With a program, you can always write test cases and run them to ensure they all pass. If your tests are solid and plentiful, the computer will catch your mistakes and you can go fix them.
There is no corresponding “proof checker” for mathematics. There is no compiler to tell you that it’s nonsensical to construct the set of all sets, or that it’s a type error to quotient a set by something that’s not an equivalence relation. The only way to get feedback is to seek out other people who do mathematics and ask their opinion. In solo, mathematics involves a lot of backtracking, revising mistaken assumptions, and stretching an idea to its breaking point to see that it didn’t even make sense to begin with. This is “bug hunting” in mathematics, and it can often completely destroy a proof and make one start over from scratch. It feels like writing a few hundred lines of code only to have the final program run “rm -rf *” on the directory containing it. It can be really. really. depressing.
It is an interesting pedagogical question in my mind whether there is a way to introduce proofs and the language of mature mathematics in a way that stays within a stone’s throw of computer programs. It seems like a worthwhile effort, but I can’t think of anyone who has sought to replace a classical mathematics education entirely with one based on computation.
Mathematical syntax
Another major reason programmers are unwilling to give mathematics an honest effort is the culture of mathematical syntax: it’s ambiguous, and there’s usually nobody around to explain it to you. Let me start with an example of why this is not a problem in programming. Let’s say we’re reading a Python program and we see an expression like this:
foo[2]
The nature of (most) programming languages dictates that there are a small number of ways to interpret what’s going on in here:
- foo could be a list/tuple, and we’re accessing the third element in it.
- foo could be a dictionary, and we’re looking up value associated to the key 2.
- foo could be a string, and we’re extracting the third character.
- foo could be a custom-defined object, whose __getitem__ method is defined somewhere else and we can look there to see exactly what it does.
There are probably other times this notation can occur (although I’d be surprised if number 4 didn’t by default capture all possible uses), but the point is that any programmer reading this program knows enough to intuit that square brackets mean “accessing an item inside foo with identifier 2.” Part of the reasons that programs can be very easy to read is precisely because someone had to write a parser for a programming language, and so they had to literally enumerate all possible uses of any expression form.
The other extreme is the syntax of mathematics. The daunting fact is that there is no bound to what mathematical notation can represent, and much of mathematical notation is inherently ad hoc. For instance, if you’re reading a math paper and you come across an expression that looks like this
The possibilities of what this could represent are literally endless. Just to give the unmathematical reader a taste:
could be an entry of a sequence of numbers of which we’re taking arithmetic
powers. The use of the letter delta could signify a slightly nonstandard way to write the Kronecker delta function, for which
is one precisely when
and zero otherwise. The superscript
could represent dimension. Indeed, I’m currently writing an article in which I use
to represent
-dimensional simplex numbers, specifically because I’m relating the numbers to geometric objects called simplices, and the letter for those is a capital
. The fact is that using notation in a slightly non-standard way does not invalidate a proof in the way that it can easily invalidate a program’s correctness.
What’s worse is that once mathematicians get comfortable with a particular notation, they will often “naturally extend” or even silently drop things like subscripts and assume their reader understands and agrees with the convenience! For example, here is a common difficulty that beginners face in reading math that involves use of the summation operator. Say that I have a finite set of numbers whose sum I’m interested in. The most rigorous way to express this is not far off from programming:
Let
be a finite set of things. Then their sum is finite:
The programmer would say “great!” Assuming I know what “+” means for these things, I can start by adding
, add the result to
, and keep going until I have the whole sum. This is really just a left fold of the plus operator over the list
.
But for mathematicians, the notation is far more flexible. For instance, I could say
Let
be finite. Then
is finite.
Things are now more vague. We need to remember that the
symbol means “in.” We have to realize that the strict syntax of having an iteration variable
is no longer in effect. Moreover, the order in which the things are summed (which for a left fold is strictly prescribed) is arbitrary. If you asked any mathematician, they’d say “well of course it’s arbitrary, in an abelian group addition is commutative so the order doesn’t matter.” But realize, this is yet another fact that the reader must be aware of to be comfortable with the expression.
But it still gets worse.
In the case of the capital Sigma, there is nothing syntactically stopping a mathematician from writing
Though experienced readers may chuckle, they will have no trouble understanding what is meant here. That is, syntactically this expression is unambiguous enough to avoid an outcry:
just happens to also be a set, and saying
means that the function
is constructed in a way that depends on the choice of the set
. This often shows up in computer science literature, as
is a standard letter to denote an alphabet (such as the binary alphabet
).
One can even take it a step further and leave out the set we’re iterating over, as in
since it’s understood that the lowercase letter (
) is usually an element of the set denoted by the corresponding uppercase letter (
). If you don’t know greek and haven’t seen that coincidence enough times to recognize it, you would quickly get lost. But programmers must realize: this is just the mathematician’s secret handshake. A mathematician would be just as bewildered and confused upon seeing some of the pointer arithmetic hacks C programmers invent, or the always awkward infinite for loop, if they had not had enough experience dealing with the syntax of standard for loops.
for (;;) { ; }
In fact, a mathematician would look at this in disgust! The fact that the C programmer has need for something as pointless as an “empty statement” should be viewed as a clumsy inelegance in the syntax of the programming language (says the mathematician). Since mathematicians have the power to change their syntax at will, they would argue there’s no good reason to change it, if it were a mathematical expression, to something simpler.
And once the paper you’re reading is over, and you start reading a new paper, chances are their conventions and notation will be ever-so-slightly different, and you have to keep straight what means what. It’s as if the syntax of a programming language changed depending on who was writing the program!
Perhaps understandably, the frustration that most mathematicians feel when dealing with varying syntax across different papers and books is collectively called “technicalities.” And the more advanced the mathematics becomes, the ability to fluidly transition between high-level intuition and technical details is all but assumed.
The upshot of this whole conversation is that the reader of a mathematical proof must hold in mind a vastly larger body of absorbed (and often frivolous) knowledge than the reader of a computer program.
At this point you might see all of this as my complaining, but in truth I’m saying this notational flexibility and ambiguity is a benefit. Once you get used to doing mathematics, you realize that technical syntax can make something which is essentially simple seem much more difficult than it is. In other words, we absolutely must have a way to make things completely rigorous, but in developing and presenting proofs the most important part is to make the audience understand the big picture, see intuition behind the symbols, and believe the proofs. For better or worse, mathematical syntax is just a means to that end, and the more abstract the mathematics becomes, the more flexiblility mathematicians need to keep themselves afloat in a tumultuous sea of notation.
You’re on your own, unless you’re around mathematicians
That brings me to my last point: reading mathematics is much more difficult than conversing about mathematics in person. The reason for this is once again cultural.
Imagine you’re reading someone else’s program, and they’ve defined a number of functions like this (pardon the single-letter variable names, I’m just don’t like “foo” and “bar”).
def splice(L): ... def join(*args): ... def flip(x, y): ...
There are two parts to understanding how these functions work. The first part is that someone (or a code comment) explains to you in a high level what they do to an input. The second part is to weed out the finer details. These “finer details” are usually completely spelled out by the documentation, but it’s still a good practice to experiment with it yourself (there is always the possibility for bugs or unexpected features, of course).
In mathematics there is no unified documentation, just a collective understanding, scattered references, and spoken folk lore. You’re lucky if a textbook has a table of notation in the appendix. You are expected to derive the finer details and catch the errors yourself. Even if you are told the end result of a proposition, it is often followed by, “The proof is trivial.” This is the mathematician’s version of piping output to /dev/null, and literally translates to, “You’re expected to be able to write the proof yourself, and if you can’t then maybe you’re not ready to continue.”
Indeed, the opposite problems are familiar to a beginning programmer when they aren’t in a group of active programmers. Why is it that people give up or don’t enjoy programming? Is it because they have a hard time getting honest help from rudely abrupt moderators on help websites like stackoverflow? Is it because often when one wants to learn the basics, they are overloaded with the entirety of the documentation and the overwhelming resources of the internet and all its inhabitants? Is it because compiler errors are nonsensically exact, but very rarely helpful? Is it because when you learn it alone, you are bombarded with contradicting messages about what you should be doing and why (and often for the wrong reasons)?
All of these issues definitely occur, and I see them contribute to my students’ confusion in my introductory Python class all the time. They try to look on the web for information about how to solve a very basic problem, and they come back to me saying they were told it’s more secure to do it this way, or more efficient to do it this way, or that they need to import something called the “heapq module.” When really the goal is not to solve the problem in the best way possible or in the shortest amount of code, but to show them how to use the tools they already know about to construct a program that works. Without a guiding mentor it’s extremely easy to get lost in the jungle of people who think they know what’s best.
As far as I know there is no solution to this problem faced by the solo programming student (or the solo anything student). And so it stands for mathematics: without others doing mathematics with you, its very hard to identify your issues and see how to fix them.
Proofs, Syntax, and Community
For the programmer who is truly interested in improving their mathematical skills, the first line of attack should now be obvious. Become an expert at applying the basic methods of proof. Second, spend as much time as it takes to clear up what mathematical syntax means before you attempt to interpret the semantics. And finally, find others who are interested in seriously learning some mathematics, and work on exercises (perhaps a weekly set) with them. Start with something basic like set theory, and write your own proofs and discuss each others’ proofs. Treat the sessions like code review sessions, and be the compiler to your partner’s program. Test their arguments to the extreme, and question anything that isn’t obvious or trivial. It’s not uncommon for easy questions with simple answers and trivial proofs to create long and drawn out discussions before everyone agrees it’s obvious. Embrace this and use it to improve.
Short of returning to your childhood and spending more time doing recreational mathematics, that is the best advice I can give.
Until next time!
Thanks for this post. I’m an experienced programmer who switched domains three years ago from web programming to “interactive art” which, in practice, is a combination of computer vision, machine learning, computational geometry, and computer graphics. With this switch I found a need (and an excitement), for the first time, to engage with the computer science literature. So much of the research progress in these fields has failed to transfer into accessible code and comprehensible texts, but remains locked up in research papers. I found very quickly that engaging with this research meant having to dust off and dramatically improve the minimal math I learned as an undergrad.
So in some ways I resemble that character with which you began this post: the programmer who just wants to understand the techniques that result from this mathematical work and finds the proofs and their forest of notation to be an inconvenience. To some degree I’ve been trying to get past that bias. And I greatly appreciate the advice you give here for notation reading and proof survival.
However, I’m not sure I completely agree with the formula for learning you recommend: to start with the basic techniques of proof and work your way up. I teach programming to grad students many of whom come from the arts and design and have little to no technical background. Our curriculum tried to bring along their grasp of the fundamentals of programming while simultaneously ensuring that, at every step of the way, they can make something that engages and rewards the interests that brought them to programming in the first place. If we just started with variables, if-statements, loops, etc without a graphical and interactive environment (Processing) in which they were, from the very first day, making work that visibly related to their interests, I don’t think many of them would stick with it long and even fewer would pick up the passionate motivation it takes to pursue one of those 20 hour-long bug hunting sessions you describe. The only reason they do that is that they can taste what the visual result will be if they can just solve this one problem.
I wish there was an equivalent medium for learning math. An environment that let me apply the result of various mathematical ideas to the objects that motivate my concern in the first place: images, 3d meshes, etc. and then let me open them up and explore them in more detail as my understanding deepened.
Or, if not a system, I guess I wish for more mathematical writing that was sympathetic to this mode of engagement. Ironically given the what you argue in this post, your blog here is actually one of the best examples of this kind of writing I’ve come across and this is exactly what I enjoy about it: how you root your explorations of a mathematical topic in a practical problem or application that is exciting enough to make it worth wrestling with the mathematical details. When a grasp of those details then also unlocks other exciting applications, that’s when you get some real forward momentum going.
Anyway, apologies for the long comment, but I just thought it would be worth putting in a word for those of us who learn top-down rather than bottom up!
This is fascinating to me. I’ve heard of Processing and always wanted to check it out, but I sort of cast it into the bin of “toy” programming languages like Scratch: something I might introduce to my children one day but wouldn’t seriously work with myself. I’ll definitely need to take a look at how I can use Processing in data visualization, and how well it would be suited to a first course in programming (as opposed to say, python, what I teach now). I’ve been sticking to the mentality that my students will go on to write code professionally, and so the focus is entirely on problem solving and testing (as you can probably tell is how I learned it). Until I become a professor, however, I am stuck teaching to that assumption. But I certainly agree with your sentiment that programming lessons need to hug very closely to the learner’s interests, as it did in my own experiences.
I think I should clarify at least that I don’t think an entire traversal of the mathematical literature is a good idea for programmers. Measure theory, for instance, is the foundation of probability theory (and hence machine learning), but the nature of discrete computation makes most naive probability theories suffice, and simply the knowledge that measure theory is a thing to make continuous probability rigorous is enough to get through most applications.
On the other hand, the “four basics” I describe are really just for interacting with mature mathematical papers and textbooks, which is what I assume most programmers are looking at when they try to learn more about machine learning and such. But for someone who just wants to learn mathematics to see what it’s all about, I think the real gem that can keep them interested is geometry (which is more or less a mathematical joke as it’s taught in elementary and secondary schools in the US today). So, for instance, if there was an art and design major who was interested in mathematics, I would still emphasize proofs above all else, but the proofs would be in the family of the “geometric method.” For a good introduction to this (which requires no background in mathematics at all), see this excellent book by Paul Lockhart. His view is essentially that mathematics can be done simply because it’s fun and proofs (esp geometric ones) are beautiful.
Thanks for the comment!
Processing is definitely more than a toy. While it has limited “production” uses outside of visual arts and design, you can use any java libraries you want in it. Combining that with how easy Processing makes it to create graphics and do interactivity is really powerful. For example, I taught a class at NYU’s Interactive Telecommunications Program last semester, called Makematics, where I tried to help students apply particular areas of CS research to their own interactive work. The syllabus is here: We covered marching squares, linear regression, SVMs, PCA (where I did Eigenfaces based significantly on your write-up here!), Dynamic Programming, and Bayes Rule. For each topic, I tried to cover the mathematical/CS behind the technique in a basic and then also show applications in different domains from computer vision to text processing to digital fabrication. It was incredibly helpful to be working in Processing since I was able to easily create libraries that implemented each technique, usually by wrapping code that already existed. And then, since it was Processing, I had immediate access to all kinds of cool interaction possibilities, from Kinect to image processing to generating files for laser cutting, etc.
I’m trying to do something similar for computational geometry right now…
What a coincidence, I’ve had a few computational geometry posts on the backlog for a while now. Computational geometry is, in my opinion, the most difficult area of computer science research out there.
Why do you think it’s the most difficult? I’ve found that the algorithms are relatively easy to follow and implement (though this may just be because the book (by Mark de Berg) I have is particularly good). However I’ve also found that it’s hard to generalize: understanding one topic doesn’t seem to apply or really help with others.
I learned from de Berg as well, and I’ve found that a lot of his pseudocode oversimplifies the technical details involved in implementing the damn things. In particular, I’ve found that computational geometry involves a lot of complicated routes to efficiently doing very simple operations (querying regions, finding intersections) and each one is a whole subfield of comparing tradeoffs between space and time, mostly involving detailed analysis of custom data structures.
For instance, it is known that a simple polygon can be triangulated in linear time. See this paper of Chazelle. However, the algorithm presented is so technical and complicated that most researchers have given up trying to actually implement it! It’s “hopelessly complicated.“
Hey Greg, I’m currently an undergrad doing CS and have done a lot of interactive art in my spare time. I want to look into it as a career but I have no idea how to “break into” the scene, get myself known, find jobs/opportunities related to it, etc. etc. Could you give me some pointers on how I might actually get started? Thanks!
People may quite reasonably want to use the code of others and learn how to do it better, but “don’t plan to write any programs and I absolutely abhor tracing program execution. I just want to use applications that others have written, like Chrome and iTunes.” We just don’t call that part “learning how to code”, but there is a lot of complex and very useful stuff you can do by using, configuring and combining code w/o writing (and knowing how) a singe line of code ever, and many, many people successfully do just that.
Similarly, people really may want to only “use” the proofs of others – and it currently seems very hard. So, is it fixable? I mean, not by fixing the “wanting” part as you describe, but fixing the “ease of use” part?
If someone wants to know if X is [provably] true, or if an item X always has property Y (or it just happens to have it in most cases) then a yes/no answer would suffice to be practically useful, and it doesn’t really matter how it was proven. Similarly, in CompSci it is very useful to be able to find out that algorithm X has a worst case/average case complexity of Y, without the proof.
What seems to be needed for this use-case of math, is being able to quickly check against a knowledge base if some statement X is proven to be true or false or undecideable. AFAIK, we don’t really have such a knowledge base. AFAIK, if we had such a knowledgebase with the exact proof “X really is true”, we don’t really have a standartized way for another user to define X so that it would match X in that proof – as you describe, notation is quite open to interpretation.
But the corollary isn’t “math shouldn’t be used that way” – the corollary is “hey math, here’s a todo-list for you to become more useful and usable. Anybody fancy to dig in that direction?”
As to your first comment, I do think it’s sort of frowned upon to combine others’ code without knowing how it works. Take for instance the “big data” community. There have recently been many outcries that these so-called data professionals are good at combining and running statistical tests, but very poor at interpreting them or adapting when a certain test gives an unexpected result. These are the coders who can call library functions, but not implement their own.
It is certainly true that people do use the theorems of others without a full understanding of the content, but that is often because someone has paraphrased the statement of a theorem into terms that one can understand. For instance, I might say that there are theorems in topology that let you determine the “shape” of a data set, and I can even give you an algorithm which produces some output that I claim records the shape of the data set (if two data sets have the same output, then they have the same shape). But to expect anyone to have only this amount of knowledge and to do something useful is quite ludicrous.
Your point about algorithm runtime is well taken. I think once someone has proved a big-theta bound on the runtime of an algorithm, it doesn’t need to be reviewed except for interest’s sake. That being said, the unfortunate reality is that almost every question you ask a mathematician is not going to have a known answer. Even if the question has been asked, lacking an exact answer often leads to all kinds of approximate answers, which can vary widely in the way that they approximate something. And so you see, once you start specifying exactly how things get approximated and how they differ, you’re already doing mathematics. Even the process of laying out exactly the statement of the problem is in nature mathematics. Problem specification alone is what requires dense notation, because in order to make any mathematical ground on a problem one needs to completely isolate it from the concerns of the real world. One prominent example of this is the time/space hierarchy of complexity theory. Very few algorithms have precisely known run times, so the best we can do is create a huge database of partially-known results and wait until things get better classified (with little hope that every question will one day be answered). And indeed, these databases do exist (they’re just often written for people who intend to establish results, not people looking for existing results).
“There is no corresponding “proof checker” for mathematics” <- Yes there is. An major example would be: . Of course such systems demand complete formality – ie much more detail – than a normal mathematical proof, and are often biased towards constructive reasoning, but they're a very interesting area.
I think the mention of Coq actually supports my ideas than opposes them. Have you ever seen a proof of a nontrivial theorem written in Coq? They’re immensely complicated! Here’s an example of a proof of Markov’s inequality written in Coq (which has a one-line mathematical proof). The reader of the actual proof of Markov’s inequality must passively understand or be able to flush out on demand all of the little “lemmas” in the Coq program. And the restrictive syntax shows you that one cannot efficiently do mathematics without bending syntax enough to express your point.
And the real point is that there’s no proof checker for a proof written in a spoken language. Part of the reason is because there’s so much implicit background information and ambiguity in that kind of syntax.
Oh, I wasn’t intending to oppose your ideas – I think it was a very interesting article! You’re absolutely right that non-trivial Coq proofs can be complicated (I have the 4 colour theorem proof somewhere on my hard drive ;-) But the whole area of computer-assisted proof is steadily progressing and improving and it is an interesting entry vector into a more mathematical world if (like me) your background is more on the IT / computer science side. Likewise dependently typed programming languages such as Agda and Idris (and, to a lesser extent, Haskell).
Math notation is not a spoken language, though. I’ve seen dozens of proofs and explanations that are trivial when described in spoken language, but are completely impenetrable when written in “rigorous” form. If we *still* need something like Coq to *actually* be rigorous, what does the half-rigor of math notation really buy us? Several seconds saved on typing/writing extra parenthesis? Or the fuzzy feeling of being an elite?
I don’t care what notation you use when working on some problem, but I definitely do care about what people use in books, research papers and lectures. All of those things are meant to explain things to other people. Yet mathematicians use a notation that is actually worse than Perl one-liners (because at least those can be unambiguously executed). Can you imagine someone teaching programming by example using exclusively stuff like this: $h{$F[2]}.=”$F[0] “;END{$h{$_}=~/ ./&&print”$_: $h{$_}”for keys%h} ? Can you imagine someone defending such practice by implying that people who don’t understand the line above are simply not worthy?
Part of the problem (which I am very cognizant of) is that most mathematics research is written for other mathematics researchers with the same level of experience. The argument goes that it would be a waste of time to give background that everyone reading the paper already has. Another issue is that mathematics is really the art of argument, and so if someone hears your proof and sees it (or hears the beginning and sees how to proceed in an “obvious” fashion), that usually is good enough. And so the half-rigor (although any mathematician would claim to be able to flush out any details needed upon request) walks the balance between too rigorous and bloated with details.
This is part of the reason I keep a blog: to keep myself from falling into that trap. Or at least to know when it’s appropriate and when it’s not.
I think probably the most valuable thing a programmer gets out of studying mathematics is that elusive quality called “mathematical maturity”. I think that’s what this blog post is getting at too, it was just a bit surprising to me not to see that phrase used. Being able to read and write proofs is part of this, of course (and my main suggestion for that would be: go slowly! You cannot read a proof at the same speed you read prose, or a program! Do not think you can gloss over any part of it, until you get really practiced at it.) But applying mathematics in day-to-day programming might not involve as much reading and writing of proofs, as recognizing where proof methods are applicable. Invariants are very valuable in software engineering, and an invariant is basically a universal quantified statement: under all conditions C, some property p(C) is true. That sets it apart from a (necessarily finite) set of tests, and requires, well, a proof, instead. For a practiced programmer with mathematical maturity, much of the proving of an invariant might go on just in their head. It should ideally be documented at some point as well, of course, to communicate it to others who must maintain the code. But it might not make sense for that documentation to take the form of a traditional mathematical proof. But it should, ideally, be as rigorous as possible.
A question regarding “There is no corresponding “proof checker” for mathematics”: what do you think of the potential for adapting the automated theorem prover technology for the purpose of helping programmers learn mathematics? It seems imaginable that in a few decades, we could have systems that let you compose a proof on a computer — formally, but in a non-burdensome way — and the computer would be able to check it for you. And that such tools could be used in mathematics education. Of course, there may be some pitfalls, as a student might come out of such an education with the impression that the mathematical syntax (and foundational axioms) used by the system they learned on is the “right” syntax (and axioms) for mathematics… but hopefully that would not be a difficult misapprehension to dispel.
Good point. “Mathematical maturity” is a good way to sum up the goals of learning mathematics for programming.
As far as I know it the world of automated theorem proving (or alternatively automated theorem checking; two different things) is limited at best, and not helpful for learning. For instance, a very large class of proofs in geometry can be proven by a computer, but why and how this works essentially boils down to a few deep theorems of algebraic geometry (approaching graduate-student level). But on the other hand, the “right” way to teach geometry is by visual proofs: argue by symmetry and finding clever manipulations of geometric shapes to make things line up. It is certainly not to pose it as a computational problem.
But there is still much to think about on that. I think if there were any way to teach mature mathematics in terms of computation, it would be in the form of computational category theory. I’m working on it ;-)
Why overlook the engineering mindset (not to mention the scientific one)? Engineers use math and science to construct artifacts. Their mindset helps them to build better artifacts. Surely you realize this optimal (for engineering) mindset is not a mathematical mindset, such as yours. Not everyone needs to be a mathematician.
Look at any text on advanced engineering mathematics. Where are the proofs? Very few. IMHO, the reason is because many engineers feel like I do. The proof of a useful (to an engineer) theorem often involves tricks and techniques orthogonal to the understanding of what the proof means. Intuitively knowing a theorem must be true and actually proving it true are often two vastly different things. So in most cases, why bother with a proof?
Computers are becoming more and more important to all fields of engineering. It seems reasonable that understanding the capabilities and limits of computer programming would be of benefit to most any engineer. Even if the engineer never writes a single line of code.
I have to disagree, because historically most of classical mathematics (the kind that gets used by physicists and engineers) comes directly from their applications. As such, the reasons why the theorems are true have much more to do with the fact that it’s the most elegant way to describe a physical system than any particular mathematical trick. This holds true for calculus as well as machine learning. Of course there will be scaffolding, just as there are diagrams in engineering which don’t by themselves isolate the heart of a design. Knowing why a theorem is true gives you insight in how to apply it to a particular situation or to modify it or, better yet, to critique and improve upon it. I’m not saying that everyone needs to be a mathematician, but if you want to be better at mathematics and applying it to your work, you need to do more than just read the statements of theorems. And additionally, reading the theorems requires knowledge of the definitions, which is in itself a large undertaking.
Let me ask you a question. As an engineer, are you more interested in the capabilities and limits of a particular computer your simulation is running on? Or of an algorithm regardless of what machine it’s in? Or in what’s impossible (more than just infeasible) to do with a computer program?
The whole point is that in applied-math heavy fields such as machine learning and physical modeling w. numerical analysis you can be much more productive by spending a year learning how to better apply the already known mathematical tools to your field rather than spending time on the critique and improvement of them (which you really wouldn’t be able to do at all after just a year from starting).
Furthermore, in these areas there tend to be unproven rules of thumb that matter a lot for your simulations – where it’s clear that finding out why it is so would require far more time than the entire project where this is used.
It’s practical to specialize – expect that other people, the mathematicians will tackle the why question for the whole class of problems, and you will apply it to your narrow problem if it ever is solved. The math skills, however, are needed to find out if it is solved, say, last year and figure out how to apply it.
As for your question to George – for engineer CompSci the difference between impossible and infeasible doesn’t matter much if at all; but the feasibility itself is critical. What would matter is the dependencies between various parameters – what and how much do you need to restrict in your problem to turn it from an infeasible one to feasible. And sometimes theoretical compsci doesn’t help at all in algorithm comparison if the often ignored constant factors get large enough – machine learning application papers are full of purely empirical performance “proofs” by testing and benchmarking, and that is good enough. The proof of the pudding is in it’s eating.
As someone who studied both math and computer science, I loved your blog post and your entire blog in general. Great stuff
I missed out on university due to illness, so I’m lacking in “advanced” math skills, but that has in no way hindered my ability to make a living through programming. In my experience, most working programmers require very little math skills. For instance, while modern encryption may be based on large primes, most programmers will never implement an encryption library to begin with.
And while mathematical maturity is a trait that I find impressive and desirable, it’s in the same category as skills such as drawing, playing the piano or being able to do five consecutive back flips. More hypothetically useful and admirable than something that will be practically applicable in my life.
However, I have recently found a project which would benefit from some knowledge of geometry, particularly mesh transformations. Which gets to the crux of the issue for me: without a project and/or a social environment to compel me to learn a complex new skill, I quickly lose motivation. Or at least, never get to the point of mathematical maturity.
Is this an artifact of my personality? Or is it fair to generalize this situation to all programmers? All humans?
Are we unwilling to put in the required energy to learn a new skill without a concrete idea of where this energy expenditure is taking us? All those hours of mental energy exerted, slowly doing work upon the neurons in your brain in order to reconfigure them in service to some hypothetical goal. That requires an incredible imagination or a constant reminder of the applicability of the goal to your future self.
Anyways, one final question. For a programmer interested in geometry (particularly as it applies to computer graphics) would you be able to recommend any books that would put me on the path that you prescribed in this blog post?
I certainly agree with you about finding motivation, and I do struggle with this myself. I was lucky enough to begin my late-start mathematical career around a group of (mostly) motivated and like-minded individuals. Or at least they all got my math jokes :) I would extend this difficulty much more quickly to all human beings than to programmers. I have the opinion that a programmer who is dedicated enough to debug code is more motivated to do something difficult than the majority of non-programmers.
As to your reference request, if you’re interested in computation and geometry, you may be interested in computational geometry. While it’s highly technical and difficult, most of the difficulty actually arises from the use of complicated data structures like heaps and quad-trees, but a seasoned programmer should have no difficulty understanding how they work and contribute to efficient runtime. The book I learned computational geometry from is that of Berg, Cheong, et al. While I do disagree with some of the ways they present certain topics, it definitely hugs closely to the programming side of things, and assumes you understand how algorithm termination proofs generally go. I should warn you though, the text is somewhat dense, and even I skipped a number of sections where I could tell the direction was taking me away from my goals.
If you’re interested in graphics programming in particular (that text does have some, but covers a lot of other things, too), then from my understanding linear algebra is important. However, unless you’re going for more advanced graphics techniques (the kind that discretize differential equations to, say, model cloth billowing in the wind) you won’t need too much theory. Unfortunately I don’t know of any references specifically geared toward that.
I’m torn here, because I love math (I actually started out as a programmer and in the past few years have mostly given it up in favor of studying pure math), but at the same time there are obvious counterexamples to your claim that practicioners of Non-Pure-Math-Field X need to intensively study proof-based mathematics in order to understand math. I don’t want to discourage anyone from studying math theory (on the contrary, I find it endlessly fascinating), but, for example, Feynman was famously derisive of rigorous math, which doesn’t seem to have handicapped him at all. As another example, Oliver Heavisides was an engineer who invented the differential operator in a wholly unrigorous manner. His attitude of “I do not refuse my dinner simply because I do not understand the process of digestion” is exemplified by other comments in this thread, and I think there’s certainly a place for that.
On the other hand, for practicioners in specific fields (like, say, machine learning) who say that it is sufficient to learn only the “relevant” theorems of their area, I have to wonder: how did anyone discover that these theorems and areas of math were relevant to machine learning or whatever in the first place? Surely the person who discovered their usage had to have understood the math theory in question before they could realize it had applications. There’s also the danger that if you don’t understand the theory behind your field in a deep way, you will never be able to truly advance it (because the open problems are pretty much by definition ones that the current bag of tricks is largely powerless against)
Physicists (Feynman and Heavyside in particular) have historically tended to abuse mathematics, and actually pave the way for new mathematical theories which have since gone on to give remarkable applications.
The simplest example I know of is in measure theory. Physicists invented the so called “Delta function” which was not a function but they pretended it was, and they pretended it could be integrated. They happened to get some awesome results out of that, and out of this (among other reasons) the field of measure theory was born, which properly defined the delta function as a “tempered distribution” or a generalized function. Measure theory then went on to form the basis of modern probability theory, which in turn gave theorists like John Nash an adequate framework to prove their theorems (this also includes the developers of PAC-learning theory, but perhaps to a slightly lesser extent than Nash).
The history of it all is fascinating and quite convoluted, but in my opinion the physicists were really doing math, and just not spending enough time to iron out the details (and rightly so, it’s a mess that only pure mathematicians should have to deal with). But what I propose people do to understand mathematics is not to study all of proof-based mathematics, but to know enough about proofs so as to be able to follow the simple arguments that abound mathematics. I’m talking about the things that literally every mathematician cannot do without, and which is used in every paper a mathematician writes. The only reason I call it intense is because it’s intense for a beginner in the same way that manipulating stack frames by hand is intense for someone who doesn’t work in security or operating system design.
I don’t agree that Feynman was derisive of rigorous math. He was certainly more than capable of it and he did not feel it was unnecessary for his work. But he was a physicist and what he wanted was answers not general proofs. He would skip steps and take shortcuts when doing calculations because he had a deep intuitive understanding of mathematics that let him know which parts were important and where he could use a trick or an approximation. I think he was actually an exemplar of “mathematical maturity”. Sort of a case of “you have to understand the rules before you can break them”.
He gave a great lecture about this called: The Relation of Mathematics and Physics:
I particularly like this bit towards the end where he talks about approaches to mathematics that mathematicians and physicists have. And it has a funny twist at the end.
What he certainly did disdain was rigorous, formulaic teaching of mathematics. This is a short video where he gives a good explanation of his feelings on that:
For some reason wordpress changed the url for the middle video and took off the start time. The part I’m referring to starts at 6:00. I’ll see if I can paste a different version here that WP will be kinder to:
Great post!
I’ve dropout math degree in my earlier years to become a software developer… and many years later I went back to college because I realize that finishing math major would make a great foundation to really understand machine learning theory and the “why, how and when this works” of the algorithms.
I can say that being a programmer help me out when I started to writing rigorous proofs, specially about being strict about “declaring” what kind of object I’m manipulating and what properties it has.
But being able to write and understand proofs, and specially being able to think hard about a statement for a long period trying to find out all the details until finally you have that moment when think “ah! Now I see this is a trivial consequences of this and this”, all of this mental exercise made me a way better programmer as now I think hard about if every code statement I write it makes sense, if it is understandable, if it is a beautiful succession of logical steps just like the way I try to write a proof.
Wonderfully said :)
+1 for the book recommendation alone. I finally see a book on set theory that explicitly states that the term “set” by itself is undefined.
Reading the first chapter preview at Amazon, I already see the need for a human to explain something to me:
Two sentences from the book [1]: “A possible relation between sets, more elementary than belonging, is equality.” and “Two sets are equal if and only if they have the same elements”. These already seem to be contradicting each other — how can equality be more basic than belonging if the former is defined in terms of the latter.
While I agree with the author on the difficulty I face when learning advanced mathematics (notation, generally tacitly assumed by the authors), one thing that also bugs me is use of human language (!) as a part of the proofs. How do I know that the proof is correct and is not impacted by something fundamental about the human language itself? Merely via inclusion of a human language in the proof, a lot more axioms “may” have been included than what meets the eye. Probably not, but I often find it hard to convince myself of this.
[1]
This is an issue that is usually rigorously solved by logicians, and ignored by working mathematicians. Part of the point is that mathematics is the art of argument, and if your point gets across then that’s good enough. The other part of the point is that mathematicians don’t all agree on the best way to create a completely rigorous foundation for mathematics, but pure mathematics basically has conceded that category theory is the best one we know of so far.
I say you should do enough examples with sets to make yourself comfortable with how they work, and worry more about proving basic facts about sets before you wonder about their foundations. You can always look up the dry formalization of ZFC set theory later, but the basics of proof are essentially required to understand how the formalization works in the first place. (and proof techniques don’t require set theory, it’s just that sets happen to be a simple and convenient vehicle to teach it with).
>> Part of the point is that mathematics is the art of argument, and if your point gets across then that’s good enough.
This clearly does not sound “mathematics” (which is about formal proofs rather than merely convincing) unless again this is the culture amongst mathematicians, which you know better.
>> category theory is the best one we know of so far
I have heard “category theory” before, but had never known the above. I’ll definitely read up more on this. If you have any suggestions on books/papers, please let me know.
I am generally already familiar with set theory basics, though had gotten stuck on diagonalization which someone on Hacker News (Colin Wright) helped me with. Now I can continue reading towards understanding Godel’s proofs.
This is very much a part of the culture. Convincing geometric arguments and picture proofs abound in topology, and they are often quite far from completely rigorous.
I’m going to start a category theory series soon which, in the spirit of this post, remains intertwined with programming for as much of it as possible.
Also, while Godel’s proofs are interesting and a subject of popular fascination, I personally think there is not much content in them. But when you do understand them, there are another class of Godel-type incompleteness theorems, one of which I presented on this blog in my post on Kolmogorov complexity. I like the elegance in these proofs, whereas Godel’s original incompleteness proof is a bit belabored (it’s a constructive proof, whereas the one in my post is only probabilistically so). And after that, if you want to see more about what modern mathematics is like, you can start reading about model theory (but it will quickly get denser). One area of logic that was fascinating to me was that of the Presburger arithmetic. It turns out there’s a natural algorithm to “eliminate quantifiers” and it provides a computable procedure to decide whether any logical formula written in that language is true or false. The only issue is that the problem has complexity
, and as far as I know it’s the only naturally occurring problem with such a big lower bound. I wanted to write a post on it (still have a draft sitting somewhere) and I had a bit of Racket code to perform the algorithm, but my attention was displaced when it came time to write up the mathematical details.
Thanks. Those are enough pointers for me to be busy for a few days! Will anxiously wait for your posts on category theory.
> It’s as if the syntax of a programming language changed depending on who was writing the program!
Oh, so it’s Perl, then!
There are a bunch of algorithms which resist a full mathematical understanding by their very nature. Typically heuristic algorithms meant to do multi-objective gradient free optimization.
In fact, even more typical techniques that were eventually given a linear algebra footing start out not having a rigorous mathematical footing. I think your boosting example was one. Although I think they used methods from analysis. And then Game Theory. Been a while since I looked. Neural networks are another from the point of view of gaussian processes.
Point being, although it is a most suggestable sufficiency, you aboslutely do not need a strong mathematical background to invent a viable learning algorithm. Only to understand why it works. And sometimes that’s not even good enough (the behaviour of schema in genetic algorithms are still argued for example).
Boosting was purely a child of learning theory, and is formulated in the PAC model of learning (again, purely theoretical).
Even with heuristics, the question remains: when should you try for a heuristic as opposed to an exact solution? (when the problem is NP-hard or worse) It’s somewhat amazing, though, that even if the best algorithm is provably a very simple one, it won’t be accepted as good without some theoretical justification. Seeing it’s good in practice is fine and dandy, but if you don’t know for sure that it will be sensible, you won’t (or shouldn’t) risk a lot of money on it. These very kinds of uses without understanding have recently caused financial crises, if you’ll recall…
Are you certain it wasn’t justified after the fact? I have a memory reading that boosting was actually originally intended as a filtering algorithm. And I know that adaptive boost followed boosting which followed bagging – the last of which is very simple. For a while people could not explain the counter intuitive behaviour of ensembles beyond handwaving about smoothing and variance. Also an aside – nowadays Boosting is often explained in a game theoretic setting
As for NP-hard (NP-hard is the or worse, NP-complete is what you are looking for?) sometimes you have just have no choice because you are doing optimization over a non continuous domain. Or one with that is not differentiable.
The financial crisis was done on purpose not out of ignorance =D
Lots of methods are used without a full understanding. Learning Classifier Systems for one. Neural Networks and Random Forests, I argue are not as well understood mathematically as support vector machines although they work very well empirically.
I’ll point out that I am only arguing that theorem guided algorithms are sufficient, not necessary – machine learning is more like physics, where Mathematics and experimentation motivates insight, not theorems and proofs. They clarify insight.
I know the weighting system used in boosting was known ahead of time, but even the idea that one could use weak learners to produce a strong learner was quite novel and not at all obvious. It’s definitely not just a matter of smoothing, but that the training algorithm picks “special” distributions of the input data with which to provide the weak learning algorithms. Because, you see, in PAC learning an algorithm can only learn something if it can learn it regardless of the distribution of the data. I believe the original breakthrough was in a paper of Schapire, but I might be remembering that wrong. IMO its best interpretation is in terms of game theory.
NP-hard is worse than NP-complete (in the sense that NP-complete is contained in NP and NP-hard is not, so many NP-hard problems are not even verifiable in polynomial time). There is still a lot of research actively going into both neural networks and support vector machines, so I would say they are both poorly understood. But in truth the only way to understand why they work is mathematically (sure neural networks have biological interpretations, but cognitive psychologists don’t believe that in any seriousness; I know because I’m working with one right now :) ).
Of course using things is good enough for many. My point is more that if you truly want a full or even a better understanding, you have to dig into the proofs. My issue in this post is simply with those who claim to want deep insights, and what stops them from getting it.
I agree completely that you need a strong mathematical understanding to really know what is going on. I even believe the tools used in machine learning are inadequate. Algebraic geometry, topology, Statistics as well as Group theory are all giving highly simplifying insights, bringing together a lot of things that were once deemed apart.
Up above you said NP-hard or harder, I was correcting you in that NP-hard or harder was redundant and asking if you meant NP-complete or harder.
I’ve implemented Adaboost so I understand the distribution meant to scale difficulty, it was in an improvement called Filterboost (a scalability and generalization improvement) that I read boosting was not originally a learning technique.
I agree that SVMs and ANNs are continually being better understood but think SVMs are better understood due to the increased mathematical tractability, being convex optimizable for a global and with built in regularization.
I completely agree that artificial neural network have very little to do with actual neural networks. At the most basic, Neurons are more like complex automata than simple functions.
There are still complexity classes that are “harder” than NP-hard, and many problems which are known to be in those classes and yet not known to be NP-hard. And of course there are always undecidable problems :)
I am a fledgling programmer who is banging my head against the wall (Well, actually I have just completed a course in actionscript… which I dunno if it is considered a real programming language?). But I really liked this piece somehow, it kind of got to me. How mathematics and Programming differ.
Reblogged this on syndax vuzz.
My experience has been in learning Math and Development not from the collegiate level of instruction, but from the school of hard knocks. I wouldn’t consider myself a master of either (though many I work with constantly place me in that area) but instead as a person who can understand both well enough to bridge the gap.
I find that Math and Programming go together like an Acid and a Base for a Chemist. If you only know the powers of one you will argue its use to the end without acknowledgement of its dangers. Once you understand the basics (and some of the advanced topics) of each you realize that the power comes from the combination of both, not in the application of either.
I’ve sat in many a room with many smart educated people, and I commonly find myself taking the exact opposite stance as anyone else.
If they are arguing what proof for a given formula is best, I suggest using a program sandbox to execute all solutions concurrently with a basic formula and visualization over the top to view where each formula stands out.
If they are arguing that a given algorithmic approach is best I find myself asking for the mathematical proof of each and using that to help choose an appropriate approach. Thus forcing them to think about the outcome, not just the edge case they are claiming best fit for.
Long story short; I think it takes strong individuals in each area to come to the best solution (math gives you a proof, development provides usability), but it also takes an idiot like me sitting in the middle playing Devils Advocate for both parties to find and use a solution.
– Jeremy
So, when has a practical programmer actually ever been called upon to use Fermat’s Last Theorem or a proof of the Halting Problem? I’ve been programming for almost 25 years and have never come upon any real-world programming problem that requires anything more sophisticated than a quicksort — not even a hash table, unless you count the stuff under the hood of the STL — let alone anything approaching serious mathematics — and this in a career consisting almost entirely of engineering and science, where you’d think the heaviest math would be. Okay, in my last job a couple of people I worked with/for developed some pretty heavy math stuff — but it almost never percolated down to *me*, even to implement, let alone to *develop*.
Also, I’m almost done with a Master’s degree in Computer Science, and overall I’d say about 85% of what I’ve been taught either has no practical relevance to me or is something I already knew. Only the remaining 15% is moderately new to me and of even *possible* practical utility. I really should have majored in Software Engineering — but I foolishly merely picked up where I’d left off with my Bachelor’s (1988) when there was no such distinction (and almost all they taught was what would today be considered pretty rudimentary programming; or maybe that was just *my* school).
On one hand, you’re right. I’m not here to say the practical programmer should use mathematics for anything. Considering that the vast majority of code is written to shuffle around credit card information and do basic arithmetic, I’d say that the vast majority of programmers use no mathematics at all. I’m only explaining why those programmers who do want to learn more mathematics have a hard time. And I don’t think it’s a surprise that programmers find mathematics so interesting: not because they need it to do their work, but because one can do so many awesome things with it. (Indeed, the whole point of this blog is to explore those awesome things and how to do them)
On the other hand, more and more algorithms today rely on mathematical analysis. Without getting into too many details, many “simple” algorithms in the randomized/approximation algorithms have extremely sophisticated analysis. This crops up in the analysis of large networks, data mining, and sub-linear streaming algorithms, and these problems are becoming more and more profitable to solve. For the everyday programmer, it’s probably just going to come in the form of someone else telling him the algorithm to code, not explaining why it works, and asking for empirical results. That doesn’t mean the mathematics isn’t important, but that they’re paying someone else to do it and they’re paying the everyday programmer to integrate the ideas into a potentially complex codebase.
Great post!
I’m coming form a pure programming background and have been able to achieve some of my life’s programming goals, but my weak math background has hindered my ability for graphical simulations and solving game theory problems which I really, really want to get into. I’m now catching up on the math, but so far I’ve really own gained some good symbolic technique, which is easy to learn solo because programs like Mathematica will check you your work.
Programming was very easy for me to learn solo because the IDE’s compiler/linker would tell me exactly what was going wrong. I could then isolate the error and ask other programmers on forums and IRC to help me. With an isolated test case, it was very easy to advance.
I’m learning to prove theorems while I study the construction of the real numbers in preparation for my quest to conquer Apostol’s Real Analysis, and I’m so frustrated that I don’t have a compiler/linker to go over my proofs. It’s harder to get help on these often trivial proofs because when I’m learning solo I sometime’s don’t even know how to orientate myself when proving basic theorems.
I do feel at the level of writing and verifying proofs, it absolutely feels like I’m writing a computer program, and I do appreciate my years of programming experience; I often don’t get that feeling of coding when I’m integrating or using algebraic techniques; I feel like I’m blindly brute forcing something, where I’ll try one technique, and if that technique doesn’t work, I’ll see if there’s any partial success to build from and if not, I’ll just have to try a different technique.
I find this post while searching for, “programming language to check number theory proofs”, and from I can gather, I’m outta luck. I’ll be investigating LISP, Coq, metamath and some other programming languages further for helping me with my proofs, but I think I’m going to just have to compare my proof’s to the books author and or pray someone in #math or physics-forums can tell I’m in the right direction.
Thanks again for blogging about this, you have a new follower for life.
I agree that programming skills do contribute to math skills a great deal! Thanks for reading :)
I have to say that if anything, my programming skills have hindered my math skills. I’ve written a fair amount of code, of pretty good code anyway, but most code isn’t really subtle, unless you’re doing funny lock-free stuff or template metaprogramming or whatever. When you zoom out it all becomes a very complex system… The fact that a lot of programmers write after a few beers is a bit of an indicator that for some code you don’t have to always completely be there. You can relax and try things… which you definitely do with math, but you have to be cognizant enough to catch yourself. The computer is the final judge and if it works and (as you say) is thoroughly covered with tests, you’ll know where you went wrong.
I’ve had to break these bad assumptions and habits while learning to become a mathematician/physicist. I’m in some sense writing a program, but really I’m instructing someone how to imagine something. Trying to brute force a proof rarely if ever works for me. It takes a bit of careful sitting down and thinking about what you have. Brute forcing requires that you have a well defined function to tell you when you’re wrong… and if that function was so well defined you wouldn’t have to brute force in the first place. Anyhow. I felt hindered because I’m used to rushing through problems with my hand held by the computer and an arguably very simple framework. Mathematical abstraction results in swinging huge swords and doing a lot of damage if you’re not careful. Good computational abstraction makes it feel like you’re still swinging a small sword, I feel.
Nicely said. I feel the same way, and I think after gaining some mathematical maturity it can go in reverse if you’re not careful too. You can spend too much time on a program that shouldn’t need that much contemplation, and you feel the need to justify steps that don’t need justification (or at least, non-mathematicians don’t need justification).
Re: if it’s not completely trivial its probably not true
Cue one of the 2 math jokes I know: (the other one starts ‘there are 3 kinds of mathematicians…’)
Student is working on his assignment and gets stuck part way through a proof.
Eventually, he decides to try working backwards from what he needs to prove.
He makes better progress, but Unfortunately he soon gets stuck again.
Desperate, he writes => in the space between his forward and backward progress (after all, the professor might not notice!) and passes the damn thing in.
Following week,he gets back the graded assignment. At the top of the page, there are two large marks – a crossed out D and a big, underlined A+.
In the middle of the page, pointing at the spurious => are two large question marks, also crossed out. There was also, in an almost indecipherable scrawl, the following:
This implication seemed to be totally unsupported, but after several hours, I realized it was completely trivial.
I think a big part of the problem is the way we do math education these days. Most students don’t even encounter proofs in high school, even though it is possible to give a very thorough introduction to proofs using only basic algebra. Just look at Daniel Velleman’s excellent book How To Prove It. I think if we could somehow incorporate a book like this into the high school curriculum, we’d see a renewal of interest in mathematics and students would be far less apprehensive about deciphering mathematical notation later in their educational careers.
Another good option for such a text would be Lockhart’s “Measurement.” It was written specifically to address this concern.
Really interesting connections between proofs and programming, including both the uncanny similarities and the extremely polar differences. The “distinction” between trivial and nontrivial though can be really misleading, but you seem to be very aware of this. Technically all theorems are a sequence of trivial steps, but the art lies in knowing which steps to use and what order to use them in. And that part is highly nontrivial.
Anyway, I am sort of approaching this problem from the opposite perspective—my mathematical training is much stronger than that in computer science or programming. I agree that for coding, a solo session can be extremely productive because we can get immediate feedback on our code. But for mathematics, doing proofs alone can seem daunting at first because there is no easy way to check the validity of a proof. I think it takes a while for one to become accustomed to writing proofs, and after that point it becomes much more natural.
Thanks for the article!
Just commenting to say thanks.
I’m afraid I’ll soon get addicted to this site.
This post hit the nail on the head so hard.
Thank you very much for writing these articles!
Incredible post. I really enjoyed reading it. The section about syntax in mathematical proofs was intriguing. I would like to see a standard in mathematical proofs that is like python or even in java with javadocs. I hate referencing an article I that I don’t remember the url for, thanks to stumbleupon, but I saw a similar article discussing how archaic the standard mathematical proof is. In an age of computers, a new proof driven language is needed to make writing, sharing, and error checking proofs less extraneous . While some proofs can be simple, the most prolific of proofs can take so long to “debug” and “decode” they become useless to the non-mathematician, or the amateur. The programming world and the hardcore mathematicians need to merge and develop a python-proof engine.
Jeremy, great post. I am no mathematician, but interested in the subject. couple questions:
1. I just finished reading Devlin’s and it does talk about the barebones of terminology and proofs. not sure if you are familiar with the book, but is this the general direction you recommend?
2. when I started reading your post I thought you would go in the direction of experimental math as an initial bridge between math and programming. again, I’m no mathematician, but i got the impression that experimental math would provide me with the tools to at least break complicated mathematical statements into smaller pieces, test them one at a time, and then try to bring them into a cohesive numerical demonstration (not proof). is that the case?
1. is a good introduction. I actually participated (lightly) as a course TA for Kieth’s online course which used that book. Another book I’d recommend if you’re interested in mathematics with a CS flavor is Sipser’s Introduction to the Theory of Computation. The big proofs in that book are all prefaced with a “proof idea” section which helps a lot in parsing which mathematical details are important and which are just necessary scaffolding.
2. This is a technique that all mathematicians use every day, but for checking the steps of proofs. In fact, I will often write computer programs to verify properties of things (say, by exhaustion) before I try to go and prove them. But for me these are always prerequisites to a formal proof, and the statement “we verified this by computer search” is a bit taboo, even in the theoretical computer science community, because it doesn’t explain why something is the case.
That being said, as you get deeper into mathematics your “experiments” become more abstract. Instead of saying something like “Let’s try this when n=4″ you say, “let’s try this for any prime which is 1 mod 4″ or worse, “let’s try this statement about general fields over an algebraically closed field of characteristic not equal to 2, where everything is nice.”
Great post and discussion here. I just wanted to suggest that one approach a programmer might take to both further motivate and aid their learning of mathematics would be to use their algorithmic chops to try to create meaningful visualizations of their subject of study. (Consider the work of Jason Davies or Steven Wittens.) Exercise: reproduce and adapt some of the visualizations found in Hilbert and Cohn-Vossen’s _Geometry and the Imagination_.
Also, Motion Planning and Optimal Transport problems provide a nice context for the application of concepts that typically fall under the rubric of “higher math” … serious algorithmic challenges only now receiving mathematical illumination.
I really enjoyed this post. In all seriousness, you should consider writing a book specifically tailored to this subject. You seem to have a natural sympathy for the coder, which most math guys lack.
I think the difference between the disciplines is rooted in the environment in which they occur as much as the culture surrounding them. Mathematics is and probably always was an art practiced in academic venues. Knowledge is stacked atop existing knowledge, which allows the initiated to follow along.
While computer science certainly has roots in the university, it grows and mutates in the wild. A coder can learn more in trying to hack a piece of open source software than they can writing thousands of academic examples. Unlike the academic world, knowledge doesn’t require the same pyramid structure underneath. You can get by with understanding only what you need to, and tailor your learning to the specific problem you are trying to solve.
Like one of the comments above suggested, there is an immediate payoff to your learning. You have a working program, which now does what you wanted it to do. Not what you were supposed to learn, but what you wanted to learn. This creates the confidence to pull out the tin snips and sledgehammer to go at another coding project.
With each victory, your knowledge increases in jagged chunks, which can be crudely summoned and at some point refined. You don’t have to be clever to learn to code, but if you keep at it long enough, cleverness might sneak up on you.
You can follow this sleazy path through the back alleys of the intellectual metropolis, until someone asks you to provide Big O notation for something. Within moments of reading that damned algorithms book for the tenth time, you realize that your bluff has been called. You are in fact too stupid to be reading this book. You understood the first 20 pages, then they started slipping the nonsense in.
So you do what has always worked before. You try to learn just enough to move forward. Sadly, all of the math on Wikipedia is written in math, so you are still screwed. There are many math sites, but they are all intended for college students studying math. If you try to ask a question, they will respond in math. Unlike programming, there just don’t seem to be primitive elements, which scale to practical use.
Mr. Krummel, nicely put. A programmer would like some path to the symbolic abstractions via the concreteness of code … a graduated semantic ascent like that offered by the Little Schemer, culminating in formal notation. Of course, proofs need not be avoided along the way, just refuted/generalized along the lines of Lakatos’ Proofs and Refutations.
I have been thinking about a book. I said in a recent post that I had long term plans to cover certain topics. A book would be super-duper long term by comparison. I don’t think I could start until after completing my PhD.
I do think mathematical knowledge is jagged as well. Mathematicians tend to specialize heavily in a subfield of a subfield of a field. I think part of my point is that the baselines are very different in the two fields. In programming you need to know how to use a text editor before you can write a program, and you should be familiar with a handful of languages and tools if you intend to be a software developer. In mathematics, the baseline is following, questioning, and generating logical arguments. I think that if the general educated public had a solid mathematical foundation there wouldn’t be such a perception of the pyramid of knowledge (or at least, that wouldn’t be considered the main obstacle). As you can see, for something like group theory it only takes me a post or two to make the gist of these coveted secrets public. It’s not research level mathematics, but it’s enough to go out and implement RSA.
Internalizing intuition about groups to the level required by a mathematician takes just as much practice as programming, and I think that’s the kind of culture that turns programmers off (and turns mathematicians off to programming!). Mathematicians expect this intuition to be developed by exercise, proof, and counterexample. Most non mathematicians just want to know how things work without all of that.
Here’s the thing: I have spent seventeen years studying mathematics. I began at around four years old, then continued throughout my formal education until I did my degree in computer science, during which I took some modules in discrete mathematics. There is no doubt that I have spent far, far more of my life engaged in deliberate study of mathematics than any aspect of programming, so why do I feel so completely lost when trying to research and apply mathematics while programming?
It’s frustrating to read posts like this that suggest both that I don’t understand the basics of mathematics, and that I’m not prepared to expend the effort to learn. The way I see it, I, and just about everyone who went through the formal schooling system, has had an extraordinary amount of mathematical education. That it was apparently useless in preparing us to tackle any kind of advanced topic in mathematics, and we’re still “beginners”, is pretty sick-making. It’s like learning to read and write all throughout school, only to get out and find that everything anyone writes is in a different, completely incomprehensible language.
The sad truth is that little of what goes on in secondary school education is “mathematics” in the sense that you want it to be. Despite that formulas are often seen as the end result of mathematical work, mathematics is not about applications or formulas. It’s about the reasoning taken to get to that end. And so I ask: how many of those seventeen years did you spend trying to solve problems for which you weren’t given an algorithm ahead of time? The problem is that you’re never taught in school to play with mathematical concepts in order to gain a better intuitive understanding of them. The analogy is that you spend 17 years learning to read and write, but all you really do is practice spelling and grammar; you never open a novel or write a short story (no matter whether it’s bad literature, you’re never given the chance). Or you learn to write sheet music but never play an instrument. You might be under the impression you spent 17 years studying music, but can you really expect to have any proficiency at all playing the piano?
When you see a new feature in a programming language, what do you do to learn about it? The best answer is: you write little programs that use it in progressively more complicated ways. This is the same attitude you need to have about mathematics when you encounter something you don’t understand. You’re supposed to feel lost, more so in mathematics than programming (all mathematicians do!). Most people expect mathematical understanding to come to them WAY faster than is realistic. When I encounter a new definition (forget the big theorems!) I spend tons of time tinkering with examples and trying to prove simple facts before moving on. Even then I rarely get the intuition I’m looking for, and similarly every little program you try to write with your new feature might have compiler errors. But when it comes to mathematics a lot of people, perhaps due to the duplicitous nature of their schooling, expect to be told what to do and how to do it, and they never get any real intuition about things. It’s like you’re writing a program and you demand to be told what to type (not what language features or data structures are appropriate, not whether such and such belongs as a separate function, but what order to type which keys).
I don’t mean to say that you do this, but it’s an extreme form of the same attitude (I’ve actually had programming students ask me what to type in their programs). The point is that mathematical thinking skills are largely unrelated to knowledge of mathematical facts. The central mathematical skill is being able to form and answer questions, to gain traction in the face of being completely lost. Because I am “completely lost” every day I go into work, and by the end of the day I am a tiny bit less completely clueless.
And I don’t mean to say programmers can’t or don’t want to learn mathematics. I was originally a programmer who had never done math. I’m saying that I see a lot of genuinely interested programmers try to learn math, and ultimately lose hope for some or all of these reasons.
Is there a curriculum list you would recommend for someone starting out? | http://jeremykun.com/2013/02/08/why-there-is-no-hitchhikers-guide-to-mathematics-for-programmers/ | CC-MAIN-2014-42 | refinedweb | 16,185 | 57.61 |
I have my plugin compiling with R#9 SDK and I believe it installed ok using extensions manager pointing to a local nuget package. However...it isn't loading within VS. I am running VS with /Resharper.Internal and I don't see any exceptions thrown. I also tried turning on debug verbose logging via the 'internals' menu but the log files created are zero bytes.
I see the nuget package layout changed...where do I look to get an insight into why it is failing to load? I have my DLL within dotFiles nuget folder...and can see copied into AppData\Local\JetBrains\Installations\ReSharperPlatformVs11
Secondly, I have a couple of references within my unit tests that I need help resolving:
- ReSharperTestEnvironmentAssembly
- DataContextOfTestTextControl.Create - I used this class to get the datacontext needed by a call to IExecutableAction.Execute Many thanks for any help in advance
Apologies for all the queries !
Hi. There are a couple of gotchas for installing to R# 9, unfortunately. Firstly, make sure your package has a "." in the name - it will not be properly installed if it doesn't. E.g. it should be "Foo.Bar" and not just "Bar". Secondly, there must be a zone marker in the lowest common namespace in your plugin - if you have namespaces "Foo.Analaysis" and "Foo.QuickFix", you need a zone marker in the "Foo" namespace. I've got reports that this is required to install, but I need to confirm this. These issues should be visible in the installer log, which is in %LOCALAPPDATA%\JetBrains\Shared\v01.
As for logging, you can enable it via the Logging page when /ReSharper.Internal is enabled. By default, it will output all VERBOSE and lower (i.e. basically everything except TRACE) to OutputDebugString, meaning you'll need a debugger attached to see the messages. To get it to output to file, uncomment the "file" appender close to the top of the file, and then add it to the <root> element lower down - uncomment the <appender-ref>file</appender-ref> line. I'm not sure if you need to restart for this to be picked up, but it should start logging to c:\logs. The best thing to do is open the log file and search for your assembly name, and also any namespaces.
There are changes to testing that mean anything using ReSharperTestEnvironmentAssembly needs updating. I'll have the docs updated over the next couple of days. DataContextOfTestTextControl.Create is still there, but moved to a different namespace - use ReSharper's import completion to bring it in.
Hello Matt, thanks for helping... Tried a couple of things but still nothing is firing up. Logs say the package was installed ok but none of my plugin features are coming to life. As suggested I've added a 'zonemarker' at the root namespace (just like). My root namespace is TestCop.Plugin so the zone marker class is TestCop.Plugin.ZoneMarker The assembly name is currently called Resharper.TestCop.dll (so it has the dot). The log files have content..but don't offer any clues
|V| NugetBuildHelpers | Package NVelocity.1.0.3: files (2pcs)[“NVelocity.dll (232 KB)”, “NVelocity.xml (343 KB)”].
|V| SimpleFileItem | SimpleFileItem,Created,Size,151040,Stream,Zakym,Path,Resharper.Testcop.dll,
|V| SimpleFileItem | SimpleFileItem,Created,Size,271872,Stream,Febeg,Path,Resharper.Testcop.pdb,
|V| NugetBuildHelpers | Generating fake JetMetadata for package Resharper.TestCop.1.9.0.0-E].
|V| SimpleFileItem | SimpleFileItem,Created,Size,1587,Stream,Ryleq,Path,Resharper.TestCop.JetMetadata.sstg,
|V| NugetBuildHelpers | Package Resharper.TestCop.1.9.0.0-EAP: files (3pcs)[“Resharper.Testcop.dll (147 KB)”, “Resharper.TestCop.JetMetadata.sstg (1.54 KB)”, “Resharper.Testcop.pdb (265 KB)”].
PS: Can't find DataContextOfTestTextControl even using DotPeek ?
Is that the installer log? What about the main product log? Is there anything there for Resharper.TestCop?
Is your zone marker the same as the example one? For now, it should have no other interfaces, just an empty class:
Ideally, it should be better specified, but doing that by hand is error prone, and could really do with diagnostics that aren't ready yet. Setting it to an empty class with no inheritance means it will be enabled correctly.
DataContextForTestTextControl is now part of an internal "test cases" package, rather than the public "test framework" package - i.e., it's an implementation detail for value tracking tests. The class itself is pretty straightforward:
Yes - my zone marker looks like that. Strangely the extension installer doesn't always ask me to restart VS...|V| NugetBuildHelpers | The Nuget package Resharper.TestCop.1.9.0.0-EAP does not have the embedded JetManifest. |V| BuildBinaryFileItems | Expanding Nuget package “Resharper.TestCop 1.9.0.0-EAP”. |V| SimpleFileItem | SimpleFileItem,Created,Size,150528,Stream,Qovud,Path,Resharper.Testcop.dll, |V| SimpleFileItem | SimpleFileItem,Created,Size,271872,Stream,Gitet,Path,Resharper.Testcop.pdb, |V| BuildBinaryFileItems | All expanded files: (2pcs)[“Resharper.Testcop.dll (147 KB)”, “Resharper.Testcop.pdb (265 KB)”].
These are the type of entries I see within the install log (AppData\Local\JetBrains\Shared\v].
Do you have any logs from running the product?
I moved forward when I downloaded the latest Resharper and this time my plugin appears within the menu (after a restart)...and I can see a couple of exceptions within the login file for me to investigate ...
Can you give me an example on how to set up keyboard shortcuts for an IExecutableAction? Is now the action.xml ?
I've found an examplepublic class GotoLineActionHandler : IExecutableAction, IAction
[Action("&Go to Line...", Id = 3246, IdeaShortcuts = new string[] {"Control+G"}, VsShortcuts = new string[] {"Control+G"})]
However, the keyboard shortcut isn't applied for my plugin unless I go into Resharper and reapply the keyboard scheme...how can I get this to happen on plugin install ??
Did you find a way to apply shortcuts at plugin installation?
Should I continue to use my DTE.Commands.Item hack?
Viktar
Nope, you just need to specify the shortcuts on the Action attribute. These are used to statically register the actions as VS commands during installation. Because the VS commands are statically registered, the shortcuts are persistent, and can be modified, and the modification is also persistent (hooray!)
Just noticed the first part of the question - not sure why your action shortcuts weren't being applied appropriately. However, if you were simply copying the dll into the installations folder (i.e. build + copy, build + copy) then it wouldn't work. When you change the registration details of an Action, you need to re-install that extension so it can be statically registered with VS.
Matt,
Here is example of my action:
[Action("Copy Current Word", Id = 11122234, IdeaShortcuts = new[] { "Control+Shift+W" }, VsShortcuts = new[] { "Control+Shift+W" })]
public class CopyCurrentWord : IExecutableAction
Options -> Enviroment -> Keyboard & Menus have Resharper 2.x or InteliJ IDEA selected
The binding above doesn't apply after plugin installation using Resharper Extension Manager.
The keyboard binding does apply when I click "Apply Scheme" in options.
After Resharper installation I customized some shortcuts, maybe this is why it doesn't work after plugin installation.
Viktar
Hello Viktar, I too could only get the shortcut to take effect if I asked it to 'reapply shortcuts'. In the end I decided to just stick with the workaround I put in place for R#8 and map the shortcut in the code for R#9 too. Note that your shortcut macro name will be different in R#9
Regards, | https://resharper-support.jetbrains.com/hc/en-us/community/posts/205991029-Help-need-migrating-plugin-from-R-8-to-R-9 | CC-MAIN-2019-51 | refinedweb | 1,240 | 51.75 |
I have switched from Ubuntu to Debian, and am happy i did so. There are enough blogs talking about their pros and i only ask why i did it not before.
Well, when you wish to compile keepassx on Debian you may find one or two obstacles, i hope this post targets them and saves you some time.
Get It:
wget tar zxvf keepassx-0.4.3.tar.gz cd keepassx-0.4.3/ mkdir build
I recommend you to read the INSTALL file
apt-get install libqt4-dev apt-get install libx11-dev apt-get install libx11-dev
And finally you have to install this one:
apt-get install libxtst-dev
Yes, it do not leaves you given dependencies, i fixed it this way:
wget dpkg -i x11proto-record-dev_1.14.2-1_all.deb
And now you go!
apt-get instal libxtst-dev qmake make
And again, second challenge, you may find this message trying to compile:
lib/random.cpp: In function [void initStdRand()]: lib/random.cpp:98:19: error: [getpid] was not declared in this scope
I did this:
vi ./src/lib/random.cpp
Basically you just modify the file, before it looks like:
#include "random.h" #if defined(Q_WS_X11) || defined(Q_WS_MAC) #include
And it should look like:
#include "random.h" #include <unistd.h> #if defined(Q_WS_X11) || defined(Q_WS_MAC) #include
Advertisements | https://twilightbbs.wordpress.com/2015/01/ | CC-MAIN-2018-30 | refinedweb | 223 | 66.64 |
View Complete Post.
We have a process that loads multiple dll assemblies each of which contains multiple service interfaces hosted by one or more actual services. Some of our components need to be able to call other services internally. Of course I do
not want the overhead of marshalling / opening a channel / etc.
Since services can be singletons or created each time, I am trying to find a way to get the service or interface through the wcf architecture that handles this.
Does anyone know of a way?
[ServiceContract]
public interface IService1
{
[OperationContract]
IEnumerable<MyObject> GetAllMyObjects();
}
[DataContract]
public class MyObject
{
[DataMember]
public String Name { get; set; }
} :)
Thanks,
Bryan.
Should my service class implement the same interface as my DAL-class? Let's say I have an interface and two classes like this;
public interface IArticles
{
string[] GetArticles();
}
public class DAL : IArticles
{
public string []GetArticles(){...}
}
public class Service : IArticles
{
private IArticles _dal;
public Service()
{
_dal = new DAL();
}
public string[] GetArticles()
{
return _dal.GetArticles();
}
}
In this case, the Service uses BOTH inheritance and composition of the interface. What is the best solution?
Hi ,
I am tring to call external web service through generic handler , please post some example code for the call webservice from generic handler .
I have a web service hosted on different server. I want to access it from my jquery. but I don't know how to do it.
I know how to call a native web service from JQuery, but I am struggling to call the external web service.
Can you please suggest me what I have to do ?
Thank you in advance.
regards
ashish();
}
I tried to use interface to define services but the JavaScript function will fail. Without the interface, everything works perfectly. Consider the following.
Consider the following.
namespace Enroll.ER.Services {
[ServiceContract(Namespace = "Enroll.WebServices")]
interface IAccountService {
[WebInvoke]
[OperationContract]
bool Checkin(string acctKey);
....
}
}
namespace Enroll.ER.Services {
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AccountService : Enroll.ER.Services.IAccountService {
public bool Checkin(string acctKey); {
...
}
...
}
[DataContract]
public class MyFaultException {
[DataMember]
public string Reason { get; set; }
}
}
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/20583-how-to-use-external-web-service-interface.aspx | CC-MAIN-2017-13 | refinedweb | 354 | 51.24 |
<<
Helen Brophy5,405 Points
Not sure why my code isn't working
I'm not sure why this isn't working. Can someone please help me understand so I can fix it and move on to the next video?
def product(num1, num2) return int(num1) * int(num2) product('2', '4')
1 Answer
behar10,797 Points
Hey Helen! Couple of things, one is that you dont actually need to call the function yourself, the backend will take care of that for you, so just remove the product("2", "4"). Secondly, you dont actually have to use the int() function, try never to do something unless you were explicitly told to do so.
Hope this helps!
behar10,797 Points
Glad to help! You can mark the question as "solved" by selecting a "best answer".
Helen Brophy5,405 Points
Helen Brophy5,405 Points
Thanks for your help. I went back over my notes plus with your pointers I figured it out. | https://teamtreehouse.com/community/not-sure-why-my-code-isnt-working-6 | CC-MAIN-2021-43 | refinedweb | 159 | 73.58 |
Larry Wall on the Perl Apocalypse 121 121
raelity writes "Larry Wall provides some insight into the design of Perl 6 on. ." " This is a really interesting article and worth reading if you're at all into Perl. Full of Wallisms, entertaining and insightful.
we just need a pragma (Score:1)
"pragma shutthefuckup", to eradicate those annoyingly mandatory warnings.
;-) I seem to recall that one only needed "use namespace std;" if you wanted to use the STL libraries in C++ btw.
Re:A question for Larry (Score:2)
Cool. .net on steroids. (Score:3)
Hey, that's cool. It does what Microsoft
.net does, but better. At least it might.
One of the major ideas of
.net is not SOAP (dunno why MS marketing makes such a hype about that), it's that you can write code in one language and use it in another because all languages use the same framework. So you can write an object in C# and use it (even subclass it) in another .net-enabled language. In .net, data types and class libraries aren't part of a programming language, only syntax and concepts are. Actually the framework is quite powerful, it can even be used for functional programming languages etc. (the downside is that only a limited subset will become a standard). That's Java, but better, if Microsoft gets things right.
How's that related to perl?
Hmmmm. Now what's that? If the semantic model is powerful enough (i.e. provides enough support to implement different programming language concepts on top of it), that's
.net, but better.
I was already worried that a large part of the open source community would ignore
.net, but it seems that they're about to accidentally develop an alternative that's even better. I seriously hope the Perl developers realize this possibility :-)
Its been posted before... (Score:1)
...and it will be posted again. [detonate.net]
Bottom two frames.
--
Re:It Could Have Been Worse... (Score:2)
And with the language changing, maybe we can get away from reference counting, and then there won't be any need for the C++ features that led me down that path in the first place.
PS: There are no 't's in my name.
Re:What!!! (Score:1)
I mean, come on. I knew it was a joke as soon as I read the stuff on the front page.
"The power of Perl and the sanity of Python."
WHAT sanity? If I ever need to obey the line breaks and whitespace rules of Python when writing Perl code, you'll soon find me at the nearest asylum... =)
(Not intended as a flame bait. Both are good languages. =)
Re:Wow... (Score:2)
And I imagine that once you get up to the level of project where you need to write your own modules, you probably would be using strict and -w anyway, for sanity sake if nothing else.
It Could Have Been Worse... (Score:2)
Think of the disaster that would have been.
"What do you mean, Perl will no longer install on my Solaris box? I don't have space for C++ as well as C. ARGH!"
C++ is still not protable across platforms in any sort of reasonable sense. It would have been nice if it was.
Luckly Chip got talked out of it. (Probably with a big stick.)
Re:Wow... (Score:1)
Add a garbage collector to C++ and you'll never need to delete. You may think Perl does the same, but if you introduce a circular reference...oh dear, there's a leak. (I know Perl 6 promises to fix this though.)
Re:Wow... (Score:2)
Perl was designed to mirror human languages, not computer languages. (C++ may not have been designed in this way, but it certainly has evolved in a very similar direction.) You're not expected to completely understand the language, you're expected to quickly learn a fairly small working set of features, then slowly grow that knowledge as you grow in the language. Like english, or any other human language, both you and the language constantly grow to handle new problems and solutions. This is part of the reason Perl and C++ are so popular, they're living languages with practical goals. They don't force certain designs and strategies on you, they try to let you work with them as you will.
Re:Um. Perl6 knows that it is perl 6 because... (Score:1)
perl 6.0
Since when has readability been a priority for Perl?
Re:Cool. .net on steroids. (Score:2)
Intermediate Language (IL) is what provides the COM-like capabilities to extend classes from one language to another. The two are very distinct. IL does not require a roundtrip conversion to XML. IL is more analogous to Java Bytecodes, except that there will be multiple languages mapped to IL. IL will require "managed" subsets of languages like Visual Basic, Visual C++, and Perl.
As for this comment:
I believe you have this 180 degrees backwards. The idea for the semantic model isn't so that other languages can be mapped to Perl. It's so that Perl can be mapped to other languages (namely, Java Bytecodes and
.NET's IL). I'm not really sure what the benefit would be of mapping other languages to Perl, when so much effort is being placed on optimizing the runtime environments for Java and .NET. I think Larry's got the right idea.
Re:Cool. .net on steroids. (Score:2)
condradictions... (Score:1)
The article was great if you are a Camel lover but some of us aren't (I use it for web stuff, but I am not Perl junkie
I am glad to see Perl continuing development, but I still think that Perl/Parrot would have been best
Re:It isn't? (Score:4)
It's my belief that I should quack like a duck while juggling bowling balls while completely naked, in the middle of Times Square.
That's funny. It might be my belief, but it's still funny. The two are not mutually exclusive.
I also think it's funny to take "apocalypse," which is commonly defined as the end of the world, all living things die, etc., etc., and redefine it to be a good thing. In the strict sense, Larry Wall is right. Merriam-Webster says:
apocalypse
Etymology: Middle English, revelation, Revelation, from Late Latin apocalypsis, from Greek apokalypsis, from apokalyptein to uncover, from apo- + kalyptein to cover -- more at HELL
Date: 13th century
1a: b capitalized: REVELATION 3
2a: something viewed as a prophetic revelation b: ARMAGEDDON
But I think it's funny to take the opportunity to take what everybody thinks of as a bad thing and turn it into a good thing, in the Christian definition. That's the Christian thing to do, I guess, is recruit more Christians. Larry Wall took advantage of an unusual opportunity to do so, and I think it's funny.
-Waldo
Re:A few bad apples. (Score:1)
Re:Wow... (Score:2)
Oh please. You don't have to use the warnings or strict. Most one-liners don't. You can still express conditionals and looping in at least a half-dozen different ways. You practically have to use strict in CPAN modules (though there's no hard requirement) because it's widely distributed code that could choke if someone did use strict and you code didn't conform.
This is nothing like Python, a language that has never heard of a pretty-printer, and thus hardwires one into the language definition itself.
--
Re:Wow... (Score:3)
MUCH cleaner than moc.
--
Re:Perl is scary. (Score:2)
Re:Wow... (Score:2)
Re:Wow... (Score:3)
All in all, this first introduction to LW's ideas for perl6 sounds pretty good. I'm looking forward to more details about what he plans to do with references. Blurring the difference between an array and an arrayref, as he proposes, seems like it could be either the biggest fuckup, or the biggest improvement to the perl language. I can't wait to read the proposed new semantics and see how it's going to work.
This probably goes together with giving prototypes and typed arguments to functions and methods; I wonder if perl6 is going to need an 'apply' function, to pass a list of arguments to a function (as opposed to passing the list as a single argument), like Python does. As a perl programmer, at first it sounds bad to me, but I could possibly be convinced that it's worth it.
Finally, I'm a bit skeptical about the idea of compiling perl into jvm or C#/IL. Despite all claims to the contrary, I don't see these bytecodes being generic enough to implement all of perl's functions (including its amazingly extended regexp engine) with reasonable efficiency. The OO side (integrating objects and mapping methods and properties) isn't really the problem, but I just don't see a JVM-compiled perl module using C-based extensions from CPAN, and I don't see all CPAN modules giving up C integration either. All in all, I think the perl interpreter should remain C, with a good C-based extension model (more like SWIG, and losing the "XS" obfuscated lossage), and work together with the JVM and IL interpreters, supplementing them at the C level to run perl code.
Re:Great! (Score:1)
Re:Um. Perl6 knows that it is perl 6 because... (Score:1)
perl 6.0
I guess you can still do a
require 6.0;
if that's what you're after. Require and version numbers have worked for quite some time, I think.
Re:Um. Perl6 knows that it is perl 6 because... (Score:1)
You got the command wrong. It's
Re:It isn't? (Score:2)
I'm not a xtian, I don't play one on TV..I just felt it necessary to point this out -- it *isn't* a bad thing (they way they wrote it)
A question for Larry (Score:1)
Larry,
How do you feel about having me as a son in law? I know that having a troll in the family can be a bit traumatic, and I'd like to know upfront if this will cause any problems. I'd like to work through them before the wedding, so that everything can go smoothly.
I know that you're a little disturbed by Heidi's recent spate of trolling here on
You are probably also thinking that maybe your daughter can do better than a shiftless layabout who got fired from AtomFilms.com for sexual harassment, but c'mon. Think about it. Look at my flowing, golden mane, my high cheekbones, my chiseled jaw and my piercing eyes. Could any young woman possibly do any better? If you're still not convinced, you can look at my broad shoulders, barrel chest, washboard stomach and manly bearing. Now you can go have a cold shower, you probably need it.
Later,
--Shoeboy
Re:Um. Perl6 knows that it is perl 6 because... (Score:1)
No, then you grab perl-6.0-i386.rpm and rpm -U it... problem solved
Re:Um. Perl6 knows that it is perl 6 because... (Score:1)
Language design is a trade-off. He's trying to avoid instanly breaking 90% of the one-lines out there, and keep the freedom the Perl is famous for, while moving on.
As he himself states, forcing folks to "use perl 5" would break everything. Settling for "use perl 6" (and, understand that there will be ways to get around this -- note his comments about "use policy") lets us get on with the concept of coding, and not with the concept of re-coding. Going to be hard enough to re-write all these modules...
----Woodrow
Wow... (Score:3)
Perhaps we will have to evolve super-intelligent Khan-like coder clones in the future, using nanotech, Beowulf clusters, and in-dash Atari 2600 emulators.
use module vs use Perl 6 (Score:1)
I know this isn't really any different than requiring a particular version of a library, but it just seems ugly to me. Still, very much looking forward to reading the rest of the Revelations of Larry.
--
Dunx
Re:A question for Larry (Score:1)
Re:Wow... (Score:2) [cpan.org]
Re:Wow... (Score:5)
Every time I go into a bookstore to read about C++ (every 4-6 months or so) I find out about more and more "features" that were added since I learned the language in 1995 or so. Stuff like 3 different versions of new and the namespaces.
IMO C++ has grown from being a useful extension of C to becoming a massive, horrible mess with too many features. Lots of people I know and work with talk about C++ in terms of being hard to learn and use well because it is extremely intricate. This is a good thing?
I'm disturbed by some of the more recent proposals for C++. Whitespace overloading?!? ho are we kidding?
I'm just glad that other people find solace from the insanity of C++ in Perl. Sometimes its refreshing to be able to choose your own way to do things, and to know that other people like you just want the damn program to work, with a minimum of futzing with things vaguely related to the problem you are solving (i.e., memory management ala C++ -- just how to exceptions and delete interact in a class hierarchy?) Who cares - every app I have written in the past 2 years has not needed to worry about these sorts of vaguely related things - why FORCE me to? Preaching the "paradogma" (great word Larry
There are certainly a number of cases when you NEED to care about those mundane, tedious details. Real-time programming and other systems level work are good examples.
I guess all I am saying is, thank you Larry, for freeing programmers like me from the tedium of malloc and free, sizeof and screwy arrays. You have added 20 years onto my lifespace, at least.
The Perfect Number (Score:2)
Larry, I think number theorists would crack that, contrary to general belief, the number 6 is one of those most significant and rarest of numbers belong to the perfect number category. Those number have their divisors added up to themselves (6=1+2+3). The other perfect number is 28 (28=1+2+4+7+14). Perhaps someone will be able to point out the others.
But whatever the perfect number, I am sure that Perl 7 will be more pearly than Perl 6
Re:Apocolypse (Score:1)
Armageddon (the field of Meddigo, site of an especially bloody historical battle) is the location of the final battle. Apocalypse is synonymous with revelation, e.g. Revelation of John == Apocalypse of John in the Bible.
Re:condradictions... (Score:3)
I think you may have read it wrong. He was simply stating the way that perl6 modules would be declared is different than perl5 modules.
Nothing was added, just changed.
The quote follows:.
--
A mind is a terrible thing to taste.
Re:Seriously, Perl *is* scary! (Score:1)
It doesn't work right now, because I'm in the middle of revising the core fuzzyfying functions for searching on variants of, for example
/yoursisterstits/images/poolbabe1.jpg to find backup files and additional images not listed in the thumbnail gallery, plus revising the user interface for declaring the method of fooling mod_referer, but who am I kidding. I don't have that much time to look at porn.
Boss of nothin. Big deal.
Son, go get daddy's hard plastic eyes.
Re:Shameless fan mail :-) (Score:1)
I'd recommend that you read "The Design and Evolution of C++" by (who else?) Bjarne Stroustrup if you're interested in this kind of non-academic language design. The book's a bit old, so it's missing some of C++'s newer features, but it's a fun read if you like that sort of thing.
Re:Wow... (Score:2)
IMHO, they should have been addressing some of the design patterns that are harder to implement in C++.
I mean just look around at what people *want* to do with the language. Look at Qt and their
just my 2 cents...
-pos
The truth is more important than the facts.
Re:Wow... (Score:1)
Mike.
Re:Thanks to Larry and Tim: Paying for the vision (Score:1)
This is the right direction for Perl (Score:3)
First of all, it's sad that Slashdot couldn't hold notable members of the Perl community. Makes me a bit wistful to look over the nearly content-free posts on this topic and remember Abigail's scathing and 100% accurate flames, and Tom Christensen's odd and brilliant posts. Assholes, maybe, but their minds are unparalleled and their writing incisive. They're sorely missed in a discussion like this.
In any case, Perl is in good hands. Require strict and warnings for modules makes sense. Leaving room for Perl to grow is a good thing. Making everything an object that is free to return in scalar context adds flexibility while giving functions the freedom to behave as they see fit.
Most of all, these principles are in place before the major work of adding full Unicode support and meta-languaging begins. There's a firm hand on the tiller, and Larry seems as up for the work as he ever has been.
When Perl has a real specification, period. (Score:1)
This is the fundamental reason why languages defined by portable implementations have problems growing beyond those implementations. The implementation actually specifies too much of the langauge's behavior - a real spec says explicitly what behavior is implementation-dependent, which tells implementors and users both exactly where the boundaries are.
The Common Lisp and Scheme communities wrote real specs for their languages (ANSI and IEEE, respectively). The user communities routinely beat up implementors and vendors who don't conform to the spec. As a result, they can write portable programs that compile to native code, without getting stuck in the C/C++ quagmire.
Someday there may be a way to answer these questions:
Are JPerl and Perl the same language?
How about JPython and Python?
that doesn't boil down to "ask Larry/Guido". A year or two after that, you might see real compilers for those languages.
Re:Wow... (Score:1)
No, he is planning (suggesting?) that that should be the default. Perl rarely forces anything.
perldoc -f no
Re:condradictions... (Score:2)
Re:use module vs use Perl 6 (Score:1)
--
Re:Wow... (Score:1)
Unless I misunderstand, I think that nothing stops you from saying:
no strict;
no warnings;
after your module or class or whatever statement if you really want to. Frankly, I think "encouraging" module writers to be -w safe is a great idea. One of my favorites is hideously noisy with -w, (unless it's been rewritten recently); every time I use it I have to look at the output and remember whether this means it failed or if it's just the usual noise.
--
Re:PERL MONGERS READ THIS (Score:1)
--
Re:Proof that P users are stupid. (Score:2)
Either you jest or you display ignorance. The perl distribution comes with tons of doc. Try issuing perldoc perldoc. You can use perldoc -f function_name_here to get information about any perl function and perldoc module_name_here to get documentation about any module for which the author has provided it (which is most of them if not damn near all of them).
More to the point, try man perl - each of the 70 sections is its own extensive man page, covering references, objects extensions in c - you name it it's probably there.
Oh, and how extensible is Perl? I never heard of an applet written in Perl.
What do these 2 sentences have to do with each other? many meabytes of perl extensions can be found at CPAN [cpan.org] - I don't believe I've ever wanted to do something that wasn't made much easier by something that was already there. What does writing applets have to do with exensibility? perl is quite extensible in both perl and c. And there is a project to compile perl source to java bytecode, tho I'm not sure if it's still active. But client side applets aren't my main concern. I don't think they're flavor of the week anymore, anyhow.
--
Perl 6.66 (Score:1)
Re:Wow... (Score:1)
Re:Cool. .net on steroids. (Score:1)
I'd be up for that..
..anyone know of a project going, let me know...
Re:Seriously, Perl *is* scary! (Score:1)
This is a really big part of Perl for myself. After learning a certain amount of the language, I was able to start guessing at how perl would work, and it would usually work that way. Where the more designed languages seem to have just mandated the way things are done, Perl tries to interpret as many ways as a user might think of doing them. This is not an easy task, and once accomplished can yield some very ugly, bad code.
It goes something like this: I say, "I wonder what would happen if I tried xxx." Perl will do it the way I want. C doesn't work that way. Java will surely have deprecated the useful way of doing it because it wasn't supported on a common architecture like the Timex Indiglo.
Re:condradictions... (Score:1)
I think the point was that the EXTEND keyword at the top of the DEC BASIC programs served no purpose other than to say "I am a new program", whereas the (proposed) Perl 6 method merely replaces the "package" keyword with something else. The keyword has to be there anyway. Changing from "package" to "class" just overloads the meaning.
--
Re:Thanks to Larry and Tim: Paying for the vision (Score:1)
Sure they will. So what?
wont the profit generated be more than enough to cover the salary they pay him ?
Perhaps. So what?
isnt oreilley as a business simply existing to generate profits ?
Ahhh, not necessarily. There are plenty of businesses that exist for reasons besides simply making a profit.
Habit #5: Think Win-Win [amazon.com]. Try it some time.
Not all positive decisions have to be at the expense of others. O'Reilly helps the computer biz, and it helps improve their own market, and Larry gets a job making bucks doing what he loves. What's wrong with that?
--
Thanks to Larry and Tim: Paying for the vision (Score:2)
I think it's great that Larry is taking the time to be the visionary and leader on Perl, and providing so much of himself in what goes into Perl 6.
And I think equally important is that O'Reilly [oreilly.com] are basically paying Larry to do it. As far as I know, Larry's been getting a paycheck from ORA for just doing the Perl stuff that he does, not unlike Damian Conway getting a paid year sabbatical to be Damian.
That salary for Larry has to be some of the best investment in the community and infrastructure of software development yet, and I cheer Tim & co. for doing it.
--
Re:Summoning lost spirits (Score:1)
Re:Cool. .net on steroids. (Score:2)
Re:The perfect language (Score:1)
The perfect language (Score:2)
I think that java approches being a really great language, but stops short because it is so god awful slow. It is also very verbose and although I like it, it doesn't go as fast as perl,python, or php. What it does have is stability, consitency, and standard libraries that come with every runtime environment. If perl 6 had classes remenicent of pythong, came with a full featured standard GUI (TK is quick,dirty, and fast but doesn't compare to the feature set of swing), standard thread, standard complex sound IO, and standard socket set that's more straightforward, I would never use anything else. I know its alot, but if that was there, then I think the language would be much more complete, then other stuff could be added with modules.
Re:What!!! (Score:1)
--
What!!! (Score:3)
Re:Wow... (Score:1)
I also get the impression that even if using warnings and strict is the default behavior, it will still be possible to turn it off if that's desirable. IIRC somebody suggested that there be something like a use loose pragma that would turn off default strict behavior, and it's already possible to selectively turn off warnings for particular blocks of code. I don't think that anyone has seriously suggested making Perl a Bondage and Discipline language where everything must be done just so.
Re:Proof that P users are stupid. (Score:1)
Which just means that you're not looking. In fact, there is currently a reference to an article on writing Gnome panel applets [perl.com] in the Perl slashbox here on slashdot. Your lack of knowledge does not mean that it isn't being done.
Re:use module vs use Perl 6 (Score:1)
There's already a use [version] pragma that requires that the Perl in use be [version] or higher. IOW, use 6.0.0 would not prevent the code from working in a hypothetical perl7.
Re:Wow... (Score:2)
It just so happens that I know exactly one such person--and he is (without a hint of exaggeration) a mind of genious caliber. Hmm... Well, I guess you've taught me that I should forget about becoming a C++ expert. Thanks!
Re:Perl is scary. (Score:1)
Not very definite (Score:1)
Is it just me or does that pretty much sum up the article? Not being a troll, but for being articles that are supposed to define what direction Perl will be headed, they don't seem to give any definite answers.
I think that Larry took on a much bigger job than he anticipated when he decided to completely rework the language. Making a language that is entirely perfect, yet all things to all people is impossible and he will have to realize that before any real work will get done!
--
(Mountain Dew == Canned Code)
Seriously, Perl *is* scary! (Score:1)
In a way, this is a variation on Microsoft's Always-Second-Guess-The-User mentality. The difference is that MS assumes all users are idiots, and Wall assumes all Perl programmers are like him: gifted creative people who prefer non-linear thinking.
OK, this is nothing wrong with this. I'm not part of the Perl culture, but I respect it. Just try to remember that the ultimate purpose of all software is for somebody to use, not just to show how clever you are.
__
Um. Perl6 knows that it is perl 6 because... (Score:2)
Sure that works. Sure.
But wouldn't it make the language a lot more readable to start with a new line like:
perl 6.0
Then newbies would be more likely to guess why their perl5 compiler/interpreter croaks??
No of course not. That would make no sense. They wouldn't have to buy a book from a certain well known publisher to use Perl...
So I'm cynical. Call me cynical.
Re:Um. Perl6 knows that it is perl 6 because... (Score:2)
Of course your perl came bundled with the OS and is a version behind.
So you would swear about perl a bit and then you give up. That's how it goes pretty much isn't it?
Re:Um. Perl6 knows that it is perl 6 because... (Score:2)
To a reasonable approximation either the 6.0 system understands 5.0 syntax or it doesn't. If it doesn't its going to come unstuck anyway when people try to run it on legacy code. If it does, and Larry seems to imply that it does to some extent, then there's no excuse for making this harder for users.
A language should beg people to use it. It sells more books too.
Re:PERL MONGERS READ THIS (Score:2)
Larry wasn't talking about making functions return the current, bloated implementation of objects -- he was, instead, talking about adding a new implementation of object (based on a C struct) to perl, and having them return those -- implemented well, this shouldn't be much slower than the current (parsed) implementation such things, especially since often what you'll lose in having to make sub calls for stringify and numify you'll win by not having to translate the original structs in the first place.
An object is just a concept, not an implementation.
Josh -- (of NY.pm)
Re:The perfect language (Score:2)
Huh? Java has a totally retarded language design that at best is an imperfect improvement over an even larger kluge, C++.
Of course, some of the "improvements" to Java aren't improvements at all. Everything is a class? No templates?
There is a reason all the implementations of Java are crappy - you can't make a cake out of shit.
Perl versioning... (Score:1)
Perl is as much a culture as it is a programming language.
I personally do not like the idea of using the existence of "package" as a way to distinguish perl5 from perl6. While this works for the modules, what about non package applications?
There's already a require VERSION convention established. The new version of perl could require that this be supplied to activate perl 6 functionality. Scripts without this would be assumed to be at 5.x.
- Pat
Re:The perfect language (Score:1)
Don't confuse design with implementation. Java is a great language with mediocre implementations and monolithic amounts of class library rushed out the door to feed the ravenous programming public at large. Java has enormous room for improvement in the realm of performance.
The java language itself is rather elegant, right down the the bytecode operations.
However, at the moment, we're talking about Perl.
Before Perl, I would have defined a great language as one with a straightforward and clear design. Java qualifies, however, Perl is none of these in my opinion. Perl can't be described in BNF -- it requires a magical context sensitive tokenizer sprinkled with magic Wall-ian pixie dust. Yet, without question, Perl is a great language too.
Perl has forced me to redefine my definition of a great language as one which effectively fulfills the needs of it's users. This is something which even the angriest python evangelist would have to agree that perl does well.
There are tasks I can accomplish in a 1/2 hour of perl coding which would take me days to accomplish in java. Programming perl is also more fun to me...I don't know why. Perhaps this is due to it's "more than one way to do it" philosophy which provides me with countless options. Perhaps it's the unix based culture that I love. Or perhaps it's the overall goodhearted spirit behind the majority of the Perl community that Larry has carefully fostered.
I wouldn't, however, want to manage a million lines of perl code. One of the things I've noticed is that the better the perl programmer, the harder it is to read their code.
Perl is the language which allows you to do in 1 line, what you should have done in 20.
Re:PERL MONGERS READ THIS (Score:2)
Second, Perl5 is already ebject oriented. But the OO stuff is kind of kludgy and particularly unieldy when dealing with class hierarchies. I cannot see how moving OO features to the core, as I understand is planned, and cleaning up the way inheritence is handled based on Perl5 experience can make Perl6 worse than Perl5. This is not adding features, this is correcting suboptimal design.
Re:PERL MONGERS READ THIS (Score:2)
Seems to me the opposite is true. Right now using objects and packages incur high overhead. Moving the inheritence code from the interpreter to the core ( which is compiled) should eliminate some of it and improve performance of OO perl code. The basic issue is that we are not talking about adding OO to perl but about correcting a faulty OO implementation. You ask what is wrong with thingies and packages. basically, IMHO, performance and the inhereritence mechanism. If Perl 6 improves on these issues it will be a Good Thing.
I certainly see the danger of screw-up, and simulating java performance will be a disaster. But we ought to give Larry Wall some credit
;-)
Re:The Perfect Number (Score:1)
6
28
496
8128
then it gets hard.
anyone know a proof that all perfect numbers are even?
Re:hrmm, perl is still better than PHP for web wor (Score:1)
In any case, I don't care much for the kind of data acquisition slash web proposition you're describing anymore. But if Perl is helping you to develop an exciting application, more power to you.
In fact it might be illuminating to hear, from your application's point of view, what you reckon might be the most exciting new feature in Perl 6.
Re:Summoning lost spirits (Score:1)
Still I can't help but feeling that the language has somehow aged (rather than matured) over the last couple of years. People just don't seem to be as enchanted with Perl as they used to be, and "Perl 6" in places seems motivated by a strong sentiment to regain this lost sense of wonder, instead of by concrete applications that Perl could be or should be targetting.
But, I know nothing.
Summoning lost spirits (Score:2)
But nowadays, I'm bored stiff with (programming for) the web, and likewise, my interest in Perl has waned. Also not unimportant, stuff like PHP has basically taken the crown from Perl where it comes to web development.
This is not to say that Perl doesn't have a place. Perl lends itself extremely well to perlish things. It's just that the excitement surrounding Perl seems to have diminished.
And so sometimes I cannot help but wonder whether this longish and rather dramatic prelude to the start of the preliminary design for Perl 6 is really not just a way to try and summon some lost Perl spirit; to try and recapture some of the excitement of yore.
Does the world really need another Perl? And if yes, what should it provide? The answers to that last question seem to oscillate wildly between grand visions of syntax independance and mundane matters such as thread support.
Frankly I think neither answer is very exciting. Grand visions are a dime a dozen, and thread support is just thread support.
The bottom line, I guess, is whether Perl 6 will succeed in targetting an application, or whether it will just succumb to change for the sake of change.
Let's just hope for the former.
Re:PERL MONGERS READ THIS (Score:1)
Making one great piece of software that needs little or no change does not mean the next to come will be an improvement.
Of course, you might argue, presidents have little to do with software.
Re:PERL MONGERS READ THIS (Score:1)
I understood what you tried to say, but let me tell you one thing, C++ objects are little more than complex structures.
C++ is slower to compile, but you only compile once. You see there'll be a penalty for perl every run and not just once. So in perl the fact that it becomes OO has longer lasting consequence.
What is amazing about OO in C++ is the mangling of names that end up in libraries with 200 character identifiers. In perl we got packages and blessed thingies - why change that? You saw the part on perl5/6 compatibility? I dropped java because there is more than one version, the best browsers won't run the code from the latest SDK's(whatever, JDK) and I felt Sun was messing a great idea up. Also I can't think of anything slower than the latest java machines.
So back to perl, I fear perl will be slower, clumsier and unstable just like java.
The CPAN is becoming a mess, and that is leaving me perl-paranoid - am I loosing my favorite language?
See for example the Gtk modules. Doing a CPAN installation with the shell you get Gtk. Then you have to go to your
See the Net::IRC module, it has some code by Nat Torkington, or so the authors claim. Everyone knows Nat is a great perl programmer, but I took the time to read the source and geez....what a mess....is that the kind of libraries being allowed in CPAN?
I think we might be loosing it. I want a snapshot of perl and CPAN from January 2001, I don't need more than that....like I said perl will be perl5.
Re:PERL MONGERS READ THIS (Score:1)
As I don't know how thingies get casted from one type to the next in perl guts I don't know how much faster the objects will be for type conversion. If I had to take a shot, I'd say slower.
Anyway, I hate to see perl go true OO and "fix" all the little things that don't need fixing. Do you want to be geeky like python programmers(oh man, I'm outta here now...)?
Blah! Enough writing on
Re:PERL MONGERS READ THIS (Score:1)
I agree that perl inheritance is one huge patch, but exactly does it do wrong? Use an array to find parents and children? What's wrong there, really? It is different and Larry always bragged about perl OO being just different. Java won't allow multiple inheritance, C++ will, and perl uses and array for inheritance and the word "class" isn't there, it's different but how is this going to be corrected when there's nothing wrong with it.
I do give Larry all the credit in the world, and who I am to be the critic, but I don't think perl needs changing. It needs improvement on what's already there. Make it faster, provide better compiling support for commercial applications, add functions, make some extremely popular and well tested modules a part of the core, and so on.... Please let it be clear that although I started this thread saying "Larry is out of his mind" I do respect him and have chosen perl for more than the language, I also chose it for the people that use it and for the discussions that it brings about
I just hope this doesn't end up like java, really....
PERL MONGERS READ THIS (Score:3)
- Everything will be an object.
This is ridiculous. I always chose C over C++, now I'm choosing perl5 over 6. Period. I'm a perl5 monger(brasilia.pm.org) now. There'll be perl6 mongers. I'll call them the PERL BLOATERS. I can write better perl with perl5.
- 'package' means perl5 otherwise 'use perl6';
A FCKING PATCH. MICROSOFT STYLE, LARRY. Go for it.
- Perl will stay perl.
Uhuh. And we're all stupid and can't tell. Perl 5 is PERL, 6 is PERL++.
Conclusions
Yeah, just like Samba we're going to see 2 perls from now on. I'm sticking with 5. Most will move to 6.
Fine with me. Just glad I dig perl 5. If others agree just show you do by writing better perl 5!!!!
Perl is scary. (Score:5)
Some people get scared when they hear the word Perl... [bbspot.com]
Re:Great! (Score:1)
Haven't tried it yet. May get around to it tonight.
Re:Wow... (Score:1)
That would be the real Perl Apocalypse.
When will the Perl compiler make real executables? (Score:3)
I am disappointed by the fact that Perl can not deliver compiled code. The help blurb on the Perl executable says that the compiler option is experimental! When will this not be experimental?
Shameless fan mail :-) (Score:4)
I think this article is interesting in that it gives some rare insights into language design. You always hear people complaining about why didn't x (where x is C++, Java, Perl, etc) do this or that? Why this feature or syntax? Here Larry points out some trade off that may not be obvious to "end user". And all written in a easy to understand language called English too
;-)
While this is not a complete redesign, it is not everyday you get to see just exactly one design an programming language used by millions of people. Good stuff, definitely stuff that matters. This is a must read for people interestined in programming language. I am really looking forward to the next one.
OT: The design of Perl6 is somewhat similar to the kernel: anyone can submit rfc (patch) and Larry (Linus) has the final say on what goes it. (No, I don't know where I am going with this either
:-)
====
There is a perfect language - C (Score:1)
As for classes, they are certainly easier to impliment in C++, but well structured C code can be made to behave very similarly, and without much extra effort. The class implimentation in perl seems rather odd and unintuitive.
Re:Wow... (Score:3)
OTOH, why not? Python does it [ducks]
--
Re:Wow... (Score:5)
The most notable, for me, is the addition of namespaces. While I understand and agree with the idea that unused functions shouldn't pollute the global namespace, I find that moving all of C++'s standard functions into a separate namespace overkill. It isn't like C++ programmers were having trouble coming up with function names that clashed with strcmp(), for example. What this leads to is the extra line
use namespace std;in many programs. In essence, the moving of all these functions into a separate namespace just forced developers to create a rote workaround, not unlike the issue Larry brought up with class or module.
Perl itself has grown over the years, and while many changes have benefitted the programmers and opened up many doors (references, objects, etc) the core language has changed little. Larry seems to be moving away from the spirit of TIMTOWTDI and more towards the BSDM style of language exemplified by Java (or insert a language you love to hate). "You must use warnings and strict everywhere except your main module" is not free and fun.
There is no doubting the efficacy of -w and use strict;. I use it in all my own Perl programs, but many don't. This used to be okay. When I used to answer questions on clpm, I always chided querents for not using them. It was good advice (just turning on warnings can help nail a problem in many cases), but they could always take it or leave it. Now in Perl 6 it seems that this attitude that what goes on between programmers and the language is none of our business is done away with, and a school marm with a quick ruler is the new paradigm.
I grew up in Perl during Perl 5 and always laughed at the backwardness of those who touted Perl 4's abilities (Alaskan electrician, Purl Gurl, etc.), but now I find myself wondering if I am exhibiting the same stubbornness. If I am, am I right in this? Perhaps I need to change with the language?
Dancin Santa
Perl 6 (Score:4)
Threading - MP3::Napster, a popular module written by Lincoln Stein requires a threaded perl interpreter; I happen to use this module for my project [no-ip.com] (spam, spam [grin]).
More perl ports - I would like to see perl ported to PalmOS; some nodes on PerlMonks [perlmonks.org] reveal that there is a lot of interest in this; Although I sometimes wish they would take a look at the projects on handhelds.org [handhelds.org].
Dusk begins to realize that he is ranting....
Anyway, I am sure that I will be pleased with the results; Saint Larry will not let us [perlmonks.org] down
:)
Great! (Score:5)
My guess it that Python porters were able to overcome this obstacle by writing much of Python in Python itself, hence Pippy. [endeavors.com]
Once Perl 6 is released, though, the Perl community will be able to quickly play catch up, and get a port out rapidly. Woohoo!
Re: It's called Dylan. (Score:2)
I have to say, though: of the currently popular scripting languages, Python seems to closest to becoming a real programming language, and it's still retaining its original utility and simplicity. What Python is missing at this point is a new implementation that provides incremental compilation to efficient native code, plus a few language cleanups to go with that.
Re: It's called Dylan. (Score:2)
Re:A question for Larry (Score:2)
I know I'm better then Heidi just ask my ex boyfreind
I fucked Heidi's camel once!! | http://developers.slashdot.org/story/01/04/03/2020200/larry-wall-on-the-perl-apocalypse | CC-MAIN-2015-32 | refinedweb | 7,587 | 73.27 |
I'm working on a simple game engine just for the experience of it. I've realized, though, that I have no idea how to export the user's custom game as its own standalone executable. For example (this is not my actual game engine, it just provides an easy reference for discussion), suppose we had the following very simple code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void RunGame(string question, string answer)
{
string submission;
cout << question << endl;
getline(cin, submission);
if (submission == answer)
cout << "Correct!";
else
cout << "Wrong!";
}
int main()
{
string question;
string answer;
cout << "Enter Question:" << endl;
getline(cin, question);
cout << "Enter Answer:" << endl;
getline(cin, answer);
RunGame(question, answer);
}
Building an executable is non-trivial. You will first need to comply with the target operating systems' ABI so that it can find your program's entry point. The next step will be deciding how your program is going to be able to access system resources: probably you'll want your executable to implement dynamic linking so it can access shared libraries, and you'll need to load the various .dll or .so files you're going to need. All the instructions you'll need to write for this will vary from OS to OS, you may need to introduce logic to detect the exact platform and make informed decisions, and you will need to vary for 32 vs 64 bit.
At this point you're about ready to start emitting the machine instructions for your game.
A reasonable alternative here is (as done by Unity) to provide a "blank" executable with your engine. Your engine itself would be a shared library (.dll or .so) and the blank executable would simply be a wrapper that loads the shared library and invokes a function in it with a pointer to something in it's data section.
Generating your user's executable would comprise loading the appropriate blank, making platform-specific modifications to it to tell it the size of the data section you're intended to provide it with and writing your data in the appropriate format. Or, you could simply have a blank that has an embedded copy of the raw structure into which you write values, just like populating a struct in memory:
struct GameDefinition { constexpr size_t AuthorNameLen = 80; char author_[AutherNameLen+1]; constexpr size_t PublisherNameLen = 80; char publisher_[PublisherNameLen+1]; constexpr size_t GameNameLen = 80; char name_[GameNameLen+1]; constexpr size_t QuestionLen = 80; constexpr size_t AnswerLen = 80; char question_[QuestionLen+1]; char answer_[AnswerLen+1]; }; static GameDefinition gameDef; #include "engine_library.h" // for run_engine int main() { run_engine(&gameDef); }
You'd compile this againsst the shared-library stub for your engine, and emit it as an executable, then you'd look up the platform-specific details of the executable format, locate the position of "gameDef" in it. The you'd read the blank into memory, and write it out with the definition of "gameDef" replaced with the one based on user input.
But what many engines do is simply ship or require the user to install a compiler (Unity relies on C#). So instead of having to tweak executables and do all this crazy platform-specific stuff, they simply output a C/C++ program and compile it.
// game-generator bool make_game(std::string filename, std::string q, std::string a) { std::ostream cpp(filename + ".cpp"); if (!cpp.is_open()) { std::cerr << "open failed\n"; return false; } cpp << "#include <engine.h>\n"; cpp << "Gamedef gd(\"" << gameName << "\", \"" << authorName << \");\n"; cpp << "int main() {\n"; cpp << " gd.q = \"" << q << \"\n"; cpp << " gd.a = \"" << a << \"\n"; cpp << " RunGame(gd);\n"; cpp << "}\n"; cpp.close(); if (!invoke_compiler(filename, ".cpp")) { std::cerr << "compile failed\n"; return false; } if (!invoke_linker(filename)) { std::cerr << "link failed\n"; return false; } }
If "RunGame" is not part of your engine but user-supplied, then you could emit that as part of the cpp code. Otherwise, the intent here is that it's making a call into your library.
Under Linux you might compile this with
g++ -Wall -O3 -o ${filename}.o ${filename}.cpp
and then
g++ -Wall -O3 -o ${filename} ${filename}.o -lengine_library
to link it against your engine's library. | https://codedump.io/share/MZtJE365a1zz/1/creating-a-custom-exe-file-in-c | CC-MAIN-2017-13 | refinedweb | 693 | 59.43 |
Ember Pro
We’ll go way beyond the fundamentals, tackling topics like authentication, advanced debugging techniques, server-side rendering, modular app design.
This course is designed to help developers already familiar with Ember.js to unlock the true power of the framework.
Welcome & Setup
Some friendly introductions, and a quick overview of the training plan.
Container, Loader and Resolver
Like many opinionated web frameworks, most of the code developers write is in hooks: important functions that are called in a predictable way, which may be extended to customize behavior.
When things appear to go wrong between hooks, being able to peek into a few of the important framework internals can be incredibly valuable. We’ll cover three important concepts that will start to give you visibility into what may have previously been a black box
EXERCISE: Consume ES5 modules in ES6
Using our knowledge of the loader, let’s put a file in our
/vendor folder to make an ES6 module available in our app in totally different namespace.
Initializers
If you’ve ever copied and pasted a code from a library’s source, in order to customize a little behavior within a complex internal process, you’ve likely felt the pain of keeping your customized behavior in sync with upstream changes to the library.
Ember’s boot process was built with customization in mind, and provides a mechanism for inserting our own custom code at various places in startup process. These bits of code are called initializers and instance-initializers.
We’ll build on our knowledge of the container, and use the Registration API to prepare it for our app, in some initializers and instance-initializers of our own.
EXERCISE: Container setup in an Initializer
We only want our app to boot up once we have geolocation data. Retrieving this from the browser is an async process, so we’ll need to ensure we halt the boot process until it’s complete. Once data has been retrieved, put it in the container under the
data:location key, in such a way that we only have a single copy of the object used across the whole app.
Building with Broccoli
Broccoli is the asset pipeline used by ember-cli, and it has one job: transforming and combining files. While the core broccoli library is great, some of the most important build-related stuff happens inside the many broccoli plugins that are used to transpile, minify, uglify and analyze your source code.
We’ll build our own broccoli plugin, explore some debugging techniques and learn some broccoli best practices.
EXERCISE: Build a Broccoli Plugin
We want to add a copyright notice comment to the top of all built JavaScript files. Do so by way of a broccoli plugin.
Note: you may end up tampering with files after the’ve already been fingerprinted, so you may need to remove
ember-cli-sri from your project.
Lunch
Break for Lunch
A Simple CI/CD Scheme
One of the distinct advantages of working with an opinionated framework is that many people are working with the same set of libraries and tools. Continuous integration and continuous deployment typically take a lot of effort to set up, but in the ember world, it’s incredibly easy! We’ll use Travis-CI and Heroku (coincidentally, two both apps) to automatically test and deploy new code that’s pushed to our project’s GitHub master branch.
EXERCISE: Github + Travis-CI + Heroku = Easy CI/CD
Set up free continuous integration w/ Travis-CI, create a new app on Heroku using the ember-cli build pack, and have Travis automatically deploy in the event that tests pass.
BONUS: setup a heroku pipeline, and enable PR apps, so you can view and play with proposed changes before merging PRs!
Fastboot
Ember’s server side rendering technology is incredibly easy to set up, particularly in comparison to getting something equivalent working in ecosystems that are less opinionated and aligned to a common set of ideas.
Although both browsers and Node.js both run JavaScript, there are a couple of very important differences that we need to be aware of, as we prepare our app for Fastboot.
EXERCISE: Ready, Set, Fastboot!
Install
ember-cli-fastboot, and run
ember fastboot --serve-assets. You’ll find that something we’re doing is making our lightweight and incomplete DOM implementation unhappy. Use our knowledge of Fastboot guards to fix this problem (i.e., skip it if we’re running in fastboot land).
EXERCISE: Server data in Client Land
Grab the user agent of the incoming request to index.html, and make it available in the container under the container key
data:request
Addressable State
Addressable state is essentially anything that’s directly represented in the browser’s URL. Poorly managed addressable state can lead to problems, where the browser’s back button doesn’t do what your user expects.
EXERCISE: Bookmarkable list filters
Add a feature where we can type a name fragment in our project’s search field in order to filter the list of records.
- This should be done in a data down, actions up way
- Reduce the number of API calls made if you can
- Ensure that you don’t break browser history
Wrap Up & Recap
We’ll recap everything we’ve learned today, and set our sights on more topics for tomorrow!
Welcome Back
We’ll remind ourselves of what was covered yesterday so it’s fresh in our minds.
Draft State & WeakMap
When a user spends some effort creating some state (i.e., a comment on a GitHub issue), it’s important to protect them from losing it by way of an accidental swipe, press of the browser’s back button, or a file drop in the browser’s window.
EXERCISE: Draft comments
We want to be able to make comments, and first we want to ensure that we don’t allow users to accidentally discard their draft comments. Additionally, we need to ensure that drafts are always associated with the appropriate record
Persisted State
You’re no doubt familiar with persisted state, and using ember-data to help you manage it. However, when doing anything asynchronous, we have to keep context and life cycles in mind.
EXERCISE: Saving comments
When a user wants to save a comment, it should be persisted to the API. Please implement this feature and meet the following requirements
- Once a save has successfully completed, the appropriate draft state should be cleared
- Your solution must behave as expected in a high-latency environment
UI State
UI State is often pertinent to the presentation layer only, is only relevant “in the moment”, and can in fact be harmful if not discarded and given a clean start if a user leaves and comes back. You may be thinking that component member data is the tool for the job, but it’s more nuanced than you think!
EXERCISE: UI State
We have a little metadata area at the top of each record, and want to allow users to expand and collapse it to their heart’s content! Implement this feature, and meet the following requirements:
- The expand/collapse state should not carry over from one record to another as we navigate around
- If we expand the metadata area on a record, then go somewhere else, and then come back, we should see things as we left them
Lunch
Break for Lunch
Concurrency
Promises are soooo 2016. We’ll do a few things with ember-concurrency, a library that leverages the power of Generator Functions to help us manage asynchronous tasks with grace and poise.
EXERCISE: Better comment saving
We can improve our comment saving experience, by disabling the textarea and save button while the operation is underway.
Animation
A little tasteful animation can make a world of difference, in making your app feel rich and interactive. We’ll look at a few easy to use features in Ember’s official animation library, liquid-fire, whose “big idea” is making animations declarative.
EXERCISE: Animated Comment Count
We have a small comment count indicator in the list of records on the left side of the screen. Use liquid fire to animate this so that it rolls over “odometer style” when comments are added or removed.
Logic in Templates
As you start building a sizable app, it’s easy to become annoyed at all of the repetitive computed properties that usually come along with conditionals, filtering and transforming data, and mutating values. We’ll look at two libraries
- ember-composable-helpers
- ember-truth-helpers
That allow us to express simple logic declaratively in templates.
EXERCISE: Public vs Private Comments
Good news! We have a new feature whereby comments can be made either in “fact” or “opinion” mode .
- Using only a
<select>element, composable helpers, and minimal imperative code in JavaScript files, add a drop down allowing the user to pick between comment types when creating a comment
- Add a filter to the top of the list, allowing us to pick from three modes “fact”, “opinion” or “all”
- In “all” mode, facts should be sorted higher on the list than “opinions”, but they should otherwise be sorted by createdAt within each category.
Authentication & Authorization
Authentication is often the first big thing we end up building into a new app, and the approach ember-simple-auth takes has clearly resonated with the Ember community. By building a small set of single-purpose JavaScript modules, and mixing a few things into a few foundational framework objects, we can have authentication working in no time! We’ll go a step further and explore the concept of roles, whereby users are granted or denied access to certain routes, based on some data associated with their user object.
EXERCISE: Login/Logout
The API we’ve been using supports authentication via OAuth2 Password Grants. Implement “logging in”, and unlock the ability to post non-anonymous comments. Add a “Logout” button to the navbar, which should
- make a
DELETErequest to the same endpoint we use for login, and then
- invalidate the client-side session
Recap & Wrap Up
We’ll recap everything we’ve covered today, and preview tomorrow’s agenda
Welcome & Recap
We’ll recap everything we’ve learned so far, so it’s fresh in our minds.
CRUD Mixins
There are several types of repetitive routes that most apps end up needing for the following purposes
- Creating a new record
- Updating an existing record
- Showing a record
- Showing a list of records
We’ll devise a common abstraction for each of these, and DRY up our code by establishing some conventions within our project.
EXERCISE: CRUD Mixins
Let’s DRY up our routes for showing a list of records, and the route for creating a new record, by building some general purpose mixins.
ES2016, ES2017 & ES2018 in Ember
You’re no doubt aware of new language features coming to the JavaScript world, but since some of us have years of experience writing ES5 code, it’s hard to develop new habits that take advantage of the new stuff.
We’ll look at some ideal places to apply destructured assignment, enhanced object literals, ES6 classes, async/await and more, with a specific focus on how the new ideas mix well with Ember.
EXERCISE: Async/Await
- Rewrite our logout logic using async/await
- Write an acceptance test for visiting a record and comment on it, using async/await
Validation
ember-cp-validations takes an approach to validating ember-data records (or really, any
Ember.Object subclass) that’s built entirely using computed properties. We’ll look at how to apply this library, customize error messages, display them on the screen, and even integrate with ember-data to surface server-side errors in the UI.
EXERCISE: Client-Side Comment Validation
Implement clients-side validation for comments, where anonymous comments must be less than 140 characters, but non-anonymous comments can be up to 255.
Lunch
Break for Lunch
6 — Modular Architecture
One of the unique strengths of the Ember ecosystem is the concept of an Ember Addon.
The big recent advancement in this area over the past year is the concept of engines, a special kind of addon that essentially is an app in and of its self, embedded or mounted in the consuming app.
Tomorrow’s ember apps will take advantage of all of these great capabilities, so we’ll thoroughly study the various building blocks, and cover some important and broadly useful scenarios.Agenda
Addon Basics
Ember addons can exist as their own independently-versioned separate projects, or as in-repo addons that live within a host app’s
/lib folder. There are major benefits to both of these patterns, so once we cover some common addon basics, we’ll outline important differences and practical use cases for each.
Module Namespaces, Resolver Consequences
Typically, when working with addons, you have two top-level folders:
app and
addon, each of which may contain familiar folders like
components,
routes, etc… . We’ll connect back to our newfound knowledge of the container, loader and resolver, to understand important consequences of putting certain types of files in each tree.
EXERCISE: UI Kit
Move our
{{x-input}} and
{{x-textarea}} components into a new in-repo addon called core-ui. Make sure your templates are not in the
/app folder.
EXERCISE: Modifying a host app's asset pipeline
Addons are the go-to way of building up an app’s asset pipeline in a modular way. We’ll look at the different places that we can get access to important Broccoli trees, and cover some important distinctions between being consumed in apps vs other addons vs engines.
Route-less Engines
Engines are a powerful new capability, similar in concept to the idea of Rails engines, for embedding a sub-application into a host app. This is a departure from non-engine addons, in that the engine has its own registry & container, can have its own initializers, services, etc…
Routed Engines
We’ve already embedded a route-less engine into a view, so let’s take things to the next level and mount a routed engine in our router. We’ll need to introduce a few new concepts relating to how engines share information with the host app, and pay special attention to the way we create
{{link-to}} components that cross the host/engine boundary.
Lazy Engines
Beyond encapsulation, one of the biggest benefits that come along with engines is that it frees us from having to pile our entire app into one big set of static assets, to be downloaded as the user first enters. Lazy engines allow chunks of assets to be downloaded on an as-needed basis, as a user crosses an engine boundary.
Although this adds a little extra complexity to our apps, the performance payoff can be huge, particularly if infrequently-used sections of your app are particularly heavy in terms of dependencies and application code.
Wrap Up & Final Recap
We’ll take a step back and recap everything we’ve learned so far, putting in the broader context of being able to build out things quickly, robustly and sustainably with Ember.js. | https://simplabs.com/training/2016-12-19-ember-pro.html | CC-MAIN-2017-47 | refinedweb | 2,523 | 53.65 |
organize your code and separate it by platform:
- Using the
Platformmodule.
- Using platform-specific file extensions.
Certain components may have properties that work on one platform only. All of these props are annotated with
@platform and have a small badge next to them on the website.
Platform modulePlatform module
React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.
import {Platform, StyleSheet} from 'react-native'; const styles = StyleSheet.create({ height: Platform.OS === 'ios' ? 200 : 100, });
Platform.OS will be
ios when running on iOS and
android when running on Android.
There is also a
Platform.select method available, that given an object the iOS version
On iOS, the
Version is a result of
-[UIDevice systemVersion], which is a string with the current version of the operating system. An example of the system version is "10.3". For example, to detect the major version number on iOS:
import {Platform} from 'react-native'; const majorVersionIOS = parseInt(Platform.Version, 10); if (majorVersionIOS <= 9) { console.log('Work around a change in behavior'); }
Platform-specific extensionsPlatform-specific extensions
When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a
.ios. or
.android. extension and load the relevant platform file when required from other components.
For example, say you have the following files in your project:
BigButton.ios.js BigButton.android.js
You can then require the component as follows:
import BigButton from './BigButton';
React Native will automatically pick up the right file based on the running platform.
Native-specific extensions (i.e. sharing code with NodeJS and Web)Native-specific extensions (i.e. sharing code with NodeJS and Web)
You can also use the
.native.js extension when a module needs to be shared between NodeJS/Web and React Native but it has no Android/iOS differences. This is specially useful for projects that. | http://facebook.github.io/react-native/docs/0.24/platform-specific-code | CC-MAIN-2019-09 | refinedweb | 344 | 51.14 |
What you're seeing here is Windows itself, not some random app. It is there
because Microsoft hardcoded a link to this page in a Microsoft product.
To be more precise, you see here Explorer.Exe (which contains the control
panel) showing settings for the desktop background (which is also
Explorer.Exe).
This exception tells you that the MyProject.Resources.Lists.resources file
was not found. Maybe the path to the file or the filename itself is
incorrect. I validated your example by creating a sample app and it works
fine.
You should replace the @"." with
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location to ensure
you are using the right location for your resource file. In the case you
are setting Directory.SetCurrentDirectory("D:\"); anywhere inside your
application, the @"." would look there for your resources.
It is possible to run UiAutomator from an application, you just need to
have your Test jar on the device and give your application su permissions.
From your application you can then just call:
uiautomator runtest Test.jar -c com.package.name.ClassName -e key value
And your device will perform whatever your UiAutomatorTestCase would
perform.
Quick example:
Process rt = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(rt.getOutputStream());
os.writeBytes("uiautomator runtest Testing.jar -c
com.hey.rich.CalculatorDemo" + "
");
os.flush();
os.writeBytes("exit
");
Are you not using an XML layout? It's much more efficient and tidy than
what you have above...
You haven't included any logcat so there isnt much to go on but it seems to
me that the issue is your addTabItem tries to make something arbitrary and
use it as the content when really you want to be using the frameLayout as
the content so try passing that into the method and setting it as the
content?
I replaced the CScrollBar and used HWND instead.
So my code changed like this:
//MainClass.h
HWND m_wndHScrollBar;
//MainClass.cpp
m_wndHScrollBar = (CreateWindowEx(
0, // no extended styles
SCROLLBAR, // scroll bar control class
(PTSTR) NULL, // no window text
WS_CHILD | WS_VISIBLE // window styles
| SBS_HORZ, // horizontal scroll bar style
left, // horizontal position
bottom, // vertical position
right, // width of the scroll bar
height, // height of the scroll bar
m_hWnd,
After two days of searching an answer I found the trick:
the problem is that you need a specific string that recognize the ActiveX
control.
what I did is:
open Word and on the developers ribbon record a macro (this option not
exists in powerpoint) of mouse clicks
add your control (Controls->More Controls->"My control")
stop recording macro.
view the macro's VBA created (click edit macro) you can find a
string like "myControlLib.myControlctrl.1"
this is the string needed by the Shapes.AddOLEObject(...) as class name.
There is no need to use $.when -> $.then as you can use .done() and .fail()
callbacks provided by promise
promise.done(function (result) {
//success callback
window[callbackFunction](result);
}).fail(function(){
//error callback
});
The error appears because GrdLogo instance doesn't know you removed element
named Bd from it's visual tree. You need to notify it by calling
FrameworkElement.UnregisterName:
if (called == true)
{
GrdLogo.Children.Remove((TextBlock)GrdLogo.FindName("Tb"));
GrdLogo.UnregisterName("Tb");
}
EDIT
Since you cannot use that method in your W8 code (there is no namescope
access in WinRT), you should avoid using named elements altogether. Remove
your textblock name in xaml and use other means of removing control like:
GrdLogo.Children.Remove(GrdLogo.Children.OfType<TextBlock>().Single());
The preferred way to work with WPF is called MVVM.
This is my take on what you described:
<Window x:Class="MiscSamples.MVVMDataGrid"
xmlns=""
xmlns:
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False"
CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Button Command="{Binding CancelCommand}"
Conte
You can use the attached properties:
public class Extensions
{
public static readonly DependencyProperty OverWidthProperty =
DependencyProperty.RegisterAttached("OverWidth", typeof(double),
typeof(Extensions), new PropertyMetadata(default(double)));
public static void SetOverWidth(UIElement element, double value)
{
element.SetValue(OverWidthProperty, value);
}
public static double GetOverWidth(UIElement element)
{
return (double)element.GetValue(OverWidthProperty);
}
}
Xaml:
xmlns:extensions="clr-namespace:NAMESPACE FOR Extensions class"
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="MinWidth" Value="{Binding
Path=(extensions:Extensions.OverWidth), RelativeSource={RelativeSource
Self}}"/>
</Trigg
You should use the svn rm --keep-local instead.
If you are on Unix, you can test this:
find . -name .project -exec sh -c 'svn info "{}"' ; -a
-execdir bash -c 'svn -q propset svn:ignore -F <((svn propget
svn:ignore;
echo .project) | sort -u) .' ; -a
-execdir svn delete --keep-local {} ;
search .project file and check if it's versioned.
retrieve properties and add .project in the local directory. sort -u
prevents from duplicates
If you want to ask for confirmation, use --okdir instead
Note: you could commit only at the end since it's the same operation (i.e.
"cleaning properties").
FWIW don't lose hope, svn 1.8 contains inherited Properties
()
Inside your tinymce init method:
setup : function(ed) {
ed.addButton('check', {
type:'checkbox',
text: 'some descriptive label',
});
},
You should be able to do it
theBritishFlag .Controls.Add(theBritishFlagText)
Update
I have tested this and it works. Have you added your hyperlink to page's
control ??
HyperLink abc = new HyperLink();
abc.NavigateUrl = "";
Literal xy = new Literal();
xy.Text = "Click Here";
abc.Controls.Add(xy); //add literal to hyperlink control
Image i = new Image();
i.ImageUrl =
"";
abc.Controls.Add(i); //add image
this.Controls.Add(abc); //add hyperlink to page control
protected int countCalendars;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["countCalendars"] != null)
countCalendars = (int) ViewState["countCalendars"];
// init
if (!IsPostBack)
countCalendars = 0;
// register existing user-controls; won't occur before onclick button
// so ViewState["countCalendar"] will be exist.
for (int i = 0; i < countCalendars; i++)
addCalendar(i);
}
// onclick button
protected void addCalender_Click(object sender, EventArgs e)
{
addCalendar(countCalendars++);
ViewState["countCalendars"] = countCalendars;
}
// Adding a new User-Control
protected void addCalendar(int idNumber)
{
CalculatorUserControl Calendar =
LoadControl("~/CalendarUserControl.ascx") as CalendarUserControl;
If you use HTML button (I guess < input), then you can
only interact with them using javascript.
You should use
window.location = url
And build url to contain your id :
Then you may pass Id using data attributes. For example :
<input type='button' data-
then, in JS, if using jquery :
var btn = ...get-your-button-by-id-or-class-name-or-whatever
var id = btn.data('id');
window.location=''+id;
If your code is exactly as above except with UITableViewCell replaced with
MvxTableViewCell and you haven't done any binding externally to change
this, then there's nothing in MvxTableViewCell that should cause this -
from MvxTableViewCell.cs - it's just a simple layer on top of
UITableViewCell
In my opinion, your best bet is to collect a bit more basic information:
is there an inner exception of that TargetInvocationException? If so, where
is that inner exception thrown?
where is the reflection itself happening here?
If you can work that out, then you might have more chance in debugging and
solving the problem
You need to add your user control to the display surface of the main form
(or another container already present)
MainScreen home = new MainScreen();
home.Show();
EntrySuggestion t_ES = new EntrySuggestion();
home.Controls.Add(t_ES);
Yes, you need to check in the Row_Created event for a row of type Pager,
like this:
private void grdClientServiceType_RowCreated(object sender,
System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Pager)
{
// Create your control here, button is an example create whatever
you want
Button theButton = new Button();
theButton.Text = "Click Me";
// Add new control to the row with the pager via a table cell
e.Row.Cells[0].ColumnSpan -= 1;
TableCell td = new TableCell();
td.Controls.Add(theButton);
e.Row.Cells.Add(td);
}
}
you need
jQuery(document).on("click", ".class1", function() {
jQuery(this).text('Validate').addClass('class2').removeClass("class1");
});
jQuery(document).on("click", ".class2", function() {
jQuery(this).removeClass("class1");
//More stuff here
});
Demo: Fiddle
This is a great article on using NuGet without adding the packages to
source control. The article is for VS 2010, but I am doing the same thing
in VS 2012
Using NuGet without adding packages to source control
But I want to have full control of this outside .exe application as it
has tabs, radio buttons, push buttons, etc.
Is there a way to do so?
Yes, multiple ways, depending on the application.
Since you're already using COM (although I'm not sure why you're using it
just to launch apps)… does the app have a COM automation (IDispatch)
interface? If so, there will probably be documentation showing how to use
it from VB# (or VBScript or C# or …), which you can easily adapt to
Python and win32com. (For an example of such an application, see the
Outlook automation docs.)
If there's no COM automation interface, there may still be a lower-level
COM interface, which is almost as easy to use via win32com, but it usually
won't provide any access to the GUI controls; instead, you'll be t
There are limits and restrictions on how many SMS's can an app send in a
given period of time. It is implemented in SmsUsageMonitor (at least in
Android 4.x).
For example, take a look at SmsUsageMonitor.check(String appName, int
smsWaiting):
public boolean More ...check(String appName, int smsWaiting) {
/* ... */
return isUnderLimit(sentList, smsWaiting);
}
As you can see, there is a list of SMS's send by an app. isUnderLimit()
simply checks if this list is no longer than a limit.
It is not necessary or even possible to add all datetime properties as
parts: only one part of a given type can exist on a type. You could do it
through fields however.
What you need to do in order to reproduce the UI of the date field in your
own part is to reproduce the template and script that they use, in your own
part templates.
Well, since you haven't gotten anything else yet. I'll throw something out
there but my experience is only moderate so far.
In the controller for your cats owners page, you could query if the user
has any associated cat entities.
You need to add OneToMany/ManyToOne annotations to your user and cat class,
and a variable for the associations. This you could review straight out of
the doctrine section of the symfony2 book (If you are working with Symfony2
and haven't taken the time to read the book, that is the minimal level of
knowledge to work with the full stack and I suggest you read it all). (Do
you really need a entity class just for cat, you could have a pet entity
with a "type" option.)
check the security context to ensure logged in, then query db.
$em = $this->getDoctrine(
Why don't you use just one ApplicationBar and add or remove
ApplicationBarButtons based on the selected Pivot control? Should be pretty
straightforward considering that many apps do it.
PS: From personal experience, add your application bar via code in C#...I
have faced issues while changing XAML app bars.
If you want to permanently change settings of an add-in then you would need
to Open this file, not attach it as an add-in to the currently running
instance of Excel. (This isn't usually done programmatically though.)
Perhaps you should clarify because, to me, an add-in is supposed to be
"complete". If any settings need to be changed when the add-in is in use,
then the add-in itself should make these settings available to the
Excel-instance, via exposed properties (or some other technique). But,
again, these settings wouldn't be permanently saved (in the add-in itself)..
I tried this on a form with a GroupBox containing a couple of controls and
it worked as expected (but for production code you should probably add some
null-checks in case nothing is selected, or the app doesn't have focus at
all):
Form activeForm = Form.ActiveForm;
Control activeControl = activeForm.ActiveControl;
while (activeControl.HasChildren)
{
activeControl = activeControl
.Controls
.Cast<Control>()
.FirstOrDefault(c => c.Focused);
}
On the other hand, if you are using a third party docking library (you
mentioned a DockPanel, so I am thinking of Weifen Luo's DockPanel Suite,
for example), then you will have to use their own properties (e.g.
DockPanel.ActiveDocument or DockPanel.ActiveContent) to get the docked
form, but the general idea stays t
What makes you think that your 'performance hit' as you call it, is caused
by the code that you showed us? In my opinion, the majority of time that a
WPF application takes to load data is actually taken up by the rendering
engine.
If you use a Stopwatch to measure the amount of time that it takes for your
for loops to complete, I'm fairly sure that it won't be long at all...
probably not even a quarter of a second for 50,000 objects or more:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
foreach (var item in items)
{
this.Items.Add(item);
}
stopwatch.Stop();
TimeSpan elapsedTime = stopwatch.Elapsed; // I'm guessing this will not be
a long time
As per the comment discussion, to meet the requirements of your question,
your best bet would probably be the NativeWindow solution.
However, I would still recommend that you speak with your colleagues to see
if there's another alternative that might make things easier on your part.
If you create solutions for your customers based on solutions provided by
your colleagues, there is a strong potential that you will have to rewrite
your customized solutions as often as your colleagues deploy their latest
updates...
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace NativeWindowApplication
{
// Summary description for Form1.
[System.Security.
No, it is not possible to show a WPF control in Silverlight. They use two
different runtimes so are not directly substitutable with each other.
You have a few options though:
use XBAP to show WPF within the browser
rewrite your control so that you can compile a version for Silverlight or
WPF (this is (was) quite a common way to do it)
Edit:
in response to your comment you seem to have some misunderstandings, I
think you haven't understood the links I gave you. You may also have
misunderstood what Silverlight is - just in case you have let me mention
that Silverlight runs as a plugin within the web page, it isn't directly
part of the HTML structure.
For the XBAP approach the WPF control/page is hosted inside a web page -
just like a Silverlight control is. However you don't have
If you want to give keyboard inputs to apps that aren't your own, the only
way is to build your own alternative keyboard. After this, the user will
have to select your keyboard as his keyboard of choice so that it shows up
whenever textboxes receive focus. You can even listen for voice inputs and
parse them to do what you need. These links might help:
Keyboard:
How to make a Android custom keyboard?
Create Custom Keyboard in Android
creating custom android keyboard layout
Voice input:
Is there a way to use the SpeechRecognizer API directly for speech input?
If this is a Mac only game you should have access to the Quartz event api.
This is the easiest way to generate mouse events in OS X...
I would recommend simply tracking the palm (hand) position, and moving the
cursor based on that.
This is how I do my palm tracking:
float handX = ([[hand palmPosition] x]);
float handY = (-[[hand palmPosition] y] + 150);
The "+ 150" is the number of millimetres above the Leap device, to use as
the '0' location. From there you can move the cursor based on the hand
offset from 0.
The function I use to move the cursor (using Quartz):
- (void)mouseEventWithType:(CGEventType)type loc:(CGPoint)loc
deltaX:(float)dX deltaY:(float)dY
{
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, type, loc,
kCGMouseButtonLeft);
CGEventSetIntegerValueField(theEvent,
The documentation for the toolkit states specifically that it is for web
forms, not mvc.
If there is a specific piece of functionality you required, then you might
want to see if there is a plugin available for jquery to replicate it. | http://www.w3hello.com/questions/-Adding-a-control-to-a-localized-ASP-NET-2-0-application- | CC-MAIN-2018-17 | refinedweb | 2,690 | 56.25 |
Graph traversal is the process of moving from the root node to all other nodes in the graph. The order of nodes given by a traversal will vary depending upon the algorithm used for the process. As such, graph traversal is done using two main algorithms: Breadth-First Search and Depth-First Search. In this article, we are going to go over the basics of one of the traversals, breadth first search in java, understand BFS algorithm with example and BFS implementation with java code.
What is a Breadth-First Search?
Breadth-First Search (BFS) relies on the traversal of nodes by the addition of the neighbor of every node starting from the root node to the traversal queue. BFS for a graph is similar to a tree, the only difference being graphs might contain cycles. Unlike depth-first search, all of the neighbor nodes at a certain depth are explored before moving on to the next level.
BFS Algorithm
The general process of exploring a graph using breadth-first search includes the following steps:-
- Take the input for the adjacency matrix or adjacency list for the graph.
- Initialize a queue.
- Enqueue the root node (in other words, put the root node into the beginning of the queue).
- Dequeue the head (or first element) of the queue, then enqueue all of its neighboring nodes, starting from left to right. If a node has no neighboring nodes which need to be explored, simply dequeue the head and continue the process. (Note: If a neighbor which is already explored or in the queue appears, don’t enqueue it – simply skip it.)
- Keep repeating this process till the queue is empty.
(In case people are not familiar with enqueue and dequeue operations, enqueue operation adds an element to the end of the queue while dequeue operation deletes the element at the start of the queue.)
Example
Let’s work with a small example to get started. We are using the graph drawn below, starting with 0 as the root node.
Iteration 1: Enqueue(0).
Queue after iteration 1 :
Iteration 2: Dequeue(0), Enqueue(1), Enqueue(3), Enqueue(4).
Queue after iteration 2:
Iteration 3: Dequeue(1), Enqueue(2).
Queue after iteration 3 :
Iteration 4 : Dequeue(3), Enqueue(5). Since 0 is already explored, we are not going to add 1 to the queue again.
Queue after iteration 4:
Iteration 5: Dequeue(4).
Queue after iteration 5:
Iteration 6: Dequeue(2).
Queue after iteration 6 :
Iteration 7: Dequeue(5).
Queue after iteration 7:
Since the queue enqueue nodes if the value of their corresponding element in the array is 0 (or false).
That’s cool, but there’s still another case to consider while you’re traversing all the nodes of a graph using the BFS in java. What happens when the graph being provided as input is a disconnected graph? In other words, what happens when the graph has not one, but multiple components which are not connected? It’s simple. As described above, we will maintain an array for all of the elements in the graph. The idea is to iteratively perform the BFS algorithm for every element of the array which is not set to 1 after the initial run of the BFS algorithm is completed. This is even more relevant in the case of directed graphs because of the addition of the concept of “direction” of traversal.
Applications
Breadth-First Search has a lot of utility in the real world because of the flexibility of the algorithm. These include:-
- Discovery of peer nodes in a peer-to-peer network. Most torrent clients like BitTorrent, uTorrent, qBittorent use this mechanism for discovering something called “seeds” and “peers” in the network.
- Web crawling uses graph traversal techniques for building the index. The process considers the source page as the root node and starts traversing from there to all secondary pages linked with the source page (and this process continues). Breadth-First Search has an innate advantage here because of the reduced depth of the recursion tree.
- GPS navigation systems use Breadth-First Search for finding neighboring locations using the GPS.
- Garbage collection is done with Cheney’s algorithm which utilizes the concept of breadth-first search.
Algorithms for finding minimum spanning tree and shortest path in a graph using Breadth-first search.
Implementing Breadth-First Search in Java
There are multiple ways of dealing with the code. Here, we would primarily be sharing the process for a breadth first search implementation in java. Graphs can be stored either using an adjacency list or an adjacency matrix – either one is fine. In our code, we will be using the adjacency list for representing our graph. It is much easier to work with the adjacency list for implementing the Breadth-First Search algorithm in Java as we just have to move through the list of nodes attached to each node whenever the node is dequeued from the head (or start) of the queue.
The graph used for the demonstration of the code will be the same as the one used for the above example.
The implementation is as follows:-
import java.io.*; import java.util.*; class Graph { private int V; //number of nodes in the graph private LinkedList<Integer> adj[]; //adjacency list private Queue<Integer> queue; //maintaining a queue Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; i++) { adj[i] = new LinkedList<>(); } queue = new LinkedList<Integer>(); } void addEdge(int v,int w) { adj[v].add(w); //adding an edge to the adjacency list (edges are bidirectional in this example) } void BFS(int n) { boolean nodes[] = new boolean[V]; //initialize boolean array for holding the data int a = 0; nodes[n]=true; queue.add(n); //root node is added to the top of the queue while (queue.size() != 0) { n = queue.poll(); //remove the top element of the queue System.out.print(n+" "); //print the top element of the queue for (int i = 0; i < adj[n].size(); i++) //iterate through the linked list and push all neighbors into queue { a = adj[n].get(i); if (!nodes[a]) //only insert nodes into queue if they have not been explored already { nodes[a] = true; queue.add(a); } } } } public static void main(String args[]) { Graph graph = new Graph(6); graph.addEdge(0, 1); graph.addEdge(0, 3); graph.addEdge(0, 4); graph.addEdge(4, 5); graph.addEdge(3, 5); graph.addEdge(1, 2); graph.addEdge(1, 0); graph.addEdge(2, 1); graph.addEdge(4, 1); graph.addEdge(3, 1); graph.addEdge(5, 4); graph.addEdge(5, 3); System.out.println("The Breadth First Traversal of the graph is as follows :"); graph.BFS(0); } }
Output
The Breadth First Traversal of the graph is as follows :
0 1 3 4 2 5
Time & Space Complexity
The running time complexity of the BFS in Java is O(V+E) where V is the number of nodes in the graph, and E is the number of edges.
Since the algorithm requires a queue for storing the nodes that need to be traversed at any point in time, the space complexity is O(V).
Conclusion
Graph traversal algorithms are some of the most important algorithms that one has to master to get into graphs. Breadth first search in java is one of the things one needs to learn before one can proceed to stuff like finding the minimum spanning tree and shortest path between two nodes in a graph. This article on the implementation of the BFS algorithm in java should help bring your concepts up to scratch. You can also check how to implement depth first search in java to complete the concept of graph traversal. | https://favtutor.com/blogs/breadth-first-search-java | CC-MAIN-2022-05 | refinedweb | 1,282 | 64.41 |
On January 15, 2017 12:35:57 PM EST, Andreas Tille <andreas@an3as.eu> wrote: >Hi Scott, > >On Sun, Jan 15, 2017 at 04:34:40PM +0000, Scott Kitterman wrote: >> >I fully agree with your generic name consideration. The software is >> >well known in this work field anyway so I'm hesitating a bit to >rename >> >it. Would you consider this a strong issue that needs to be >discussed >> >with upstream or is it in a "not nice but acceptable" status? >> >> I think it should be discussed with upstream, but we have broader >namespace considerations that they may not understand or care about. > >Definitely. > >> As long as a package search for freebayes returns this in the result >set, I don't think it's critical to have the package name match exactly >the upstream name. > >Do you care only about the *package* name or do you care as well about >the name binary /usr/bin/freebayes? I think they are both important. Scott K >> Not wearing my FTP team hat for this, consider it as a comment from >another DD. > >Both is welcome. > >Kind regards > > Andreas. | https://lists.debian.org/debian-devel/2017/01/msg00453.html | CC-MAIN-2019-26 | refinedweb | 186 | 72.26 |
On Wed 29-08-07 12:31:52, Eric W. Biederman wrote:> Jan Kara <jack@suse.cz> writes:> > >> I suspect the namespace virtualisation guys would be interested in a new> >> interface which is sending current->user->uid up to userspace. uids are> >> per-namespace now. What are the implications? (cc's added)> > > I know there's something going on in this area but I don't know any> > details. If somebody has some advice what should be passed into userspace> > so that user/group can be idenitified, it is welcome.> > For non networking stuff netlink is a pain to use in this area.> > Although if we are very careful we may be ok. But this requires> some thinking through.> > In principle the uid that corresponds to a struct user depends> on which user namespace you are in.> > Now there is a cheap trick we can play. A traditional filesystem> belongs to exactly one user namespace. So we can return the uid> in the filesystems user namespace.> > Wait you are returning current->user->uid? Shouldn't we return> the user who's quota is exceeded? I.e. if alice owns a file> and makes it world writable. And bob writes to the file wouldn't> that file still be billed to alice's quota? So shouldn't we complain> about alice and not bob? Yes, the quota will still be billed to Alice and originally we complainedonly about Alice. Now, we are actually passing identities of two users: Theone who actually caused the quota to be exceeded and the one whose quota isexceeded. Userspace app can then decide what to do with the information...For example it makes sence to display the message to both Alice and Bob inthe case you've described...> Anyway if the goal is to return a user who maps to the filesystem we> can just always return uids in the filesystems uid namespace.> > Although if filesystems start supporting multiple user namespaces> natively we might have a challenge on our hands.> > Let me see if I can think of a concrete example here.> > We have a nfs server with quotas.> We have clients who mount the nfs filesystem without synchronizing> their /etc/password files, so we have separate user namespaces.> > What are the ways to make this work?> - Everyone who has right access to the NFS mount on all> machines must have their uid synchronized across all machines> (the easiest case).> > - Each different kernel has a mapping from it's local uids to> the uids of the nfs filesystem. (ick if we do much more the> root squash).> > - The nfs filesystem knows about the situation and remembers the> uid source (the uid namespace) as well as the uid when storing> owners of files. NFSv4 allows for this by treating users> as user@domain.> > Generally synchronizing uid namespaces (with possibly a root squash> exception) is the sanest and simplest thing to do in a case like this,> but it isn't always what is done.> > As long as we are returning the filesystems idea of users we> shouldn't have to worry much about uid namespaces. However> for non-traditional filesystems that don't store the user> as just a uid, say 9p and NFSv4, this implies that we want> to use the filesystems string identifier. However I don't think> the quota system supports these filesystems yet. So that> isn't an issue just yet. OK, quota kind of works for NFSv4 - we simply enforce quotas on theserver on a traditional filesystem and there are some RPC calls to getquota status. For 9p, it does not work. But we should probably design theinterface generic enough so that it accommodates those untraditionalcases anyway.> touserspace is something (and I don't really care whether it will be number,string or whatever) that userspace can read and e.g. find a terminalwindow or desktop the affected user has open and also translate theidentity to some user-understandable name (average user Joe has tounderstand that he should quickly cleanup his home directory ;). Thinking more about it, we could probably pass a string to userspace inthe format: <namespace type>:<user identification>So for example we can have something like: unix:1000 (traditional unix UIDs) nfs4:joe@machineThe problem is: Are we able to find out in which "namespace type" we areand send enough identifying information from a context of unpriviledgeduser? | http://lkml.org/lkml/2007/8/29/207 | CC-MAIN-2013-20 | refinedweb | 728 | 64.41 |
Tell us what you think of the site.
Hi guys,
I’m starting my big adventure (as i hope) with Python and by the way with writing widgets compatible for Maya & MoBu. I started learning it by following the video made by David Coleman (, big thx for that great vid) and unfortunately I met a painful as hell problem.
I can’t get anything working, that uses outside libraries like from PyQt4 QtCore, QtGui etc…
the error I get from Maya:
# Error: Error in maya.utils._guiExceptHook:
# File "C:\Program Files (x86)\Autodesk\Maya2011\Python\lib\site-packages\maya\utils.py", line 267, in formatGuiException
# exceptionMsg = unicode(exceptionObject.args[0])
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xbf in position 23: ordinal not in range(128)
#
# Original exception was:
# Traceback (most recent call last):
# File "<maya console>", line 2, in <module>
# ImportError: DLL load failed:
I’m working under Windows7 x64, with Maya/Python 2.6.4/PyQt v.4.8.4 (all x86). My system language is PL, the rest is EN (if that makes any useful info).
Last 2 days I spent on searching the solution, browsing the web/forums, but still I can’t go any closer. I will be very great-full for any kind of clue on that issue because I’m stuck and it’s driving me mad!
Sorry for my bad english
Ok, small update incoming, sorry for double posting but can anybody plz answer me something :))
I’ve got the same problems in MotionBuilder, running simple code like
from PyQt4 import QtCore, QtGui
gives me
ImportError: DLL load failed: The specified module could not be found.
and ofc a small headache :/
I’ve uninstalled/cleaned/reainstalled Python/Maya/MoBu/PyQt/Qt etc… same goes to environmental varaibles.
I can import and run scripts involving elements from QtGui in Python IDLE, but can’t in Maya/MoBu. I know I’ve missed something and I’m new in this, so if any expert could give me a hand, I really need got this working.
I’m using Maya/Mobu ( x86) with Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 onboard
PyQt GPL v4.8.4 for Python v2.6 (x86)
Qt by Nokia v4.7.2 (MinGW OpenSource)
and
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 | http://area.autodesk.com/forum/autodesk-maya/python/python---unicodedecodeerror---need-help/ | crawl-003 | refinedweb | 408 | 73.17 |
The Problem
JavaScript Single-Page-Applications tend to consist of a lot of JavaScript files. Several hundreds of JS files are no exception.
When accessing these applications using a web browser, every single JavaScript file has to be fetched using a distinct request. Unfortunately, browsers support only a limited number of parallel connections/requests. Older versions of Internet Explorer were limited to only two concurrent connections. Most modern browsers support six to eight concurrent connections, but this is still not enough to effectively fetch several hundreds of files.
Additionally, JS frontends these days can be several megabytes in size which need to be fetched from the server.
This results in wait times and high server load.
To reduce the wait time and server load, one could cache these files in the browser.
But how long should these files be cached?
And when they are cached and you deploy a new release of your application, users would have to delete their browser cache manually, which is not very practical.
Introducing Perfect Caching
The engineers of Google came up with a simple but effective solution to this problem – an approach called “Perfect Caching”.
It is implemented in Google’s web framework GWT. But even if you are not using GWT, the approach can be easily adopted for any JavaScript application.
This is how it works:
- Combine all JavaScript files into one big JavaScript file.
- Name the combined JS file using the pattern
<hashcode>.cache.js
- calculate the hash of the contents of this file
- use a common hashing algorithm like MD5 or SHA1
- Instruct the browser to cache files matching the pattern
*.cache.*
as long as possible.
- You can do this via Apache by adding an entry to the
.htaccessfile.
- If your app is a Java application you can alternatively use a simple servlet filter.
- Instruct the browser to never cache files matching the pattern
*.nocache.*.
- call the resource that includes your JavaScript file (your host page) accordingly, e.g.
index.nocache.html
Whenever a JavaScript source file is changed, the file name of the combined JavaScript file will change, so the browser is forced to fetch the new file. It is essential to prevent caching of the host page, as this page contains the
URL to the combined JavaScript file.
The result of this approach is as follows:
- When you access the application for the first time, all your JavaScript code is fetched once with a single request.
- Subsequent access to the application leads to no additional requests. As the JavaScript is cached by the browser, the browser doesn’t even
have to ask the server if the file has been changed since last access.
- When a new release is deployed, the browser will fetch the new JavaScript code. Once. Again, subsequent access doesn’t lead to requests to
the server.
Integration into Java Apps Using Servlet Filter
As said before, one possibility to instruct the browser to cache files matching the pattern
*.cache.* and never cache file matching
*.nocache.* is to use a servlet filter. E.g., such a servlet filter could look like this:
public class ResourceCachingServletFilter implements Filter { public void destroy() {} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; if (httpReq.getRequestURI().contains(".nocache.")) { httpResp.setHeader("Cache-Control", "no-cache"); } else if (httpReq.getRequestURI().contains(".cache.")) { httpResp.setHeader("Cache-Control", "max-age=2592000"); } chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException {} }
Integration into a Gradle Build
If you are using Gradle as your build tool, you can use the following two plugins in combination to implement perfect caching:
- Gradle JavaScript Plugin – this plugins allows to combine JavaScript files into a single file, either by simply concatenating the files or by using the RequireJS Optimizer. If you are using RequireJS you just have to point the plugin to your root module and it will traverse the dependency tree and concatenate all the files in the correct order.
- Resource-Caching Gradle Plugin – This plugin will generate the filename of the combined JavaScript file using the files hash. Additionally, it can inject the required script tag into your host page.
Here you can see a sample build.gradle file which uses these two plugins in combination to build a Java WAR file that uses Perfect Caching.
Pingback: TCP and HTTP for web developers | https://blog.oio.de/2014/10/01/javascript-caching-adopting-perfect-caching-for-js-apps/ | CC-MAIN-2020-24 | refinedweb | 727 | 63.19 |
The problem is that my train data could not be placed into RAM due to train data size. So I need a method which first builds one tree on whole train data set, calculate residuals build another tree and so on (like gradient boosted tree do). Obviously if I call
model = xgb.train(param, batch_dtrain, 2)
Disclaimer: I'm new to xgboost as well, but I think I figured this out.
Try saving your model after you train on the first batch. Then, on successive runs, provide the xgb.train method with the filepath of the saved model.
Here's a small experiment that I ran to convince myself that it works:
First, split the boston dataset into training and testing sets. Then split the training set into halves. Fit a model with the first half and get a score that will serve as a benchmark. Then fit two models with the second half; one model will have the additional parameter xgb_model. If passing in the extra parameter didn't make a difference, then we would expect their scores to be similar.. But, fortunately, the new model seems to perform much better than the first.
import xgboost as xgb from sklearn.cross_validation import train_test_split as ttsplit from sklearn.datasets import load_boston from sklearn.metrics import mean_squared_error as mse X = load_boston()['data'] y = load_boston()['target'] # split data into training and testing sets # then split training set in half X_train, X_test, y_train, y_test = ttsplit(X, y, test_size=0.1, random_state=0) X_train_1, X_train_2, y_train_1, y_train_2 = ttsplit(X_train, y_train, test_size=0.5, random_state=0) xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1) xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2) xg_test = xgb.DMatrix(X_test, label=y_test) params = {'objective': 'reg:linear', 'verbose': False} model_1 = xgb.train(params, xg_train_1, 30) model_1.save_model('model_1.model') # ================= train two versions of the model =====================# model_2_v1 = xgb.train(params, xg_train_2, 30) model_2_v2 = xgb.train(params, xg_train_2, 30, xgb_model='model_1.model') print(mse(model_1.predict(xg_test), y_test)) # benchmark print(mse(model_2_v1.predict(xg_test), y_test)) # "before" print(mse(model_2_v2.predict(xg_test), y_test)) # "after" # 23.0475232194 # 39.6776876084 # 27.2053239482
Let me know if anything is unclear!
reference: | https://codedump.io/share/54Rfp0sPrToM/1/how-can-i-implement-incremental-training-for-xgboost | CC-MAIN-2016-50 | refinedweb | 351 | 52.97 |
See Branko's reaction for why the atomic handling will be necessary when you
don't want to hardcode hardware assumptions. Bugs in these assumptions are
exactly the problem we try to solve here.
This implementation idea is copied from how Microsoft implemented some of
their thunking in a completely thread safe way, with the least amount of
overhead possible after the first call. You don't even need function
inlining this way for an optimal call.
And to your third point: The function pointer itself is the inline function
with this implementation.
Your suggestion is like:
// A already defined as variable
static APR_INLINE int A()
{
return A();
}
Luckily you just get a compiler error for the duplicated symbol, otherwise
it would just implement endless recursion instead of an actual function
call.
Bert
From: daniel.lescohier@cbsinteractive.com
[mailto:daniel.lescohier@cbsinteractive.com] On Behalf Of Daniel Lescohier
Sent: zaterdag 7 december 2013 16:05
To: Bert Huijben
Cc: William A. Rowe Jr.; Stefan Fuhrmann; APR Developer List; Stefan
Fuhrman; Philip Martin; Subversion Development
Subject: Re: Race condition in APR_DECLARE_LATE_DLL_FUNC() implementation
I don't think the static function pointer should be declared volatile. That
would mean that for the normal use of the function pointer in the main part
of the program, compiler optimizations of memory address load reordering
would be disabled. It's only operations that require strict memory ordering
that should declare it volatile. That is why all the apr_atomic functions
"cast" values through a volatile pointer.
Second: why use apr_atomic_casptr? Writing a pointer to a memory address is
already atomic: another thread cannot see a halfway-changed pointer. What
the apr_atomic_casptr would prevent would it from being written twice with
the new address value. But why do we need to prevent that? I think it's
all right to have a race to write the new function pointer; it's all right
if it's written multiple times, since they are all writing the same value.
Third: missing is the declaration of apr_winapi_##fn, referenced later in
the file, which should be:
static APR_INLINE rettype apr_winapi_##fn args \
{ return apr_winapi_##fn names; } /* call the function pointer */
On Sat, Dec 7, 2013 at 5:51 AM, Bert Huijben <bert@qqmail.nl
<mailto:bert@qqmail.nl> > wrote:
> -----Original Message-----
> From: Bert Huijben [mailto:bert@qqmail.nl <mailto:bert@qqmail.nl> ]
> Sent: vrijdag 6 december 2013 19:14
> To: 'William A. Rowe Jr.'; 'Stefan Fuhrmann'
> Cc: 'APR Developer List'; 'Stefan Fuhrman'; 'Philip Martin'; 'Subversion
> Development'
> Subject: RE: Race condition in APR_DECLARE_LATE_DLL_FUNC()
> implementation
>
>
>
> > -----Original Message-----
> > From: William A. Rowe Jr. [mailto:wrowe@rowe-clan.net
<mailto:wrowe@rowe-clan.net> ]
> > Sent: vrijdag 6 december 2013 18:24
> > To: Stefan Fuhrmann
> > Cc: Bert Huijben; APR Developer List; Stefan Fuhrman; Philip Martin;
> > Subversion Development
> > Subject: Re: Race condition in APR_DECLARE_LATE_DLL_FUNC()
> > implementation
> >
> > On Fri, 6 Dec 2013 16:44:52 +0100
> > Stefan Fuhrmann <stefan.fuhrmann@wandisco.com
<mailto:stefan.fuhrmann@wandisco.com> > wrote:
> >
> > > On Fri, Dec 6, 2013 at 6:05 AM, William A. Rowe Jr.
> > > <wrowe@rowe-clan.net <mailto:wrowe@rowe-clan.net> >wrote:
> > >
> > > > On Thu, 5 Dec 2013 15:01:05 +0100
> > > > "Bert Huijben" <bert@qqmail.nl <mailto:bert@qqmail.nl> > wrote:
> > > >
> > > > > I think the dll load function should be converted to a more stable
> > > > > pattern, that properly handles multiple threads. And perhaps we
> > > > > should just assume a few more NT functions to be alsways there
> > > > > instead of loading them dynamically.
> > > >
> > > > This is possible with the 'mandatory' call to apr_init, but I think
> > > > the existing pattern should persist for those who don't like to
> > > > call the initialization logic.
> > > >
> > >
> > > We currently call apr_initialize() before spawning threads or doing
> > > anything other APR. What else do we need to become thread-safe
> > > under Windows?
> >
> > Working on a patch. Simply, we just need an _initialize hack that
> > triggers this lookup for each internally required (or not-present) fn.
>
> It is also possible to rewrite the functions to do an atomic replace of
the
> function pointer, which makes them safe for multithreaded usage. (Same
> pattern as we use in Subversion for atomic initializations or even simpler
> variants as it is safe to do the same LoadLibraryXX() and GetProcAddress()
> in multiple threads at once, via the Windows loader lock.)
>
> But as far as I can see all the functions are always available on Windows
XP
> and later (and the others are not even used by APR and APR-Util), so I'm
not
> really sure if we should really spend more time on this.
A patch like the following would make the code thread safe.
[[
Index: include/arch/win32/apr_arch_misc.h
===================================================================
--- include/arch/win32/apr_arch_misc.h (revision 1547134)
+++ include/arch/win32/apr_arch_misc.h (working copy)
@@ -18,6 +18,7 @@
#define MISC_H
#include "apr.h"
+#include "apr_atomic.h"
#include "apr_portable.h"
#include "apr_private.h"
#include "apr_general.h"
@@ -188,22 +189,23 @@
* ERROR_INVALID_FUNCTION if the function cannot be loaded
*/
#define APR_DECLARE_LATE_DLL_FUNC(lib, rettype, calltype, fn, ord, args,
names) \
- typedef rettype (calltype *apr_winapi_fpt_##fn) args; \
- static apr_winapi_fpt_##fn apr_winapi_pfn_##fn = NULL; \
- static int apr_winapi_chk_##fn = 0; \
- static APR_INLINE int apr_winapi_ld_##fn(void) \
- { if (apr_winapi_pfn_##fn) return 1; \
- if (apr_winapi_chk_##fn ++) return 0; \
- if (!apr_winapi_pfn_##fn) \
- apr_winapi_pfn_##fn = (apr_winapi_fpt_##fn) \
- apr_load_dll_func(lib, #fn, ord); \
- if (apr_winapi_pfn_##fn) return 1; else return 0; }; \
- static APR_INLINE rettype apr_winapi_##fn args \
- { if (apr_winapi_ld_##fn()) \
- return (*(apr_winapi_pfn_##fn)) names; \
- else { SetLastError(ERROR_INVALID_FUNCTION); return 0;} }; \
+ typedef rettype (calltype *apr_winapi_fpt_##fn) args;
\
+ static rettype calltype apr_winapi_ld_##fn args;
\
+ static volatile apr_winapi_fpt_##fn apr_winapi_##fn =
apr_winapi_ld_##fn; \
+ static rettype calltype apr_winapi_unavail_##fn args
\
+ { SetLastError(ERROR_INVALID_FUNCTION); return 0; }
\
+ static rettype calltype apr_winapi_ld_##fn args
\
+ {
\
+ apr_winapi_fpt_##fn dl_func = (apr_winapi_fpt_##fn)
\
+ apr_load_dll_func(lib, #fn, ord);
\
+ if (! dl_func)
\
+ dl_func = apr_winapi_unavail_##fn;
\
+ apr_atomic_casptr((volatile void**)&apr_winapi_##fn, dl_func,
\
+ apr_winapi_ld_##fn);
\
+ return apr_winapi_##fn names;
\
+ }
-#define APR_HAVE_LATE_DLL_FUNC(fn) apr_winapi_ld_##fn()
+/*#define APR_HAVE_LATE_DLL_FUNC(fn) apr_winapi_ld_##fn() */
/* Provide late bound declarations of every API function missing from
* one or more supported releases of the Win32 API
]]
It is not a complete solution as it breaks APR_HAVE_LATE_DLL_FUNC().
The only caller of this macro uses it to check for the existence of
WsaPoll(). This should just be checked with the Windows version/feature
level like how we check all others functions in APR, or better yet the usage
of WsaPoll should just be removed for the know issues this function has.
See for a summary
of the problems and Microsoft's explanation that they are not going to fix
this 'for compatibility reasons'.
In all our uses in Subversion and Serf we have explicit code to *not* use
WsaPoll via apr for these reasons.
If we use it the network IO will just get stuck on network problems.
>
> Bert | http://mail-archives.apache.org/mod_mbox/apr-dev/201312.mbox/%3C09f701cef669$1f6c18e0$5e444aa0$@qqmail.nl%3E | CC-MAIN-2014-41 | refinedweb | 1,102 | 51.38 |
In this post, we will go through the Lightning Web Component (LWC) Bundle and all the different files that we can have. There are different types of files that we can create as part of the Lightning Web Components (LWC) Bundle to write a particular type of code to meet the business requirements.
Lightning Web Components (LWC) Bundle
To create a Lightning Web Component, we first need to create a Folder that bundles our component’s files. The folder and its files must have the same name, including capitalization and underscores.)
Bofore going into the details, have a look at the below image to get the basic idea of the Lightning Web Component (LWC) Bundle.
HTML File
Every Lightning Web Component that should have a UI must have an HTML file. The root tag for the HTML file is <template>. It should follow the naming convention as a <myComponent>.html such as helloCmp.html. Below is the sample code for an HTML file that displays Text Box to get the Name and greets with the Name.
helloCmp.html
<template> <lightning-card <div class="slds-p-around_medium lgc-bg"> <lightning-input type="text" label="Contact Name" placeholder="Enter contact name..." value={strContactName} onchange={changeName}></lightning-input> <br/> <p>Hello {strContactName}</p> </div> </lightning-card> </template>
JavaScript File
Every component must have a JavaScript file. JavaScript files define the HTML element if the component renders UI. It should follow the naming convention as a <myComponent>.js such as helloCmp.js. JavaScript files in Lightning web components are ES6 modules.
Every UI component must include a JavaScript file with at least below code.
import { LightningElement } from 'lwc'; export default class HelloCmp extends LightningElement { }
Below is the sample code for HelloCmp JavaScript file:
helloCmp.js
import { LightningElement } from 'lwc'; export default class HelloCmp extends LightningElement { strContactName = ''; changeName(event){ this.strContactName = event.target.value; } }
Configuration File
Every component must have a configuration file. This is used to define the metadata values for the component, including the design configuration for Lightning App Builder, Experience Builder, Utility Bar, etc.
It should follow the naming convention as a <myComponent>.js-meta.xml such as helloCmp.js-meta.xml.
Below is the sample code for HelloCmp Configuration file:
helloCmp.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns=""> <apiVersion>50.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> </targets> </LightningComponentBundle>
Here, isExposed is set to true to make the Lightning Web Component visible to Lightning App Builder and Experience Builder. We added the target as lightning__AppPage to make this component available for the Application Page.
CSS File
Any Lightning Web Component can include a CSS file. Use standard CSS syntax to style the Lightning Web Components.
It should follow the naming convention as a <myComponent>.css such as helloCmp.css. Below is the sample CSS file:
helloCmp.css
p{ color: green; font-size: 20px; }
SVG File
We can include the SVG resource in the Lightning Web Component (LWC) Bundle to use as a custom icon for our component in Lightning App Builder and Experience Builder.
To add the custom icon for the component, create a file with the name <component>.svg such as helloCmp.svg and add the SVG markup for the icon. We can only have one SVG per folder.
Here is the sample SVG file:
<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ""> <svg xmlns="" width="40" height="40"> <circle cx="20" cy="20" r="8" stroke="black" stroke- </svg>
Also Read: Use SVG in LWC (Lightning Web Component)
__tests__ Folder
We can create a folder called __tests__ for each Lightning Web Component (LWC) Bundle to create Jest tests. Jest runs the JavaScript files in the __tests__ folder. Test files must have the name that ends in .test.js. We can have multiple files or a single file to test multiple scenarios. All files should be inside the __tests__ folder. We can also create Sub Folders inside __tests__ and keep the test files inside these SubFolders.
Additional JavaScript Files for Sharing Code
In addition to the JavaScript file that created the HTML element, we can have more JavaScript files inside the Lightning Web Component Bundle to share common code.
This is how our output looks:
If you don’t want to miss new posts, please Subscribe here.
Check official Salesforce documentation for Lightning Web Component (LWC) Bundle, if you want to know more about it.
Thank You! | https://niksdeveloper.com/salesforce/lightning-web-components-lwc-bundle/ | CC-MAIN-2022-27 | refinedweb | 739 | 57.27 |
I wrote this script about 2 years ago, to set a long definition query on a layer from data contained in a spreadsheet. I can’t remember why I couldn’t join the data to the spreadsheet, but I’m in the process of adding all my scripts to GitHub, so even if I can no longer recall the reason for the script, the logic of it should still be able to help someone.
A few things to note – Line 12:
import arcpy.mapping as MAP
I went through a phase where most of my scripts involved data driven pages, and I was getting tired of typing out the full reference. However, I have since returned to the more verbose way of typing it because my laziness should not violate Python’s philosophy of readability and there are so many ways to import that it doesn’t matter in these tiny scripts.
lyr.definitionQuery = ' OR '.join(lst_qry)
I used join to create a bulky SQL query. This is terrible, but it gets the job done, and it helped me evolve my understanding of the peculiarities of using SQL in ArcGIS.
One thought on “Build a definition query from an existing spreadsheet”
Reblogged this on SutoCom Solutions. | https://cindygeodev.wordpress.com/2015/04/08/build-a-definition-query-from-an-existing-spreadsheet/ | CC-MAIN-2017-39 | refinedweb | 206 | 63.22 |
error.JPGerror.JPG
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CDManagementSoftware { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void salesEntriesToolStripMenuItem_Click(object sender, EventArgs e) { } private void salesEntriesToolStripMenuItem1_Click(object sender, EventArgs e) { FormSalesEntry fse = new FormSalesEntry(); fse.TopLevel = false; WorkingPanel.Controls.Add(fse); fse.Visible = true; } private void dealerEntriesToolStripMenuItem1_Click(object sender, EventArgs e) { Form_DealerInfo fdi = new Form_DealerInfo(); fdi.TopLevel = false; WorkingPanel.Controls.Add(fdi); fdi.Visible = true; } } }
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
From novice to tech pro — start learning today.
As I said before, you can simply prevent the opening of another form if there is already one open in the panel:
private void salesEntriesToolStripMenuI
{
if (WorkingPanel.Controls.Cou
{
FormSalesEntry fse = new FormSalesEntry();
fse.TopLevel = false;
WorkingPanel.Controls.Add(
fse.Visible = true;
}
}
you could do something like this
FormSalesEntry fse = new FormSalesEntry();
fse.TopLevel = false;
WorkingPanel.Controls.Add(
fse.ShowDialog(this);
You could either:
(1) Check the WorkingPanel to see if it already has a form loaded:
if (!WorkingPanel.Controls.Co
{
// load the new form up, the above check may need to be more complex depending on what is in WorkingPanel
}
(2) Disable the menu option until the form is closed by subscribing to the FormClosed() event and re-enabling when the menu when it fires.
This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.
Thanks for your suggestion but sir it not working sir.
I tried.
It is showing error.
Thanking you
error.JPG
I hope you can remember me.Sir it is your code only sir as you had suggested me that I am using in the total project.
I am extremely elated to see the result.
But I am facing a problem as I depicted in this question .
As you can see there are
Sales entries ,dealer entries,inventory,customer
Sir it is nice to see you only again .
I did not know how to contact to you.
Sir I can not disable the menu option as otherwise the customer will not be able to understand them..The end user might think those are options for me or I am unable to use them..
Sir your 1st option I tried but it is becoming too heavy for me to control the code.
Can you suggest a simple option.sir.
Thanking you Idle_Mind for answer ,
Anindya Chatterjee
Bangalore
India
I am sorry for not responding in time as I was not in good health.
Thanking you
Anindya Chatterjee
Bangalore
India | https://www.experts-exchange.com/questions/25911831/How-to-stop-two-forms-to-open-simultaneously.html | CC-MAIN-2018-22 | refinedweb | 467 | 52.26 |
Exposed AudioMixer Parameters
Checked with version: 5
-
Difficulty: Beginner
In Unity it's possible to control the parameters of an AudioMixer directly by exposing them to script control. Parameters that have been exposed to script control can be set using the SetFloat function.
Exposed AudioMixer Parameters
Beginner Audio
Transcripts
- 00:00 - 00:03
In Unity it's possible to directly control
- 00:03 - 00:06
parameters of an audio mixer
- 00:06 - 00:08
like levels and effects settings
- 00:08 - 00:11
via script at runtime.
- 00:11 - 00:15
To set a single mixer parameter via script
- 00:15 - 00:18
we'll use the SetFloat function.
- 00:18 - 00:20
SetFloat has two parameters,
- 00:20 - 00:23
a string for the name of the exposed
- 00:23 - 00:24
parameter we're going to be setting
- 00:24 - 00:28
and a float for the value to set it to.
- 00:28 - 00:32
SetFloat is called from an audio mixer.
- 00:32 - 00:34
In order for a parameter to be controlled
- 00:34 - 00:40
using SetFloat it has to be exposed to script control.
- 00:40 - 00:44
First make sure that the parameter is visible in the inspector.
- 00:45 - 00:50
Then in the inspector right click on the parameter name.
- 00:50 - 00:53
Here we'll expose volume for the master group of master mixer.
- 00:55 - 00:59
Right click and choose Expose To Script.
- 01:01 - 01:04
When this is done you'll see a little arrow appear beside the name.
- 01:04 - 01:08
You'll also notice that it's been added
- 01:08 - 01:10
to our list of exposed parameters
- 01:10 - 01:14
for the master mixer audio mixer asset.
- 01:14 - 01:17
If we click on the list of exposed parameters
- 01:17 - 01:20
we'll see two parameters that have already been exposed,
- 01:20 - 01:23
Music Vol and SFX Vol which correspond to the volumes of
- 01:23 - 01:25
the music group and the sound effects group
- 01:25 - 01:27
of master mixer.
- 01:27 - 01:30
And we have a third called My Exposed Param.
- 01:30 - 01:32
My exposed param is our new parameter
- 01:32 - 01:35
and we can see that it's the master volume.
- 01:36 - 01:39
If we double click on it we can set it's name.
- 01:39 - 01:41
The name that we choose is the
- 01:41 - 01:43
string that we'll parse to SetFloat
- 01:43 - 01:46
when setting the value via script.
- 01:46 - 01:49
Here's one example of how we can use SetFloat,
- 01:49 - 01:52
in this case to control the music volume
- 01:52 - 01:56
and sound effects volume balance in our game.
- 01:56 - 01:59
Here we have the Nightmares project which is available
- 01:59 - 02:01
as a free download from the assets store.
- 02:02 - 02:05
And we've added a simple pause menu with some
- 02:05 - 02:07
audio options to it. Let's check it out.
- 02:13 - 02:16
When we hit escape our pause menu comes up
- 02:16 - 02:18
and here we can adjust the music volume,
- 02:20 - 02:22
and the sound effects volume.
- 02:23 - 02:26
Notice how the new values are reflected in the mixer.
- 02:34 - 02:37
Now that we've seen how to expose parameters to script control
- 02:37 - 02:39
let's look at setting their values via script.
- 02:41 - 02:44
On our game object audio mixer control
- 02:44 - 02:47
we have a script called Mix Levels.
- 02:47 - 02:49
In our mix levels script we have
- 02:49 - 02:51
the namespace declaration using
- 02:51 - 02:53
UnityEngine.Audio
- 02:53 - 02:55
And what this allows us to do is to access
- 02:55 - 02:58
classes like audio mixer, which are members
- 02:58 - 03:00
of UnityEngine.Audio.
- 03:00 - 03:02
We also have a public variable
- 03:02 - 03:06
of the audio mixer type called masterMixer.
- 03:06 - 03:09
We have two public functions, SetSfxLvl,
- 03:09 - 03:13
which takes a parameter of the type float called SfxLvl.
- 03:14 - 03:18
And then in that function we're going to called the SetFloat function
- 03:18 - 03:21
from master mixer and we're going to parse in our string
- 03:21 - 03:25
SfxVol saying that's the parameter we want to address
- 03:25 - 03:27
and we're going to parse in our floating
- 03:27 - 03:31
point value SfxLvl, which is what the value is going to be set to.
- 03:31 - 03:33
In our public function SetMusicLvl
- 03:33 - 03:35
we're going to do the same thing, we're going to parse in
- 03:35 - 03:39
our float musicLvl and we're going to use that to call
- 03:39 - 03:42
SetFloat for masterMixer and parse in the string
- 03:42 - 03:45
musicVol saying we want to address the musicVol exposed parameter
- 03:45 - 03:47
and set the value
- 03:47 - 03:49
using our float music Lvl.
- 03:49 - 03:52
In the Unity editor we've dragged
- 03:52 - 03:55
our master mixer audio mixer
- 03:55 - 03:57
to our master mixer variable slot.
- 03:58 - 04:02
In order to set the floating point values in mix levels
- 04:02 - 04:04
we're using the UI system.
- 04:05 - 04:08
Here in our menu canvas we've got two sliders,
- 04:08 - 04:10
here's our effects slider.
- 04:10 - 04:13
In the slider script of our effects slider
- 04:13 - 04:17
we're choosing our audio mixer control
- 04:17 - 04:19
from our list of objects in the scene
- 04:19 - 04:22
with the audio mixer control game object selected
- 04:22 - 04:25
we're going to address our mix level script
- 04:25 - 04:28
and set SFX level within that
- 04:28 - 04:33
to parse the value of the slider to SetFloat.
- 04:33 - 04:35
For our music slider we've gone through the same
- 04:35 - 04:38
process but in this case setting it to
- 04:38 - 04:41
the float of SetMusicLvl.
- 04:41 - 04:45
When working with exposed parameters it's important to note
- 04:45 - 04:48
that exposing a parameter and setting it's value
- 04:48 - 04:51
using SetFloat removes it from control
- 04:51 - 04:54
of the audio mixer snapshot system.
- 04:55 - 04:58
The audio mixer snapshot system allows us to recall the
- 04:58 - 05:01
entire state of the mixer by toggling between
- 05:01 - 05:03
one snapshot and another.
- 05:03 - 05:07
It's possible to return a parameter to snapshot control
- 05:07 - 05:09
using the ClearFloat function.
- 05:09 - 05:13
ClearFloat is called from an audio mixer
- 05:13 - 05:16
and takes a parameter of the type string,
- 05:16 - 05:19
which specifies the parameter that we want to release
- 05:19 - 05:22
from snapshot control on that mixer.
- 05:22 - 05:24
For more information about snapshots and
- 05:24 - 05:26
controlling them via script
- 05:26 - 05:28
please see the information linked below.
Related tutorials
- Audio Mixer and Audio Mixer Groups (Lesson)
- Audio Effects (Lesson)
- Send and Receive Audio Effects (Lesson)
- Duck Volume Audio Effect (Lesson)
- Audio Mixer Snapshots (Lesson)
Related documentation
- Pre-Order Unity 5 Blog post (Blog) | https://unity3d.com/learn/tutorials/topics/audio/exposed-audiomixer-parameters?playlist=17096 | CC-MAIN-2018-09 | refinedweb | 1,309 | 63.22 |
Google Analytics is a service provided by Google that makes it easy to track what users do. In this tutorial, learn how to track Android application events like screen loads and button clicks in order to determine what your application's users are doing—and what they're not!
The Google Analytics SDK for Android provides helpful classes and methods to track user activity and generate useful statistics about your Android app activities. Here is a typical custom dashboard for some application behavior.
, that you have properly installed the Google Analytics SDK for Android, as described in "Android App Publication: Enabling Google Analytics to Gather App Statistics", and that you have signed up for a Google Analytics account.
Note: This tutorial is based upon the latest version of the Google Analytics for Android SDK Release 2 (in the Android SDK Manager), with Version 1.4.2 listed in the ReadMe.txt file and on the website download link.
Step 2: Starting a Tracking Session
In order to collect statistics, your application must be running a tracking session. All tracking must occur during this session. Typically, you'll start your tracker somewhere like your Activity class onCreate() or onResume() .
To start a tracking session, you'll need to import the tracker:
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
Get an instance of the tracker:
GoogleAnalyticsTracker tracker = GoogleAnalyticsTracker.getInstance();
Start the tracker with a valid Google Analytics user account token. Here we configure the tracker to send data to the Google Analytics servers every 30 seconds:
tracker.startNewSession("UA-12345678-9", 30, this);
Step 3: Tracking Application Activity – An Overview
Once you have a tracking session up and running, tracking events is relatively straightforward. Here are some tips for good tracking:
- Understand that tracking is only effective if you put the statistics collection hooks in the right places in your app. This usually means understanding the callbacks associated with the user events in your application and dropping the even tracking code in at the precise moment intended. For example, you typically wouldn't want to track Button hover events, but you might want to track clicks.
- Once you have identified the right place for the hook, make sure you send the right (unique) data to the Google Analytics servers. All tracking methods have developer-defined parameters, mostly Strings, which can be used to provide details about the event being tracked. You will want to play around with the details you send to the server and what sort of reports you can generate with that data. There's no one right answer here.
- Tracking is like logging—it will affect performance, so use it wisely. Collect events and send them to the server in batches. If possible, trigger the upload during a time when your application is awake and using the network anyway.
- If you use Google Analytics tracking in your published applications you MUST inform the user that you are collecting their data. Collect only the information you need. Consider statistics collection like an anonymous survey – generic data that cannot be tied back to a specific user.
Step 4: Tracking Activity or Screen Hits
During a valid tracking session, you can track screen views by supplying the name of the Activity or screen using the trackPageView() method:
tracker.trackPageView("/Splash-Screen");
This method takes a simple developer-defined String value and logs the "view" to the Google Analytics server. You'll want to ensure that you define unique names for each item you want to track using this method. We recommend defining all Strings used by this method as constants in a single location, so that it is also straightforward to determine what screens or Activities are not receiving hits, as this information is just as valuable as those screens that receive a lot of traffic.
Step 5: Tracking User Events
During a valid tracking session, you can track user events of any type using the trackEvent() method:
tracker.trackEvent("Clicks", "Button", "Easy", 0); tracker.trackEvent("Completions", "Game-Deaths", "Hard-Level-One", 15); tracker.trackEvent("Die", "Easy", " Two", someNum);
Again, this method takes a flexible set of developer-defined parameters, all of which can be used to create interesting drill-down reports on the Google Analytics dashboard. How you organize your statistics is up to you, but the parameters are basically in hierarchical order.
The trackEvent() method takes four parameters:
- A category (required) – this String defines the event category. You might define event categories based on the class of user actions, like clicks or gestures or voice commands, or you might define them based upon the features available in your application (play, pause, fast forward, etc.).
- An action (required) – this String defines the specific event action within the category specified. In the example, we are basically saying that the category of the event is user clicks, and the action is a button click.
- A label (optional)– this String defines a label associated with the event. For example, if you have multiple Button controls on a screen, you might use the label to specify the specific View control identifier that was clicked.
- A value (optional) – this integer defines a numeric value associated with the event. For example, if you were tracking "Buy" button clicks, you might log the number of items being purchased, or their total cost.
While these are what the reports call the values, you really can map them however you'd like. It's best to be consistent within a particular application. For example, the second two log events shown above are equivalent, but organized differently. We logged a bunch of the last one; see the figure below.
This report is a good example of how the value field shows up in the report. It's both accumulated into a total across all events as well as averaged. You have to decide for yourself if you want or need the value to be meaningful for each view of categories, actions, and labels. The screenshot shown demonstrates that the value we used may only be meaningful when view labels. This value could represent time to completion. It could represent score. It could represent a count of something. It's yours to define. But, define it well up front or, if you change it, change the tracking code and move to new reports. You can't fix up old data.
Step 6: Ending a Tracking Session
Typically, you'll terminate the session in your Actvitiy's onPause() or onDestroy() methods, like this:
tracker. stopSession();
Conclusion
The Google Analytics SDK for Android is an easy way to help determine how your users are using your Android applications. There are several different event tracking methods which can be used to determine what parts of the application are being used, as well as what features of the application your users use routinely or rarely. The data being sent to the Google servers should be generic enough to protect users' privacy but specific enough to generate useful reports for the developer. This is a balancing act that usually requires some tweaking on an app-by-app basis.<< | https://code.tutsplus.com/tutorials/tracking-user-behavior-with-google-analytics-sdk-for-android--mobile-9526 | CC-MAIN-2016-44 | refinedweb | 1,181 | 53.81 |
In my last post:
Simplify Caching using the Policy Injection Application Block: Aspect-Oriented Programming Opportunities
I gave an example of using the Policy Injection Application Block to remove the pre- and post-processing code that is associated with simple caching in your applications. The Policy Injection Application Block removed the clutter associated with caching from your code to better reveal its intention and simplify maintenance.
Before the Policy Injection Application Block:
public class Service : IService
{
public Data GetData()
{
// Pre-Processing
Are Results in Cache? If yes, return cached results.
// Real-time Expensive Processing
Nope. Get data from datastore.
// Post-Processing
Cache for X minutes and Return Results.
}
}
After the Policy Injection Application Block:
public class Service : IService
{
[CachingCallHandler(0, 30, 0)]
public Data GetData()
{
Get data from datastore.
}
}
Tag Matching Rule
Using the CachingCallHandler we were able to cleanse our code, but we still need to change source code if we want to change the caching interval. Given that the caching interval on this particular method is expected to be volatile, it would be ideal to change the caching interval through meta-data in an external file that can be modified without requiring any source code changes. We also like the idea of an attribute on this method as a hint to other developers that caching is indeed happening here, but we aren't handling it in the method itself. The Tag Matching Rule in the Policy Injection Application Block provides us this wonderful capability.
Let's remove the CachingCallHandlerAttribute from the method and put a TagAttribute that will still invoke caching, but instead grab the caching interval from our Web.config file instead of in the attribute itself.
public class Service : IService
{
[Tag("CacheResults")]
public Data GetData()
{
Get data from datastore.
}
}
Now we will jump into the new Enterprise Library Visual Studio-Integrated Configuration Editor and configure our caching policy in the Web.config file.
Notice we still specify the interval as 30 minutes, but now it is in the Web.config where we can change it easily without changing source code and recompiling. We could have just as easily specified an external file other than Web.config as well.
The way we create this service has not changed. We still use the factory as opposed to creating it explicitly. Under the covers the Policy Injection Application Block may pass you a proxy class if it finds that you want it to intercept some method calls and do some pre- and post- processing. In this case it reads the policies in the Web.config, notices the TagAttribute on the GetData Method, and intercepts the call to do caching for you.
IService service = PolicyInjection.Create<Service,IService>();
What has changed is now we can modify the caching interval in the Web.config file without changing code. You can do it via the graphical editor or just change the XML yourself:
<add name="CachingPolicy">
<matchingRules>
<add match="CacheResults" name="Tag Attribute Matching Rule" />
</matchingRules>
<handlers>
<add expirationTime="00:30:00" name="Caching Handler" />
</handlers>
</add>
This is a nice way to manage caching intervals when you expect it to be volatile or you just want the option to change it via configuration.
Conclusion
Enterprise Library is a good tool for your toolbox when your applications could benefit from these types of features.
If you find yourself using the Policy Injection Application Block, there is an Effective Policy Viewer for the Policy Injection Application Block that can help you understand what policies are tied to classes when using configuration.
Don't forget about the Day of Patterns & Practices in Tampa, Florida on May 25th :) Register here.
by David Hayden
You have just taken something that was very explicit, and turned it into implict.
You now have to worry about mispelling, case sensitivity, miscofiguration, etc.
In my opinion, you didn't gain anything from this.
I disagree 200%.
I gained the ability to change the caching interval in a configuration file while still maintaining a hint about caching being done via an attribute. I now don't have to change source code to change the caching interval, and a team of developers new to the Policy Injection Application Block can feel at ease that I am flagging policies until they feel comfortable about a configuration-only option which is my next post :)
Yes there are disadvantages ( case sensitivity not being one of them, however ), but this is definitely a great intermediate solution when a development team is new to the Policy Injection Application Block and doesn't want to hide the intentions about what is happening in code in a configuration file and a requirement is that the caching interval needs to be changed via configuration.
I would agree that it is not as explicit as the other attribute and a configuration only option, but don't broadly discount the option as I am sure it has merits even beyond the one I mention above.
If there is a need to configure the caching interval from the configuration, why not:
[Cacheable]
It is explicit, clear, and doesn't take away anything.
My main objection is that you went from the explicit to the implicit. Now you no longer have a caching attribute, you have a tagged caching, etc.
I don't see the value here.
I guess the simple answer is because [Cacheable] does not exist in the Policy Injection Application Block and [Tag("...")] does exist.
You could easily build a [Cacheable] attribute and use the Custom Attribute Matching Rule to look for it. But at the end of the day I don't think this offers a lot of advantages over the Tag | http://codebetter.com/blogs/david.hayden/archive/2007/04/21/simplify-caching-with-tag-matching-rule-in-policy-injection-application-block.aspx | crawl-001 | refinedweb | 942 | 51.48 |
I have been experimenting with React Native apps and how to run motion graphic animations inside such apps for some time now. And that’s where I came across the fantastic library called Lottie. If you are wondering how to integrate awesome motion graphics in your React Native mobile app, then Lottie is the answer. This tutorial will walk you through how to get started with Lottie animations for React Native iOS Apps. For Android, I will come up with a separate post sometime later.
TLDR;
What is Lottie?
Let’s hear it from the creators of Lottie…
Lottie is an iOS, Android, and React Native library that renders After Effects animations in real time, allowing apps to use animations as easily as they use static images.Airbnb
You can read and explore more about Lottie from its official page. Let’s see an example below,
How does it work?
- Using BodyMovin plugin you can export your Adobe After Effects animations to a JSON file.
- This exported JSON data can then be rendered as motion graphic animation inside your React Native app using the Lottie library.
Where do I get the animations? size grow. Lottie files are JSON and hence lightweight.
Alright, without wasting much time lets get started with our tutorial for integrating Lottie animations into our React Native app. First things first, What do you need?
The Setup
You are writing React Native mobile apps and of course, you need to have your React Native development tools set up on your computer. I will not go into the details of it. You can surely find everything on the web, official RN site or you can also go through one of my presentation slides.
I am excited, let’s get to the point…
Alright, let’s create an app from scratch and go through the steps. You can also find these instructions from the official Git repo.
Create a new React Native project
react-native init LottieTry
once done, cd into your project directory
cd LottieTry
Install React Native Lottie
yarn add lottie-react-native yarn add [email protected]
Go to your ios folder (inside /LottieTry)
cd ios/
Install necessary pod dependencies
pod install
This will install the React Native module pods for lottie-ios and lottie-react-native. Once done it will also link all the native dependencies. So no need to do “react-native link lottie-react-native” separately.
Now you can go ahead and launch your RN app,
Open LottieTry/ios/LottieTry.xcworkspace
Hit the Run button
So far so good, but there is one last step that needs to be done or else you might get this error while building the app from XCode (I got it…)
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Follow the steps mentioned below to fix this error.
1. Open the XCode project, and under targets select LottieTry. See the image below
2. Select the Build Settings tab and search for “library search paths”. Refer to the image below,
3. Under Library Search Paths, add the following to Debug and Release. Double click to open the dialog.
$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)
Refer the screenshots below,
Now clean the project and build or run again. The linking error should be gone now.
At the time of writing this tutorial, these are the versions that I had,
- react-native – 0.60.5
- react-native-cli – 2.0.1
- lottie-react-native – 3.1.1
- NodeJS – v8.10.0
- npm – 5.6.0
- yarn – 1.10.1
- XCode – 10.1
Need not worry, it should work with the versions you are having unless there are breaking changes. I would recommend reading the official docs. Still, having issues with your set up, give me a shout in the comments section.
Let’s write some code and build our animated app
Now that our app is up and running, let’s integrate our first Lottie animation. For this tutorial, I am using this car animation from Lottiefiles. Go ahead and download the JSON file and save it in a folder called assets inside the LottieTry RN project.
Next, import the lottie-react-native module in your App.js file
import LottieView from 'lottie-react-native';
And then declare the component inside your render() function,
<LottieView source={require('./assets/car.json')} autoPlay loop style={{height: 200}}/>
You can use props such as autoPlay, loop to customize your animation. You can even add styles such as height, width, backgroundColor, etc. Basically all the styles that you can apply to a View component can be applied to LottieView. Some examples below,
<LottieView source={require('./assets/car.json')} autoPlay loop style={{ height: 400, backgroundColor: 'red' }}/>
You can also use absolute positioning to place your Lottie animation
<LottieView source={require('./assets/car.json')} autoPlay loop style={{ position: 'absolute', bottom: 0, height: 200, backgroundColor: 'yellow' }}/>
See the full list of props and methods from the official document. So now you should have the car animation running inside your View.
Check the full source code below,
import React, {Fragment} from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, } from 'react-native'; import LottieView from 'lottie-react-native'; const App = () => { return ( <Fragment> <SafeAreaView style={styles.container}> <StatusBar barStyle="dark-content" /> <View style={styles.body}> <Text>This is a Car Animation</Text> <LottieView source={require('./assets/car.json')} autoPlay loop style={{height: 400}}/> </View> </SafeAreaView> </Fragment> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, body: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 15 }, }); export default App;
You can play around with the code, add multiple Lottie JSON in your view and try to position them. Use a ScrollView and see what happens. Fork my git repo which has this example.
Github repo
I will soon start writing more tutorials on React Native. Till then, chow!!
If you are looking to run Lottie animations for your React web application, you can read this tutorial which covers all the steps. It includes source code and demo. | https://josephkhan.me/react-native-lottie-animations/ | CC-MAIN-2021-04 | refinedweb | 997 | 57.37 |
Service Directory pricing
This document explains Service Directory pricing details. You can also use the Google Cloud Platform Pricing Calculator to estimate the cost of using Service Directory.
If you pay in a currency other than USD, the prices listed in your currency on Cloud Platform SKUs apply.
Pricing overview
Service Directory is billed per namespace, service, and endpoint per month, and by the number of Service Directory API calls.
Pricing tableIf you pay in a currency other than USD, the prices listed in your currency on Cloud Platform SKUs apply.
Note that if you use Service Directory zones, you are billed separately for Cloud DNS based on Cloud DNS pricing.
What's next
- Read the Service Directory documentation.
- Try the Pricing calculator.
Request a custom quote
With Google Cloud's pay-as-you-go pricing, you only pay for the services you use. Connect with our sales team to get a custom quote for your organization.Contact sales | https://cloud.google.com/service-directory/pricing?hl=lt&skip_cache=false | CC-MAIN-2021-49 | refinedweb | 159 | 55.95 |
[] Colliders that overlap with the given box.
Find all colliders touching or inside of the given box.
Creates an invisible box you define that tests collisions by outputting any colliders that come into contact with the box.
//Attach this script to your GameObject. This GameObject doesn’t need to have a Collider component //Set the Layer Mask field in the Inspector to the layer you would like to see collisions in (set to Everything if you are unsure). //Create a second Gameobject for testing collisions. Make sure your GameObject has a Collider component (if it doesn’t, click on the Add Component button in the GameObject’s Inspector, and go to Physics>Box Collider). //Place it so it is overlapping your other GameObject. //Press Play to see the console output the name of your second GameObject
//This script uses the OverlapBox that creates an invisible Box Collider that detects multiple collisions with other colliders. The OverlapBox in this case is the same size and position as the GameObject you attach it to (acting as a replacement for the BoxCollider component).
using UnityEngine;
public class OverlapBoxExample : MonoBehaviour { bool m_Started; public LayerMask m_LayerMask;
void Start() { //Use this to ensure that the Gizmos are being drawn when in Play Mode. m_Started = true; }
void FixedUpdate() { MyCollisions(); }
void MyCollisions() { //Use the OverlapBox to detect if there are any other colliders within this box area. //Use the GameObject's centre, half the size (as a radius) and rotation. This creates an invisible box around your GameObject. Collider[] hitColliders = Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, m_LayerMask); int i = 0; //Check when there is a new collider coming into contact with the box while (i < hitColliders.Length) { //Output all of the collider names Debug.Log("Hit : " + hitColliders[i].name + i); //Increase the number of Colliders in the array i++; } }
//Draw the Box Overlap as a gizmo to show where it currently is testing. Click the Gizmos button to see this void OnDrawGizmos() { Gizmos.color = Color.red; //Check that it is being run in Play Mode, so it doesn't try to draw this in Editor mode if (m_Started) //Draw a cube where the OverlapBox is (positioned where your GameObject is as well as a size) Gizmos.DrawWireCube(transform.position, transform.localScale); } } | https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html | CC-MAIN-2022-40 | refinedweb | 377 | 54.32 |
table of contents
NAME¶
get_color_depth - Returns the current pixel color depth. Allegro game programming library.
SYNOPSIS¶
#include <allegro.h>
int get_color_depth(void);
DESCRIPTION¶
Returns the current pixel format. This can be very useful to know in order to write generic functions which select a different code path internally depending on the color depth being used.
Note that the function returns whatever value you may have set previously with set_color_depth(), which can be different from the current color depth of the screen global variable. If you really need to know the color depth of the screen, use bitmap_color_depth().
SEE ALSO¶
set_color_depth(3alleg4), bitmap_color_depth(3alleg4), exrgbhsv(3alleg4) | https://manpages.debian.org/bullseye/allegro4-doc/get_color_depth.3alleg4.en.html | CC-MAIN-2021-43 | refinedweb | 105 | 50.33 |
by Alexander Prohorenko and Olexiy Prokhorenko
Originally published on BEA Dev2Dev June 2005
Over the past few years XML technology has gained great popularity as a format for exchanging information over the Internet. Today, XML is often portrayed as a distinct technology, but initially it was born as an Internet technology (somewhere between HTML and SGML). This article looks at how XML can be used as a "transport protocol" between a database and an end user.
The most popular relational database management systems use SQL queries for working with data. Although XML-oriented databases are already on the market, they are not yet ubiquitous. Keeping in mind the popularity of XML, the developers of relational databases are moving forward by adding XML compatibility to their products. This article looks at one such approach: having a database return XML. An Oracle database is used in the sample code, which is supposed to be an XML-compliant database that already has a mechanism for working with XML data.
This article will be divided into two parts. In the first part we'll prepare Java code to work with an Oracle database, make an SQL query, and receive XML output. The second part will be devoted to a web application that will receive XML data from the database and output it as HTML text.
The following software is used in this article:
The code in this article was run on Microsoft Windows XP but should work on any operating system with only minor changes.
We assume that the reader is an experienced Java developer who is familiar with BEA WebLogic Server and has some experience programming with JDBC.
If you are familiar with the configuration of JDBC connection pools and data sources, skip this section.
First we need to configure a connection pool and data source. The code will later retrieve the data source using JNDI. This requires a little configuration. We need to configure a JDBC Connection Pool, which holds connections to the database. Log in to the WebLogic console and choose the Service Configurations -> JDBC -> Connection Pools node.
Now create a new Connection Pool by selecting the Configure a new JDBC Connection Pool... link. On the next screen, choose a database type and a driver (Figure 1).
Figure 1. JDBC Connection Pool: Select database
You'll see many different databases to choose from. We need an Oracle database type, and we'll use BEA's Oracle Driver (Type 4). Click Continue to define the connection properties (Figure 2).
Figure 2. JDBC Connection Pool: Connection properties
On this screen, select a name for the JDBC Connection Pool, and set the additional database parameters such as database name, host name, port to connect, user name, and password.
Instead of creating a new database and set of tables, we'll use the sample
SCOTT/TIGER schema in Oracle and the EMP table. This sample exists on almost every Oracle installation, therefore it should not require any additional configuration from your side. If you do not have the EMP table or it is empty, you can use the scripts at the Oracle directory
\sqlplus\demo\demobld.sql to build tables from scratch and fill them with data, and use
\sqlplus\demo\demodrop.sql to drop old values.
After you have properly configured these parameters, click Continue (Figure 3).
Figure 3. JDBC Connection Pool: Connection test
Generally you don't need to change anything on this page. This is a connection test page (which you can skip by clicking the Skip This Step button). WebLogic Server shows the database parameters like driver classname, URL (for JDBC drier), and credentials for review. After you have reviewed these parameters you are ready to test. Click the Test Driver Configuration link, and if everything is correct, you will see the "Connection Successful" message. You can click the Create and deploy button to finish the JDBC Connection Pool configuration.
Now that we have finished with the JDBC Connection Pool, we need to create an appropriate Data Source. Go back to the main page of the WebLogic Server console, and follow Service Configurations -> JDBC -> Data Source. On the next screen you should click the Configure a new JDBC Data Source link. You'll get to the Data Source configuration page (Figure 4).
Figure 4. JDBC Data Source: Configuration
You should define the JDBC Data Source name and the JNDI path for where this JDBC Data Source will be bound. Remember the JNDI path; we'll use it later to set up a connection from our code. Next select Continue, and then choose the correct connection pool to associate with the Data Source. Select the Connection Pool that you just created, and click Continue. The next page allows you to select servers and clusters on which to deploy the Data Source. Check the necessary ones from the list, and then click Create. The Data Source has been created and we ready to start writing the code.
Let's prepare our environment for writing a simple client application. To be able to make an SQL query and receive XML data as output, we will use the Oracle XML-SQL utility (XSU). We will need to configure the CLASSPATH variable to point to the Oracle XML-SQL Utility library and the Oracle XML Parser. Normally, XSU can be found in the Oracle path
\rdbms\jlib\xsu12.jar, and the XML Parser can be found at
\lib\xmlparserv2.jar. Also, as we're using JNDI, we need to have
weblogic.jar in our CLASSPATH. Normally, you can find it in the WebLogic Server install directory at
\bea\weblogic81\server\lib\weblogic.jar.
The typical CLASSPATH will look like the following:
CLASSPATH=c:\Program Files\java\jdk1.5.0_01\lib;.; C:\DevSuiteHome\rdbms\jlib\xsu12.jar; C:\DevSuiteHome\lib\xmlparserv2.jar; C:\bea\weblogic81\server\lib\weblogic.jar;
Before showing you the code, it's worth noting that there are two approaches to working with XML in Oracle. They are quite different, and you should use the appropriate approach for your task. The first approach is to use Oracle's XSU, which allows you to return XML from any SQL query. The second approach is to use Oracle's XMLType column type.
XMLType columns allow you to treat XML as a native datatype within the database. Consequently, these columns can participate in queries just like any other column type. Oracle provides the
XMLTYPE() function to construct an XMLType data object and also provides different functions for working with this data type, like
XMLELEMENT() and
XMLAGG(). You can read more about this approach and see examples in the WebLogic Server documentation on the Oracle driver, or on the
Oracle Technology Network. In this article we are going to focus exclusively on the XSU approach.
Here is the complete source code (
oraxml.java) needed to make an SQL query on an Oracle database and produce XML output.
1. import javax.naming.*; 2. import javax.sql.*; 3. import java.sql.*; 5. import oracle.xml.sql.query.*; 5. public class oraxml 6. { 7. public static void main(String args[]) throws SQLException, NamingException 8. { 9. String tabName = "emp"; 10. int maxRows = 3; 11. Context ctx = new InitialContext (); 12. DataSource ds = (DataSource) ctx.lookup ("MyOra"); 13. Connection conn = ds.getConnection (); 14. OracleXMLQuery qu = new OracleXMLQuery ( conn, "select EMPNO, ENAME from " + tabName); 15. qu.setMaxRows (maxRows); 16. qu.setRowsetTag ("EMPLOYERS"); 17. qu.setRowTag ("PERSON"); 18. String xmlString = qu.getXMLString(); 19. System.out.println (xmlString); 20. conn.close (); 21. } 22. }
The code is very simple. Lines 11-12 retrieve a Data Source with a JNDI name of
MyOra. Lines 13 and 20 establish and close the connection. The most interesting lines are 14-18 which make a so-called "XML query". Technically, this is an SQL query, converted to XML by XSU. Line 14 initializes the query. Lines 15-17 set the structure of the future XML document. Line 15 sets the maximum number of rows returned, limited to
maxRows. Lines 16 and 17 set the root element of the document and the item delimiters. Line 18 generates an XML document and stores it in the
xmlString variable. As you can see, the code is very simple and easy to read.
Editor's note: Note that this is not production code. You should close a connection in a
finally clause.
We should not forget about JNDI, which we're using in this code. As this is a stand-alone Java application, we need to set a naming provider for it to use. We'll use our WebLogic Server; to configure this we need to create a
jndi.properties file and make sure it's accessible from the classpath. If your CLASSPATH has the current directory (.) in the path, you should place the
jndi.properties into the current directory. Here is our
jndi.properties file:
java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory java.naming.provider.url=t3://localhost:7001
The typical compilation command and result of running the program is shown below (remember that the output is limited to
maxRows):
C:\white\work\Java\xmlweb_src>javac oraxml.java C:\white\work\Java\xmlweb_src>java oraxml <?xml version = '1.0'?> <EMPLOYERS> <PERSON num="1"> <EMPNO>7369</EMPNO> <ENAME>SMITH</ENAME> </PERSON> <PERSON num="2"> <EMPNO>7499</EMPNO> <ENAME>ALLEN</ENAME> </PERSON> <PERSON num="3"> <EMPNO>7521</EMPNO> <ENAME>WARD</ENAME> </PERSON> </EMPLOYERS>
Let's look at the Oracle XML-SQL Utility in just a little more detail. As you can see, this is quite a handy utility that can be used for performing SQL queries and returning an XML formatted output. However, XSU is not limited only to this functionality. XSU can also perform tasks such as dynamically generate DTDs (Document Type Definitions), and it can perform simple transformations. XSU can also generate XML documents in their string or DOM representations, insert XML into database tables or views, update or delete records from a database object, and given an XML document can generate complex nested XML documents. XSU can also store them in relational tables by creating object views over the flat tables and querying over these views. Starting in Oracle9i, XSU can also generate an XML schema given an SQL query. In addition, it supports XML attributes during generation. To fully understand how you can utilize XSU functionality for your needs, refer to the XSU documentation.
We want to highlight the advantages of the XML transfer method described in this tutorial and explain why we think it's useful. One of the questions you may be asking yourself is why we are using XML here and why we are calling it "a bridge." The best way to explain the advantage of XML as "a bridge" is through a small example. Imagine you've got an information portal, which is designed to deliver news from the SQL database to end users, whoever they are: mobile users using WAP browsers or regular web surfers with modern browsers. Furthermore, you, as an information owner, can resell it to other end users, and your news should be shown with different titles, like "News from the Acme, Corp." and "Latest news from Big Company" and whatever else. But the news that you are delivering does not change. So why should you perform extra coding for every kind of end user who may receive your news, when you technically need only change the "look and feel"?
Now you can see that you need some transparent bridge that can receive SQL on one side and produce different formats on the other. This bridge is XML. Your servlet makes a request to the database, receives XML output, and applies an XSL template to it, producing a page for an end user. So, you need to change only a design in XSL and nothing more. No extra coding, no wasted time. What about sharing your news with others? That's great, but why should you allow others to access your SQL database? Why should you explain the structure of it? You can simply produce XML from the basic SQL query and share it.
Now that we have successfully coded our stand-alone application and it can query SQL and produce XML, we are halfway there. The next step is mastering the WebLogic Server options for converting XML into different formats, and building a web application. At the moment, there are different technologies for handling XML streams. Let's focus on only one of them, which is the XSLT JSP tag method. WebLogic Server provides this small JSP tag library for convenient access to an XSLT transformer from within a JSP. It is used for transforming XML documents into HTML, WML, and other formats. Let's first look at preparing an environment for our web application that will take advantage of these tools.
It is not a good idea to configure the CLASSPATH every time for a web application, therefore we need to take all our Oracle jar files and put them into the
\WEB-INF\lib directory of our application. We will also need to copy from the Oracle home the
\rdbms\jlib\xsu12.jar and
\lib\xmlparserv2.jar jar files. WebLogic Type 4 JDBC drivers are installed with WebLogic Server in the home directory of a server in the
\server\lib folder, and the drivers are automatically added to your CLASSPATH on the server.
The process of using the WebLogic XML tags is pretty simple and well documented in the WebLogic documentation Developing XML Applications with WebLogic Server. However, we will guide you through the whole process to make it even easier for you.
Take the
xmlx.zip from the WebLogic Server installation directory path
\bea\weblogic81\server\ext\. We need the
xmlx-tags.jar from this archive, and we have to put it in the
\WEB-INF\lib directory of our web application:
C:\white\work\Java\xmlweb\xmlweb_war\WEB-INF\lib>pkzipc -extract C:\bea\weblogic81\server\ext\xmlx.zip xmlx-tags.jar PKZIP(R) Version 4.00 FAST! Compression Utility for Windows Copyright 1989-2000 PKWARE Inc. All Rights Reserved. Shareware Version PKZIP Reg. U.S. Pat. and Tm. Off. Patent No. 5,051,745 Masking file attributes: Read-Only, Hidden, System, Archive Extracting files from .ZIP: C:\bea\weblogic81\server\ext\xmlx.zip Inflating: xmlx-tags.jar
Finally, you will need a
web.xml in your
WEB-INF directory with a
<taglib> tag referring to
xmlx-tags.jar file like this:
<web-app> <taglib> <taglib-uri>xmlx.tld</taglib-uri> <taglib-location>/WEB-INF/lib/xmlx-tags.jar</taglib-location> </taglib> </web-app>
See the included sample WAR application for the complete example.
Our goal in this section is to take the lesson we learned about producing XML in our stand-alone application, and apply it to build a web application that does the same&mdash&with the addition of transforming the XML to HTML. Let's review the files that are required for our web application. We will use
\WEB-INF\web.xml (mentioned above),
html.xls (a style sheet for the XSL converter, which will be used for producing HTML), and an
index.jsp (the main page of the web application). Let's look at these files in detail.
First of all, let's consider the style sheet file. The
html.xls file is used for converting XML output to HTML.
<?xml version="1.0" ?> <xsl:stylesheet <xsl:template <table width="60%" border="1" cellspacing="0" cellpadding="1"> <tr> <td align="center"><b>Employer No.</b></td> <td align="center"><b>Employer Name</b></td> </tr> <xsl:apply-templates </table> </xsl:template> <xsl:template <tr> <td align="center"><xsl:value-of</td> <td align="center"><xsl:value-of</td> </tr> </xsl:template> </xsl:stylesheet>
As you can see, this matches the root element, creates a table, and inserts a row for every template match of the
PERSON element. Using this we should be able to produce HTML from the incoming XML.
The
index.jsp is our main file in the web application. This is a regular JSP file. As we're using JSP tags, let's take a look at them. The XSLT JSP tag syntax is based on XML. A JSP tag consists of a start tag, an optional body, and a matching end tag. We'll just use the
<xslt> tag in our example. The tag can take optional (attribute) parameters such as
xml, which specifies the location of the XML file that we want to transform (relative to the document root of the web application), and
stylesheet, which specifies the location of the style sheet to use to transform the XML document. This location is also relative to the document root of the web application. For more information about available tags and options, refer to Using the JSP Tag to Transfer XML Data documentation, to the "XSLT JSP Tag Syntax" section. Let's now look at the JSP:
1. <%@ taglib 24. <x:xml> 25. <%=xmlString%> 26. </x:xml> 27. </x:xslt> 28. </BODY> 29. </HTML>
Line 1 includes the
xmlx tag library that we use later on in line 23. Lines 7-22 are the conversion from the regular Java code to JSP (without exception handling). It has a minor change of syntax but nothing more. Lines 23-27 is the actual XML shown. Line 23 configures the XML output and sets the style sheet file to be used to
html.xsl. Lines 24-26 include the XML to be converted, which was retrieved from the database. As you can see, the code is quite straightforward.
Now that you are familiar with the code, we are ready to build and deploy the web application to WebLogic Server. As this is such a simple WAR, we'll build it manually. Here is how to create
xmlweb.war for future deployment:
C:\white\work\Java\xmlweb\xmlweb_war>jar -cvf xmlweb.war . added manifest adding: html.xsl(in = 579) (out= 279)(deflated 51%) adding: index.jsp(in = 935) (out= 486)(deflated 48%) adding: WEB-INF/(in = 0) (out= 0)(stored 0%) adding: WEB-INF/lib/(in = 0) (out= 0)(stored 0%) adding: WEB-INF/lib/xmlparserv2.jar(in = 689990) (out= 645476)(deflated 6%) adding: WEB-INF/lib/xmlx-tags.jar(in = 11106) (out= 9952)(deflated 10%) adding: WEB-INF/lib/xsu12.jar(in = 456545) (out= 138160)(deflated 69%) adding: WEB-INF/web.xml(in = 327) (out= 226)(deflated 30%)
Now, take the built web application WAR file and deploy it to WebLogic Server. You can use the WebLogic Console for this. After deploying, point your web browser to the following link: and view the result. You should get something resembling Figure 5.
Figure 5. Deployed web application
As you can see, the data, retrieved as XML from the database is nicely formatted for presentation. And now we can use this technology for a lot of different things, starting with a news feed and finishing with some complex listing engine with templates and style sheets.
This tutorial presented the basics of a technology that combines SQL queries with XML transformers, giving you a unique feature to use in your software. XML technology itself has many uses in web applications, but its combination with databases make it an even more powerful tool.
Alexander Prohorenko is a certified professional, who holds Sun Certified System Administrator and Sun Certified Java Programmer certifications. His areas of interests include system development lifecycle methodologies, IT project management, server and application architecture.
Olexiy Prokhorenko is a Sun Certified Enterprise Architect, also holding Sun Certified Java Programmer and Sun Certified Web Component Developer certifications. His areas of interests include Web software architecture, development of software with frequently changing requirements, and management of distributed outsourcing teams. | http://www.oracle.com/technetwork/articles/entarch/xml-bridge-093515.html | CC-MAIN-2015-32 | refinedweb | 3,279 | 57.27 |
You can show more detailed information about you project.
You can show more detailed information about you project.
I should apologize for you.I am so dazed
Actually ,you can directly draw in the Frame object.
the code has been amended
import java.awt.*;
import javax.swing.*;
public class rago...
Hi maikeru .
you have made some mistakes that the Frame is a container ,you can't directly put something non-component in it.
For your sample,you should first create a panel object that hava...
Actually,you can write a get and set method for each attribute of Person.
Like:
public String getForename()
{
return this.Forename;
}
public void setForename(String Forename){...
This message occurs if CORE Generator cannot allocate enough memory to invoke the Java Virtual Machine (JVM). The default system memory used by CORE Generator is 1024 MBytes (512 MBytes on Windows...
I think it's the matter of memory ~
hi there,The code will be showed below :
import java.util.*;
class Person{
private String Forename;
private String Surname;
Hi.The first style Loop will be showed below
public class LoopPrint{
public static void main(String args[]){
int countspace=4;
int countstar=1;
for(int i=0;i<5;i++) | http://www.javaprogrammingforums.com/search.php?s=809ebb7b6dc8b654a4482f484181d5c6&searchid=686140 | CC-MAIN-2013-48 | refinedweb | 201 | 68.47 |
Preface
While reading this interesting and well-written blog post
on Scala,
Functional Programming and Type Classes, at some point I got
particularly interested in the section entitled "Yes Virginia, Scala has
Type-Classes" (section 4) where the author introduces type-classes as one
of Scala's more powerful features by giving an easy-to-understand
example.
While this example might perhaps be a little too much for Scala beginners who happen to encounter type-classes (and implicits) for the first time, it is still well suited to show off parts of the power and beauty of Scala, especially in terms of type-safety and, to some degree, also its outstanding collections library.
Well, there is maybe one minor drawback in the mentioned example, namely that it loses type information where it possibly shouldn't which is what I would like to address with this blog-post.
For beginners, there is quite a long introduction to type-classes in Scala, along with numerous examples. Others might want to skip that "detour" and jump right to where the fun starts.
Detour
If you are already familiar with what type-classes are and where they usually come in handy, you might want to skip this section. Nevertheless, if that is not the case, I will try to give you a quick (and, agreed, incomplete) introduction. First and foremost, however, I would like to refer to this excellent paper on Type Classes as Objects and Implicits.
Alright, so what are type-classes and why would I care?
The original concept of type-classes was developed years ago in the realm of Haskell with respect to adhoc polymorphism. They are of course not restricted to the Haskell world. In fact, in Scala-land they have numerous applications as well, namely
- require and/or provide certain characteristics for parameter types in generic programming (so-called context bounds)
- add behaviour to existing classes without having access to or modifying their respective code (so-called view bounds),
- provide a mechanism for type-level programming.
Context bounds
According to the Scala Language Specification:
A type parameterSo, what does this mean? Well, this is probably best explained in terms of some examples. There are three typical use-cases (in fact it is just one and the same thing but each of the following serves a slightly different purpose) to be found with respect to context bounds, one of which is...
Aof a method or non-trait class may also have one or more context bounds
A : T. In this case the type parameter may be instantiated to any type
Sfor which evidence exists at the instantiation point that
Ssatisfies the bound
T. Such evidence consists of an implicit value with type
T[S].
(#1) Restricting a generic function to parameters of a certain type
Suppose you wanted to implement a function
def doSomething[T](x: T) = ???
which works on some
x of type
T. Furthermore,
suppose you wanted to restrict
T to certain types. If those
types were to adhere to a particular class hierarchy, the solution would
be easy, say for all subclasses of
MySuperClass:
def doSomething[T <: MySuperClass](x: T) = ???
But what would you do if you wanted to restrict
T to
arbitrary classes having no relationship to each other at all,
e.g.
MySuperClass,
Double,
and
Vector[Double]? What you actually could do is define
a trait together with a set of values such as
sealed trait CanDoSomething[T] object mySuperClassCanDoSomething extends CanDoSomething[MySuperClass] object doubleCanDoSomething extends CanDoSomething[Double] object vectorOfDoubleCanDoSomething extends CanDoSomething[Vector[Double]]
and then, in a first step, refurbish the above method's declaration as follows:
def doSomething[T](x: T)(ev: CanDoSomething[T]) = ???
Don't worry, that's not the end. What we have done so far is nothing but
define
doSomething as a method which takes two arguments in
a curried fashion where the second argument merely serves
as evidence for the existence of a parameterized instance
of
CanDoSomething, hence effectively introducing a context
bound on
T. Now any caller of this function could only do
so once she had a suitable value at hand.
However, having to call
doSomething like that and having to
import those values or pollute namespaces is arguably clumsy, which is
exactly the point where type-classes for context bounds emerge in the form
of implicits.
Let us hence define the following companion object
to
CanDoSomething and move our values inside that object,
only this time prefixing them with the keyword
implicit:
trait CanDoSomething[T] object CanDoSomething { implicit object MySuperClassCanDoSomething extends CanDoSomething[MySuperClass] implicit object DoubleCanDoSomething extends CanDoSomething[Double] implicit object VectorOfDoubleCanDoSomething extends CanDoSomething[Vector[Double]] }
We also prepend the keyword
implicit to the second parameter
list of
doSomething
def doSomething[T](x: T)(implicit ev: CanDoSomething[T]) = ???
which can be written in a shorter form as (this is really just syntactic sugar)
def doSomething[T: CanDoSomething](x: T) = ???
Now we have two options: We can still call
doSomething and
explicitly provide a parameterized instance
of
CanDoSomething, or we can leave away that second
argument and have the compiler find the most suitable value
implicitly.
At this point, you would typically counteract and argue that this were some sort of compiler magic and hence it ought to be burned at the stake, but it is really not. There are strict rules for the determination and the priority of implicits such that there is always only one "winner", and that is chosen deterministically. For the detailed rules I would suggest to have a look at the Scala Language Specification.
(#2) Having type-classes provide behaviour
The second, closely related, and probably the more important use-case is having type-classes provide behaviour (read: methods) for certain parameterized instances.
Not yet following along? Then let me give you another example: Suppose you wanted to implement a generic function that scales all elements of a given collection according to a given factor. How would you do that? Well, let us roll up the sleeves and try the following naive approach:
def scale[T](xs: Traversable[T], factor: T) = xs map (x => x * factor)
But what happens once we compile the above definition is that the compiler
consequently complains about the missing symbol
*:
error: value * is not a member of type parameter T xs map (_ * factor) ^
This is usually the point where confusion starts. Why ffs would the
compiler not know how to multiply two elements? Isn't that just
silly?
Well, yes, and no: From our point of view, we probably meant to multiply some numbers, but what we actually defined was a generic function for a parameter
T which actually happens to represent any
possible type, i.e. not only numeric types
like
Int,
Double or
Float, but
also e.g.
String,
Vector or even
BufferedInputStream. Now, how is the compiler supposed to
know how to multiply instances of the latter classes or, more precisely,
call a method
obj.* on one such
instance
obj?
Luckily, we can use type-classes to the rescue again. For example, we
could define the following trait and companion object (please note that in
order to avoid confusion I will be using
times instead
of
*)
trait Numeric[T] { def times(x: T, y: T): T } object Numeric { implicit object IntIsIntegral extends Numeric[Int] { def times(x: Int, y: Int): Int = x * y } implicit object CharIsIntegral extends Numeric[Char] { def times(x: Char, y: Char): Char = (x * y).toChar } // ... something similar for Double, Float and all other // classes for which you explicitly want to provide the // corresponding behaviour. }
and subsequently redefine
scale as
def scale[T](xs: Traversable[T], factor: T)(implicit num: Numeric[T]) = xs map (x => num.times(x, factor))
which would then enable us to call
scale for collections of
all types for which we have explicitly provided a corresponding instance
of type-class
Numeric, e.g.
scala> scale(List(1,2,3), 4) res1: Traversable[Int] = List(4, 8, 12) scala> scale(List('A', 'B'), 1.toChar) res2: Traversable[Char] = List(A, B)
It is in fact no coincidence that browsing through the documentation of the Scala Standard Library reveals that such a type-class has already been implemented in a similar (read: better) way.
Still, some people might argue that most if not all of the above could be
achieved by a number of overloaded methods in the respective classes,
e.g.
Int.times(Int),
Int.times(Double),
Double.times(Double),
and so on. But then what would they do if they wanted to introduce another
- new - numeric type, say
MySuperDuperBigInt? First, they
would have to provide new overloaded methods for all existing classes
(
Int.times(MySuperDuperBigInt), etc.) which means modifying
tons of code and is probably error-prone, and secondly, how would they do
that if they had no access to the code of the existing classes, e.g. to
classes from the Java library (JDK)?
(#3) Increasing type-safety (possibly adding behaviour)
The third use-case is rather a combinaton of the former two. Let us start with another example where we wish to write a generic function that takes a collection of values and returns a probability density function for the corresponding random variable (a PDF can be understood as a function that evaluates to the relative likelihood of a random variable to take a given value).
Our function should return new instances of subclasses of
PDFDiscrete for e.g. collections
of
String whereas for collections of
Double we
would like to get a new instance of
PDFGaussian.
A typical first attempt at defining this could be
trait PDF[T] extends (T => Double) trait PDFDiscrete[T] extends PDF[T] trait PDFGaussian[T] extends PDF[T] def createPDF[T](lst: Traversable[T]): PDF = ???
where
createPDF would do all the dirty work for us and return
a new instance of either
PDFDiscrete
or
PDFGaussian.
So far, so good, but didn't we lose information about the most specific
type on the way? Oh boy, we did! While the dynamic type of the
return value is known at runtime, we (read: the compiler) have no way of
telling the most specific static type of the return value once
control flow is returned to the caller, i.e. we will only know that we got
a subclass of
PDFDiscrete,
PDFGaussian).
But there really is no reason why we should go without the exact type since we want to write type-safe programs, don't we? It is not surprising that this issue can be solved with type-classes (which in this case, but not necessarily, also know how to handle the given input):
trait CanBuildPDF[Elem, That] { def apply(xs: Traversable[Elem]): That } object CanBuildPDF { implicit object DiscreteFromStrings extends CanBuildPDF[String, PDFDiscrete[String]] { def apply(xs: Traversable[String]) = new PDFDiscrete[String] { // Determine the number of occurences of each distinct String ... def apply(x: String) = throw new Error("Not yet implemented.") } } implicit object GaussianFromDoubles extends CanBuildPDF[Double, PDFGaussian[Double]] { def apply(xs: Traversable[Double]) = new PDFGaussian[Double] { // Determine the mean and standard deviation from the given values ... def apply(x: Double) = throw new Error("Not yet implemented.") } } }
Here, we have a type-class
CanBuildPDF which is parameterized
with respect to the type
Elem of the elements of the given
input collection as well as the type
That of the
corresponding subclass of
That such
as
That <: PDF[Elem]). Each instance of this type-class
knows how to create the respective subclass of
CanBuildPDF.apply in a type-safe manner.
We would subsequently redefine
createPDF so as to use (and
require) one such instance as
def createPDF[Elem, That](lst: Traversable[Elem]) (implicit bldr: CanBuildPDF[Elem, That]): That = bldr(lst)
and, summa summarum, that will give us exactly what we wanted:
scala> createPDF(List("Hello", "world")) res20: PDFDiscrete[String] =
scala> createPDF(Array.fill(50000)(util.Random.nextDouble)) res21: PDFGaussian[Double] =
View bounds
According to the Scala Language Specification:
A type parameter
Aof a method or non-trait class may have one or more view bounds
A <% T. In this case the type parameter may be instantiated to any type
Swhich is convertible by application of a view to the bound
T.
Alright, so here we have the promise that once we give the compiler the
means of implicitly viewing a value of type
A as if it
were a value of type
T, it will happily do so and hence
enable us to e.g. call any method etc. provided by
T on the
original value which is of type
A.
How on earth is this useful, you might ask? And again, we have several use-cases which in fact all boil down to the very same thing. So let us go on.
(#1) Implicit conversion
For one thing, suppose you had the following representation of an n-dimensional vector:
class Vec(val elems: Seq[Double]) { require(elems.length >= 1) def +(other: Vec): Vec = new Vec(for ((x,y) <- elems zip other.elems) yield x+y) def *(other: Vec): Double = (for ((x,y) <- elems zip other.elems) yield x*y) sum override def toString = "Vec(" + elems.mkString(",") + ")" } object Vec { def apply(x: Double, xs: Double*) = new Vec(x +: xs) }
Agreed, the implementation is just bad, but that is not the point here.
The point is that we might wish for some kind of automatic conversion from
e.g. numeric literals or even tuples to instances of
Vec in
order to ease syntax a bit. So instead of having to write
Vec(1,2,3)
+ Vec(4,5,6) we prefer to express the same matter as e.g.
v +
(4.,5.,6.) for some instance
v of
Vec, or
even
(1.,2.,3.) * (4.,5.,6.). How would we do that?
Turns out we can deal with this by using a number of
corresponding implicit conversions (they really should go
into
Vec's companion object):
implicit def doubleToVec(x: Double) = new Vec(List(x)) implicit def tuple2ToVec(x: (Double, Double)) = new Vec(List(x._1, x._2)) implicit def tuple3ToVec(x: (Double, Double, Double)) = new Vec(List(x._1, x._2, x._3))
And consequently get
scala> import Vec._ import Vec._ scala> 1 + Vec(3) res1: Vec = Vec(4.0) scala> (2.,4.) + Vec(4,5) // Note the explicit use of Doubles res2: Vec = Vec(6.,9.) // in the left-hand tuple scala> (1.,2.,3.) * (4.,5.,6.) // Duples in both tuples res3: Double = 32.0
So far, we had to be explicit about using
Double for the
values of the tuple elements in the above example, and that was due to the
fact that we declared our implicit conversions with respect
to
Doubles, only. Can we maybe also get rid of this?
Yes, sure! Similarly to what we did before in one of the examples for
context bounds, we could redefine our implicit conversions such that they
work for all types
T for which there is a function that turns
any given
T into a
Double. Of course that's an
implicit view again! Let us hence proceed (so as to avoid more code
duplication I'll only treat
tuple3ToVec, the rest is of
course analogous):
implicit def tuple3ToVec[T](x: (T, T, T))(implicit conv: T => Double) = new Vec(List(x._1, x._2, x._3))
Here,
conv is the function that takes a
T and
gives us a corresponding
Double. Note that this argument
needs to be implicit itself due to the fact that
since
tuple3ToVec is implicit there's no way for us to
explicitly provide a function value for
conv. Luckily, the
Scala library designers have already implemented such a method for us, so
we don't need to do it ourselves.
Also note that we're not explicitly using
conv. Well, we could, but we don't need to as it will
(implicitly) be passed on and applied at the appropriate place:
scala> (1,2,3) + Vec(2.,3.,4.) res4: Vec = Vec(3.0,5.0,7.0)
Lastly, since implicit conversion are used so often (gosh, they're just so hideous), there is a more compact syntax for us syntax-lovers out there:
implicit def tuple3ToVec[T <% Double](x: (T, T, T)) = new Vec(List(x._1, x._2, x._3))
(#2) Pimp My Library™
One very useful thing is the ability to add behaviour to existing classes
without the need to access their original code. This way, you could
e.g. add methods to classes for which you feel these methods are really
missing. For example, let us propose that every
String should
have a method
runLengthEncoded which yields the corresponding
encoded representation of that string. Let us start out with some kind of
wrapper class that is supposed to enrich the original
class
String:
class RichString(s: String) { lazy val runLengthEncoded: List[(Char, Int)] = { def auxRLE(xs: List[Char]): List[(Char, Int)] = xs match { case Nil => Nil case h :: _ => val (buf, rem) = xs span (_ == h) (h, buf.length) :: auxRLE(rem) } auxRLE(s.toList) } }
This then gives us
scala> new RichString("aaabbaac").runLengthEncoded res1: List[(Char, Int)] = List((a,3), (b,2), (a,2), (c,1))
which is not yet what we wanted. Can we somehow use implicit conversions
to improve this? Well, you already know the answer. We simply define one
such conversion from
String to
RichString as
implicit def stringToRichString(s: String) = new RichString(s)
Now that we have successfully pimped the original class, we can
use
runLengthEncoded on just any instance
of
String:
scala> "aaabbaac".runLengthEncoded res2: List[(Char, Int)] = List((a,3), (b,2), (a,2), (c,1)) scala> val german="Doppelkupplungsgetriebe"; german.runLengthEncoded res3: List[(Char, Int)] = List((D,1), (o,1), (p,2), (e,1), (l,1), (k,1), (u,1), (p,2), (l,1), (u,1), (n,1), (g,1), (s,1), (g,1), (e,1), (t,1), (r,1), (i,1), (e,1), (b,1), (e,1))
(#3) Domain Specific Languages
DSLs allow for the extension of the syntax without touching the language core at all. If not overused, they're absolutely awesome, and their use is wide-spread, for example in many well-known specs or unit-test frameworks, or Akka, or just for fun.
To explain all aspects of DSLs is surely out of the scope of this document, but you should definitely go ahead and investigate this topic. By now you probably have more than just an idea about how things like these might work behind the scenes (taken from the user guide of ScalaTest):
Array(1, 2) should equal (Array(1, 2)) string should endWith ("world") sevenDotOh should be (6.9 plusOrMinus 0.2) map should contain key (1) map should contain value ("Howdy")
No? Implicits and friends ring a bell? Yep, that went well ☺
Riding the horse without saddle (the actual topic)
The OP's example (which I'm going to modify slightly) is all about folding
over the elements of a given parameterized collection. Such a fold could
e.g. be used to sum up all elements of a
Vector. A typical
naive attempt for this might be
def sum[T](lst: Traversable[T]): T = (lst foldLeft 0)(_ + _)
which of course fails for two reasons: one, there is no
+
defined for every possible type
T, and two,
0 is
certainly no meaningful value for anything but numbers.
Solving this problem with the help of type-classes is rather easy. So we start out with:
trait CanFold[-Elem, Out] { def sum(acc: Out, elem: Elem): Out def zero: Out } object CanFold { implicit object CanFoldInts extends CanFold[Int, Long] { def sum(acc: Long, elem: Int): Long = acc + elem def zero = 0 } } def sum[Elem, Out](lst: Traversable[Elem])(implicit cf: CanFold[Elem, Out]): Out = (lst foldLeft cf.zero)(cf.sum)
Let's check this:
scala> sum(List(1,2,3,4,5,6)) res0: Long = 21 scala> sum(1 to 100) res1: Long = 5050
Looking good so far. But what if we now wanted to fold over collections of
collections? At a first glance, that should be no problem at all, given
another corresponding instance of
CanFold.
implicit def canFoldTraversables[T] = new CanFold[Traversable[T], Traversable[T]] { def sum(acc: Traversable[T], elem: Traversable[T]): Traversable[T] = acc ++ elem def zero = Traversable.empty[T] }
And off we go:
scala> sum(List(List(1,2,3), List(4,5,6))) res1: Traversable[Int] = List(1, 2, 3, 4, 5, 6)
See the problem there? We are losing information about the actual type of
the collection since we got back a
Traversable where we
really wanted a
List (or whatever the designers of Scala
deemed applicable depending on what we stuck in there).
Saddling the horse
What we actually need is a way to determine the most specific type of the returned collection that we can get. But how can we do that?
Well, there is this especially useful type-class which is to be found in the collections
library,
namely
CanBuildFrom,
and we set off with this:
import scala.collection.generic.CanBuildFrom implicit def canFoldTraversables[Repr[T] <: Traversable[T], T, That] (implicit cbf: CanBuildFrom[Repr[T], T, That]): CanFold[Repr[T], That] = new CanFold[Repr[T], That] { def sum(acc: That, elem: Repr[T]) = acc ++ elem def zero = cbf().result }
For one thing, we made use of
CanBuildFrom only to determine
the most specific return type
That. As soon as we try to
compile that code, though, the compiler will consequently tell us that
"
value ++ is not a member of type parameter That". Well,
darn, we should have thought of this before. How about introducing an
upper bound then?
Turns out that defining an upper bound is not enough because, when we
have
That <: Traversable[T],
That could again
be just any subtype of
Traversable, somewhere deep down below
the type hierarchy, but the result of
++ is
a
Traversable and hence violates our very own type
constraints.
We could thus conclude that we need a lower bound as well, leaving us
with
That >: Traversable[T] <: Traversable[T], but that
would be nonsense or rather yield nothing more than the original approach
where we always lost the most specific type. And keeping that type was our
mission, remember?
So, let us rewind and see if we can still find a working solution with
respect to
That <: Traversable[T]. First, we remember that
the compiler complained about the result type of
++. Second,
we realize that we could have used the
CanBuildFrom instance
to create the return value of
sum:
import scala.collection.generic.CanBuildFrom // Note the use of type constructor `That[T]` instead of `That` implicit def canFoldTraversables[Repr[T] <: Traversable[T], T, That[T] <: Traversable[T]] (implicit cbf: CanBuildFrom[Repr[T], T, That[T]]): CanFold[Repr[T], That[T]] = new CanFold[Repr[T], That[T]] { def sum(acc: That[T], elem: Repr[T]) = { val builder = cbf() builder ++= acc builder ++= elem builder.result } def zero = cbf().result }
Good lord, this is ugly! But it yields our first working solution:
scala> foldFoo.sum(List(List(1,2,3), List(4,5,6))) res0: List[Int] = List(1, 2, 3, 4, 5, 6) scala> foldFoo.sum(List(Set(1,2,3), Set(3,4,5))) res1: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4) scala> foldFoo.sum(Vector(List(1,2,3), Set(3,4,5))) res2: scala.collection.immutable.Iterable[Int] = List(1, 2, 3, 3, 4, 5)
Can we do better? The answer to this rhetorical question is of course yes
(you can get more from details from Josh Suereth's
answer to a
related question on SO). By using
TraversableLike instead
of
Traversable we get more info on the type than what we got
before. However, we must drop
That in favor
of
Repr or else we will run into trouble with the type
inferrer:
import scala.collection.generic.CanBuildFrom import scala.collection._ implicit def canFoldTraversables[Repr[T] <: TraversableLike[T, Repr[T]], T] (implicit cbf: CanBuildFrom[Repr[T], T, Repr[T]]): CanFold[Repr[T], Repr[T]] = new CanFold[Repr[T], Repr[T]] { def sum(acc: Repr[T], elem: Repr[T]) = acc ++ elem def zero = cbf().result }
This concludes this rather longish blogpost with our final working
solution. Maybe the code could still have been improved in terms of
using
That and hence not restricting the type of the
resulting collection too much, but so far I couldn't figure out how.
Please note that it was my intention to demonstrate the development cycle in this last example with all its one-way streets as I think that this is something that we all experience every now and then.
Thank you very much for reading along! The code examples can be found here. Any constructive feedback is appreciated. | http://rudairandamacha.blogspot.de/2012/11/saddling-horse-with-type-classes-in.html | CC-MAIN-2015-48 | refinedweb | 4,116 | 59.74 |
L. This post contains a summary of some of the new capabilities announced. Let’s take a look at some of those great new features!
1. app/Models Directory
The
artisan:make model command will create the model in the app/Models directory. This feature was decided after Taylor asked people on Twitter how they feel about this.
To those in the "app/Models" camp. What do you do when you have 1 class that isn't a model – it's just a regular class? Since you have set a precedent that no files can live in "app" directory, do you create some "Misc" folder? "Libraries"? 😬
— Taylor Otwell 🛸 (@taylorotwell) June 30, 2020
Spicy Monday poll… don't respond with some "I follow DDD and put them in contextual directories" thing either 💋
— Taylor Otwell 🛸 (@taylorotwell) June 29, 2020
If you don’t like that, it’s possible to delete the
app/Models directory and artisan will create the model file in the
app/ folder. It’s cool that Laravel is built with so much input from the community!
2. New Landing Page
Laravel 8 comes with a new landing page for a brand new install. It is now redesigned and It is built using TailwindCSS, includes light and dark-mode capabilities, and by default extends links to SaaS products and community sites.
3. Controllers Routing Namespacing
No more double prefix issues! In previous versions of Laravel, the RouteServiceProvider had an attribute called namespace that was used to prefix the controllers in the routes files. That created a problem when you were trying to use a callable syntax on your controllers, causing Laravel to mistakenly double prefix it for you. This attribute was removed and now you can import and use it without the issue.
It can also be used for single action controllers that have the
__invoke method.
4. Route Caching
Laravel uses route caching to compile your routes in a PHP array that is more efficient to deal with. In Laravel 8, it’s possible to use this feature even if you have closures as actions to your routes. This should extend the usage of route caching for improved performance.
5. Attributes on Extended Blade Components
In Laravel 7 the child components didn’t have access to the
$attributes passed to it. In Laravel 8 these components were enhanced and it is now possible to merge nested component attributes. This makes it easier to create extended components.
6. Better Syntax for Event Listening
In the previous versions of Laravel, when creating a closure-based event listener there was much repetition and a cumbersome syntax.
In Laravel 8 it’s simpler and cleaner:
7. Queueable Anonymous Event Listeners
In Laravel 8 it is possible to create queueable closure from anywhere in the code. This will create a queue of anonymous event listeners that will get executed in the background. This feature makes it easier to do this, while in previous versions of Laravel you would need to use an event class and an event listener (using the ShouldQueue trait).
8. Maintenance Mode
This is especially useful when you need to do some maintenance on your application and you want to take it down for your users but still let your developers investigate bugs. This will create a secret cookie that will be granted to whoever hits the correct endpoint, allowing it to use the application while in maintenance mode.
Pre-rendering an error view is a safe way for not exposing errors to your end user when your application is down (during a new deployment, for example). The Laravel 8 framework guarantees that your predefined error page will be displayed before everything else from the application.
This combines the new features and will make the application only display a single predefined route, while still allowing for the people who have the secret to test and debug. This can be very useful when launching a new app.
9. Closure Dispatch “Catch”
Laravel has a pretty robust queue system that accepts a closure queue that will get serialized and executed in the background. Now we have a way to handle failures in case your job fails.
10. Exponential Backoff Strategy
This is an algorithm that decreases the rate of your job in order to gradually find an acceptable rate.
Now Laravel has this capability too, which is handy for jobs that deal with external APIs, where you wouldn’t want to try again on the same amount of time. It can also be used to dynamically generate the return array, setting different times to wait before retrying.
11. Job Batching
Modeled after the Sidekiq and Ruby library, job batching makes it easy to handle many jobs at the same time concurrently. It’s also easy to be notified when all jobs are complete, or when there’s any error on it’s execution. You can see more details on the PR that added this functionality.
12. Rate Limiting
Rate limiting provides a new and more convenient way of limiting the use of your routes.
13. Schema Dumping
Schema dumping is a way to squash migrations to a single file. It generates a schema file that has the whole schema for your database in a SQL form. This is used during development, useful for integrating new developers on your project that already has a large number of migrations. It supports MySQL, Postgres, SQLite.
14. Model Factories
Model factories are class based factories that add a lot of new features to Laravel 8. For each model there’s also a factory class, where there is a definition method that says which attributes it will generate for that model. Your models make use of that factory through the Factory trait.
Factories are rewritten for Laravel 8 to be class based. 🦩 pic.twitter.com/2ODeIfktsC
— Laravel News (@laravelnews) August 26, 2020
15. Laravel Jetstream
Laravel Jetstream is a brand new scaffolding for Laravel released as an open-source package. It builds an application using TailwindCSS and TailwindUI, includes login, registration, two-factor authentication, session management. It offers two versions for handling frontend: Livewire (TALL Stack) or InertiaJS (VueJS)
References
- Laravel 8 – A rundown of new features
- What’s new in Laravel 8?
- Laravel 8 Goodies – Part 1
- Features and Changes Coming to Laravel 8’s Queue System
- Laravel 8 Upgrade Guide
- Time traveling is coming to Laravel 8
- Reddit – What’s new on Laravel 8
- The Challenges of Building a Community of Experts
While Communities of Experts improve outcomes for our clients and aid career growth for our…
- Comparing AdonisJS to Laravel
Over the past two years I have been involved in a project that was built… | https://moduscreate.com/blog/15-features-laravel-8/ | CC-MAIN-2022-21 | refinedweb | 1,110 | 60.04 |
How to Send Email Using C#
Sending email is a useful feature to have in many web applications. For instance, internet marketing strategies often involve using autoresponders to constantly send offers to subscribers. Daily reports can also be emailed to web administrators to keep them updated on the health of their site.
In this post, we will send a simple email using c sharp.
What Is Needed
In order to send email, we would need the following settings:
- The email host
- Credentials (username / password)
Of course, we would also need the email subject, body, From address, and To address.
Composing and Sending the Email
We would only need these classes to send email: SmtpClient, NetworkCredential, MailMessage, and MailAddress. We would have to include the namespaces System.Net and System.Net.Mail for us to use them.
Now it's time to compose the email. Here's where MailMessage and MailAddress come into play:
MailAddress fromAddress = new MailAddress("me@me.com"); MailAddress toAddress = new MailAddress("you@you.com"); MailMessage message = new MailMessage { From = fromAddress, Subject = "hi, this is a test", Body = "<html><head></head><body><h1>Hello, world!</h1></body></html>", IsBodyHtml = true }; message.To.Add(toAddress);
In the above code, we used the constructor of the MailAddress class that takes one argument, which is the name of the address. We then created the MailMessage using object initializer syntax.
Notice that the body is an html fragment, and a property called IsBodyHtml is set to true. Making the body an html document allows for the use of additional styles, such as colors, fonts, and layout.
Now that we have something to send, let's send it using the SmtpClient and NetworkCredential classes:
SmtpClient smtpClient = new SmtpClient { Host = "smtp.myHost.myDomain.com", Credentials = new NetworkCredential { UserName = "myUsername", Password = "myPassword" } }; smtpClient.Send(message); // message is the MailMessage we created earlier
And that's it! The email will be sent. | https://www.ojdevelops.com/2013/08/how-to-send-email-using-c.html | CC-MAIN-2021-10 | refinedweb | 316 | 58.28 |
In application development - as every developer knows - there is always a point in time where he has to deal with object-persistence. So if you don't want to write SQL-code or stuff like that all the time, you need a general solution - an object persistence framework. Such frameworks have very different approach and are often specialized for different tasks and environments.
I'm a contributor to an Open source-project that implements a web-application-server called RAPPTOR[^]. There, we had to deal with that nasty persistence-thing. But when we took a look at the market, there was no solution that satisfied all our needs.
There are many powerful frameworks around, but we couldn't use any of them without any restrictions and so we decided to realize it ourselves. Because our web-application-server is called RAPPTOR, we decided to name our persistence framework RAPPTOR.Persistence. It's completely independent from the application-server, so everybody is invited to use it. In this article, I want to give an overview on how to use that thing.
The general philosophy of our framework is that the storage-schema follows our object-model and not vice versa. So, it would not be possible to set an object model on top of an existing SQL-schema. We first want to write our code and then the framework will do the data-storage stuff for us.
I will now explain in short the general structure of the framework. It is divided into three layers:
The data-model layer is a very abstract thing that enables us to implement different drivers to deal with data from our code in different ways. Currently, there is only one implementation called DataModelREF that reflects an object-model to retrieve the schema and uses specific member declaration helper-classes to read and write the data of our object-model. That data-model (that's the way we call such drivers) is the one I will introduce in a later example. So it is not that schema information must come from a class hierarchy - e.g. an XML-schema with associated data could be persisted by a suitable model-driver, too.
The general database layer is used by the data-model drivers to access stored data in general. It is designed in a way that enables us to write a driver for an object-oriented database system. General object-management and caching are realized here.
The relational database layer sits on top of the general database layer and specializes it towards relational databases. The design-goal was to be able to write drivers for relational databases in a very easy way. Currently there are three drivers supporting MySQL 4.1, PostgreSQL and MSSQL.
The whole system is implemented by using the new .NET concepts from the 2.0 Framework. So you need either mono SVN[^] or the .NET 2.0 (beta) Framework.
Now, I will show you a small example. With the help of an easy object I will show you what happens in the database. After that I will change the structure a little bit. Finally, in the third part we will enhance complexity by expanding the data model using inheritance. By using such a persistence layer, life becomes much easier for developers.
Before we can work on the persistence layer and build our object model we have to prepare the database. We need PostgreSQL in our example, the actual version is 8.0. In the PostgreSQL admin tool or the phpPgAdmin I'll generate an empty database and call it "CarData". Consider that you have all the needed privileges to that database, especially CREATE, DROP and ALTER rights on tables. Preparation on the database side is finished with that.
CREATE
DROP
ALTER
The easiest way to demonstrate the example is to take a console-project and add references to "RAPPTOR.Persistence.dll" and "RAPPTOR.Persistence.PostgreSQLDriver.dll".
We have to take a nice example. So we have to store something that everybody knows: cars. Objects from this class have certain properties, e.g. manufacturer, a color, max speed and the number of gears.
In our project we add a new class "cars.cs". In the using directive we add:
using
using Rapptor.Stage0.DataModel.REF;
In order to make the class Car persistent, we have to inherit from the class ManagedObject. Furthermore our class is complete with maintenance functionally and becomes an object ID (ObjID) - in RAPPTOR this is a global unique identifier (GUID).
Car
ManagedObject
If you want to store members in the database you define them by special data types. These generic classes are defined in the DataModel.REF namespace and are inherited from the MemberManager class. You can use the following data types:
MemberManager
As we use .NET generics we will work with their type secure members. We have to use the methods Value and Object to read and write data (we will see that later in an example). Complex objects are the ones that are inherited from the class ManagedObject.
Value
Object
We define the following members: the Manufacturer and Color as string, the MaxSpeed as float and the number of Gears as byte. In the code it looks like this:
Manufacturer
Color
string
MaxSpeed
float
Gears
byte
public class Car : ManagedObject
{
public EV<string> Manufacturer;
public EV<string> Color;
public EV<float> MaxSpeed;
public EV<byte> Gears;
}
In our main program we make an instance of the class Car. We have to use the following namespaces:
using Rapptor.Stage0.DataModel;
using Rapptor.Stage0.DBDriver.PostgreSQL;
First, we define a handle to the database. In the static GlobalDataModel we join the driver with the class member DB. Then we make an instance of DBDriverPostgreSQL and call the Open method. The connection string is the parameter; use it like an ADO.NET string:
GlobalDataModel
DB
DBDriverPostgreSQL
Open
Finally the PostgreSQL driver object has to be set on the static member DB of the class GlobalDataModel.
PostgreSQL
DBDriverPostgreSQL db;
db = new DBDriverPostgreSQL();
db.Open(
"server=yourserver;database=CarData;uid=testuser;pwd=");
GlobalDataModel.DB = db;
Here comes our car. We create a green Porsche which is stored in the variable car:
car
Car car = new Car();
car.Manufacturer.Value = "Porsche";
car.Color.Value = "green";
car.MaxSpeed.Value = 250;
car.Gears.Value = 5;
You have to use the property Value, it is mandatory (handled in DataModelREF). The reward is a type secure programming. Now you can run the program and - nothing happens visibly. The local object car in the memory is forgotten when the program ends. Look at the next chapter and you will see some interesting things in the background.
The tables in the database "CarData" are automatically generated by the framework. At the moment the PostgreSQL driver object is associated with the GlobalDataModel. The database structures are compared and if the database is empty, the system creates all the necessary tables. Every persisted class has one table (look at "dn_car"). The columns represent the members of the class. Every object is also stored in the table "object" which saves further information, e.g. the column "TypeID" saves the class membership. Finally the "globalvalues" table holds the entire data model structure as a serialized SOAP stream in order to compare the structures faster.
Take a look at the database:
All columns in the table "dn_car" represents the class Car. What I declared before the member "OID" is the system administrated unique object ID. So every object is identified clearly:
If the green Porsche is instantiated, the object is stored in a memory cache managed by the framework. Later the object is stored in the database, managed by the GarbageCollector. This happens when there is no reference to the object, like when the program terminates. In the table "dn_car" you will see:
Even the table "object" has an entry:
I said that cars have a model description. Now we can expand the class structure and insert a string member Model, as you can see in the next code block:
Model
public class Car : ManagedObject
{
public EV<string> Manufacturer;
public EV<string> Model;
public EV<string> Color;
public EV<float> MaxSpeed;
public EV<byte> Gears;
}
In the main program where we create the new car we will set the model to "911" and make it red.
Car car = new Car();
car.Manufacturer.Value = "Porsche";
car.Model.Value = "911";
car.Color.Value = "red";
car.MaxSpeed.Value = 260;
car.Gears.Value = 5;
We know that we have to look directly into the database after the program starts. The table "dn_car" has changed; a new column "model" has been inserted by the framework. This happens by comparison of the data structures:
What happens to our values in the table? The green Porsche still exists; the red one has been added. Only the red Porsche has a model description, formerly the member wasn’t known.
As you can see, changing the data structure lately has no problem. You don't have to care about that, the database structures are updated automatically. The algorithm will do that by the principle "keep the values of the members that still have the same name and data-type".
Look at the table "dn_car":
Now we will enlarge the car model.
In the model, we save the car driver. Every car refers to a driver. Add the class Driver as shown:
Driver
public class Driver : ManagedObject
{
public EV<string> Name;
public EV<DateTime> Birthday;
}
Now we add a reference to the Car class:
public class Car : ManagedObject
{
...
public RO<Driver> CarDriver;
}
We also want to save racing cars with a notable engine in the model. We inherit the class RacingCar from Car because a racing car has all the properties of a car. As Car inherits from ManagedObject, RacingCar is also a persistable class.
RacingCar
We want to embed an engine object in our racing car. So define the class Engine as follows and use the class RacingCar as declared by inheritance:
Engine
public class Engine : ManagedObject
{
public EV<float> Cylinder;
public EV<float> HorsePower;
}
public class RacingCar : Car
{
public EO<Engine> CarEngine;
}
You know, racing cars are built using advertisement-money. All the sponsors of the car will be managed by a collection:
public class Sponsor : ManagedObject
{
public EV<string> Name;
public EV<double> AdvertisementMoney;
}
Now complete the class RacingCar and give it a chief designer:
public class RacingCar : Car
{
public COL<Sponsor> Sponsors;
public EO<Engine> CarEngine;
public EV<string> ChiefDesigner;
}
The object model shows the structure, the code block demonstrates how to define the objects:
Driver cd = new Driver();
cd.Name.Value = "Michael Schumacher";
cd.Birthday.Value = System.DateTime.Parse("01/03/1969");
Engine engine = new Engine();
engine.Cylinder.Value = 10;
engine.HorsePower.Value = 900;
Sponsor s1 = new Sponsor();
s1.Name.Value = "Red Flash";
s1.AdvertisingMoney.Value = 1000000;
Sponsor s2 = new Sponsor();
s2.Name.Value = "MoneyBank";
s2.AdvertisingMoney.Value = 5000000;
RacingCar rc = new RacingCar();
rc.Manufacturer.Value = "Ferrari";
rc.Model.Value = "F2005";
rc.Color.Value = "red";
rc.MaxSpeed.Value = 380;
rc.Gears.Value = 6;
rc.CarDriver.Object = cd;
rc.ChiefDesigner.Value = "Rory Byrne";
rc.CarEngine.Object = engine;
rc.Sponsors.Add(s1);
rc.Sponsors.Add(s2);
The database-schema that establishes while the program runs, represents our object-model. Every embedded and referenced object is persisted with its actual values.
The RacingCar-object rc is now stored in the tables "dn_car" and "dn_racingcar" (look at the OID). To store objects using inheritance, every inheritance-layer of an object (a class) is stored in a table. To collect all the members of a RacingCar object, the tables "dn_car" and "dn_racingcar" are connected 1:1 by the OID.
rc
Every object is represented in the "object"-table. Here the two sponsors and the engine are very interesting, because all of them are referencing to their parent object by the column "ParentID". The column "MemberInParent" additionally holds the name of the embedding member of the parent object. The multiple entry "Sponsors" indicates a collection as the holding member.
In the next tutorial I will explain, how to load stored objects from the database. This tutorial only shows you the general function and the central idea of the framework.
At the moment RAPPTOR.Persistence is in its development phase and uses - as it is very young - very new approaches from the .NET 2.0 Framework - especially generics. To use it you need to have .NET 2.0 (at the moment a beta 2) or mono 1.1.8. The persistence layer is in alpha-phase and is growing fast. For example there will be many more service-functions in the DataModelREF-classes, a query language and so on. We cannot guarantee that it will work without any problems. It has a huge optimization potential. If you are interested in helping us to extend, polish or test the framework please contact us[^] or Novell Forge[^]. Every contribution. | http://www.codeproject.com/Articles/11444/RAPPTOR-Persistence-Transparent-object-persistence?fid=210853&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None&fr=11 | CC-MAIN-2016-30 | refinedweb | 2,140 | 58.38 |
This form action's result is just one variable value
even if you checked all Skills set checkbox
(Java, Jsp, Servlets) it will return only one value
it will return only "Servlet" as one last value, not all three value are sent?
Post your Comment
Array of checkboxes - Struts
Array of checkboxes How to handle unknown number of checkboxes using tag in an ActionForm. Hi friend,
Code for multiple checkbox
import javax.servlet.http.HttpServletRequest;
import
JavaScript Array of checkboxes
JavaScript Array of checkboxes
... that help you in
understanding JavaScript Array of checkboxes. For this we are using JavaScript
as Script language. In this example we make a HTML form
how to get data from checkboxes - JSP-Servlet
how to get data from checkboxes hi,
i got list of tables on screen by invoking webservices.when the user selects the tables by using checkboxes, i... things using getParameterValues() which returns string array
want to ask how to update data for runtime selected multiple checkboxes
have checkboxes for each record when I will select more than one checkboxex...
var rowNumber;
function check23(abc)
{
/* alert...= f1.elements.length;
alert(e);
var cnt=0;
var j=0;
var name=new Array
The checkboxes tag
In this section, you will learn about checkboxes tag of Spring form tag library
checkboxes set to true using JavaScript
checkboxes set to true using JavaScript To set all checkboxes to true using JavaScript
Updating multiple value depending on checkboxes
Updating multiple value depending on checkboxes Hi .. I want to Update the multiple values of database using checkboxes and want to set the session for selected checkboxes..? please answer if any one knows as soon as possible
List of checkboxes - JSP-Servlet... checkboxes should be displayed. And we should keep remaining checkboxes
help me in disabling checked checkboxes
in this code....such that...
when i select some checkboxes and submit this form..., it should display previoue checked checkboxs as disabled.and remaining checkboxes
how to display selected checkboxes dynamically using jsp
how to display selected checkboxes dynamically using jsp Hi friends i have a requirement that :
in my JSP page i have radio buttons followed by the DB fields..when i click SUBMIT button,if the field(or record
dropdown wth checkboxes - Design concepts & design patterns
dropdown wth checkboxes Hi Friends,
Instead of using Ctrl key i want to put checkboxes inside the dropdown,then we can check the options whatever we want.
Please give me the html code(only html & javascript).
Thanks
JavaScript Array
that help you in
understanding JavaScript Array of checkboxes. For this we are using...
only one result valueRidwanK October 25, 2011 at 3:56 PM
This form action's result is just one variable value even if you checked all Skills set checkbox (Java, Jsp, Servlets) it will return only one value it will return only "Servlet" as one last value, not all three value are sent?
Post your Comment | http://roseindia.net/discussion/22580-JavaScript-Array-of-checkboxes.html | CC-MAIN-2015-32 | refinedweb | 486 | 60.35 |
ASP.NET Core: Converting C# Enums to JavaScript
ASP.NET Core: Converting C# Enums to JavaScript
In this article, we pick up where we left off last time, and show you how you can convert C# enums to JavaScript while using ASP.NET Core.
Join the DZone community and get the full member experience.Join For Free
In my previous posts about enums, I covered how to convert C# enums to JavaScript on classic ASP.NET MVC. This blog post introduces how to do it on ASP.NET Core using the simple view component.
To get a better understanding of my previous work on getting C# enums to JavaScript on classic ASP.NET MVC, I suggest to read my following blog posts:
This post takes the latter one as a base and ports it to ASP.NET Core. In large part, the code will be the same but there are some small differences in how reflection is used and how enums get to the page as JavaScript. On ASP.NET Core, I decided to use ViewComponent as it returns an instance of HtmlString.
JavaScriptEnum Attribute and Sample Enums
I begin again by defining the JavaScriptEnum attribute that marks our enums that we want to get to JavaScript. I also define two simple enums for testing.
public class JavaScriptEnumAttribute : Attribute { } [JavaScriptEnum] public enum PaymentTypeEnum { CreditCard, Check, Cash } [JavaScriptEnum] public enum CustomerStatusEnum { Regular, Gold, Platinum }
Now let's get to real business.
Defining View Component
I decided to go with the view component that returns enums in JavaScript as HtmlString. This view component doesn't have any view, as view for this simple output would be overkill.
public class EnumsToJavaScriptViewComponent : ViewComponent { public Task<HtmlString> InvokeAsync() { var query = from a in GetReferencingAssemblies() from t in a.GetTypes() from r in t.GetTypeInfo().GetCustomAttributes<JavaScriptEnumAttribute>() where t.GetTypeInfo().BaseType == typeof(Enum) select t; var buffer = new StringBuilder(10000); foreach (var jsEnum in query) {; } }
As out view component is here, it is now time to try converting this to JavaScript.
Testing View Component
My decision was to include the view component in the layout page of the web application.
<script> @await Component.InvokeAsync("EnumsToJavaScript") </script>
When a web application is run, the script block above looks like this.
<script> var PaymentTypeEnum = { "CreditCard": 0, "Check": 1, "Cash": 2 }; var CustomerStatusEnum = { "Regular": 0, "Gold": 1, "Platinum": 2 }; </script>
Now the enums marked for JavaScript are available in JavaScript.
Wrapping Up
Although reflection APIs are a little different in ASP.NET Core than in classic ASP.NET, and on ASP.NET Core it's possible to use view components instead of HtmlHelper extension methods, the porting of enums to JavaScript code from classic ASP.NET to ASP.NET Core was actually simple and there was no need for big changes. The view component is actually a good choice, as it supports framework level dependency injection and is, therefore, open for more advanced scenarios.
Published at DZone with permission of Gunnar Peipman , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/aspnet-core-converting-c-enums-to-javascript?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev | CC-MAIN-2019-30 | refinedweb | 520 | 65.01 |
Welcome to part 3 of my C Video Tutorial!
In this tutorial I cover : exit(), switch, Arrays, Array Indexes, Problems with scanf(), Memory Overflow, strcpy(), fgets(), Array Interation, strcmp(), strcat(), strlen(), strlcpy(), Global Variables, Local Variables, Functions, and more…
The code below is heavily commented and will help you learn. Feel free to leave any questions you have.
If you like videos like this it helps to tell Google+ with a click here [googleplusone]
Code From the Video
CTutorial3_1.c
#include <stdio.h> // Needed for exit() #include <stdlib.h> void main(){ int whatToDo = 0; do{ printf("\n"); printf("1. What Time is It?\n"); printf("2. What is Todays Date?\n"); printf("3. What Day is It?\n"); printf("4. Quit\n"); scanf(" %d", &whatToDo); } while(whatToDo < 1 || whatToDo > 4); // How to handle the input with if if(whatToDo == 1){ printf("Print the time\n"); } else if(whatToDo == 2){ printf("Print the date\n"); } else if(whatToDo == 3){ printf("Print the day\n"); } else { printf("Bye Bye\n"); // Exit the program with a non error state // Almost always better to use return exit(0); } printf("\n"); // How to handle the input with switch // Switch checks the value provided and executes // accordingly. (Value must be char or int) // break is used to stop checking input against the // other options. Without break other options would // be checked switch(whatToDo){ case(1) : printf("Print the time\n"); break; case(2) : printf("Print the date\n"); break; case(3) : printf("Print the day\n"); break; default : printf("Bye Bye\n"); exit(0); break; } }
CTutorial3_2.c
#include <stdio.h> #include <string.h> void main(){ printf("\n"); // ARRAYS ------------- // We have already taken a look at arrays when we stored // strings in a character array. // An int array is the same type of thing, and array // that stores ints. // An array can only store elements of the same data type char wholeName[12] = "Derek Banas"; // You can also define an array one element at a time int primeNums[3] = {2, 3, 5,}; // You don't need to define the size if you define // the values up front int morePrimes[] = {13, 17, 19, 23}; // Like most other languages the first number in an // array is put in the zero index printf("The first prime in the list is %d\n\n", primeNums[0]); // A character array can be created the same way char city[7] = {'C', 'h', 'i', 'c', 'a', 'g', 'o'}; // If I want to print the character array as a string // though I have to add \0 at the end char anotherCity[5] = {'E', 't', 'n', 'a', '\0'}; printf("A City %s\n\n", anotherCity); // Creating the string like before is easier // No quotes and an automatic null at the end char thirdCity[] = "Paris"; // Once an array is defined we can change the value with // strcpy() but make sure if you do that that the new // array is of the same size, or less. Otherwise you will // overwrite other data in memory. // You have to make your arrays big enough to hold all // potential input, but don't over do it, or you'll consume // to much memory. char yourCity[30]; printf("What city do you live in? "); // scanf() is kind of limited for adding a string to an array // 1. It will allow you to overwrite data past the end of // the space allowed // 2. It won't allow you to enter spaces unless you define // exactly how they will be entered // fgets() has neither of these problems and it also adds a // \0 at the end for you. The only negative is that you must // provide a size limit for the data being entered fgets(yourCity, 30, stdin); printf("Hello %s\n\n", yourCity); // fgets() Will read in everything up till the end of the array // is reached or until a \n is entered and then it will add // a \0 at the end. It leaves in the \n though which can be // a bad thing. // Let's get rid of the '\n' // Use -std=c99 since we are initializing i below in the for for(int i = 0; i < 30; i++){ if(yourCity[i] == '\n'){ yourCity[i] = '\0'; break; } } printf("Hello %s\n\n", yourCity); // Some string functions available // strcmp() takes 2 strings and returns a negative number // if the first string is less then the second. It returns // a positive if the opposite occurs. It returns a 0 if // they are equal printf("Is your city Paris? %d\n\n", strcmp(yourCity, thirdCity)); // strcat() adds the second string to the end of the first char yourState[] = ", Pennsylvania"; strcat(yourCity, yourState); printf("You live in %s\n\n", yourCity); // strlen() returns the length of the string minus \0 printf("Letters in Paris : %d\n\n", strlen(thirdCity)); // As mentioned before strcpy() is bad for copying strings // because it can overwrite memory. // That is were strlcpy() comes in. // It won't overwrite memory and it always adds a \0 strlcpy(yourCity, "El Pueblo del la Reina de Los Angeles", sizeof(yourCity)); printf("The new name is %s\n\n", yourCity); }
CTutorial3_3.c
#include <stdio.h> // Needed for exit(), rand() #include <stdlib.h> // I'm a global variable. Every function can see me and change // my value. int globalVar = 0; // Each function has a return type // (void if nothing is returned) // Between the parentheses you can define the type and number // of attributes passed to the function if any int addTwoInts(int num1, int num2){ // return the result to the function that called this one return num1 + num2; } void changeVariables(){ // This variable is local and doesn't exist outside // of this function even if it has the same name // as a variable outside of this function int age = 40; printf("age inside of function = %d\n\n", age); // Since globalVar is accessible in any function though // can change it for all other functions globalVar = 100; printf("globalVar inside of function = %d\n\n", globalVar); } void main(){ // FUNCTIONS ------------------ // If you want to some day make a big program you will // have to step out of main(). // With a complex program you are going to want to write // a function for each task required // How to call a function and pass data by value to it int total = addTwoInts(4,5); printf("The Sum is %d\n\n", total); // GLOBAL VS LOCAL VARIABLES ------ // That brings us to the concept of local versus global // variables. // This age variable is local to main() int age = 10; // I changed the global variable globalVar here to 50 globalVar = 50; printf("age before a call to the function = %d\n\n", age); printf("globalVar before a call to the function = %d\n\n", globalVar); changeVariables(); printf("age after a call to the function = %d\n\n", age); printf("globalVar after a call to the function = %d\n\n", globalVar); }
derek sir wanted to learn web development so could u plz guide me which of your tutorial I should take and their order.
thanku
Check out this page I made Web Design Course. All my videos are on that one short page. Follow them in order, but feel free to skip XML and come back to it when you need it. You can also learn either javascript or php in either order. I hope that helps 🙂
When I try the strlcpy function I get the error: undefined reference to strlcpy.
I read that strlcpy is not standard c. do I need additional header files
Use this #include and the error will go away | http://www.newthinktank.com/2013/07/c-video-tutorial-3/ | CC-MAIN-2019-18 | refinedweb | 1,250 | 63.43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.