Search Results

Search found 36179 results on 1448 pages for 'generic list'.

Page 5/1448 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • 'Generic' ViewModel

    - by Ian MacPherson
    Using EF 4, I have several subtypes of a 'Business' entity (customers, suppliers, haulage companies etc). They DO need to be subtypes. I am building a general viewmodel which calls into a service from which a generic repository is accessed. As I have 4 subtypes, it would be good to have a 'generic' viewmodel used for all of these. Problem is of course is that I have to call a specific type into my generic repository, for example: BusinessToRetrieve = _repository .LoadEntity<Customer>(o => o.CustomerID == customerID); It would be good to be able to call <SomethingElse>, somethingElse being one or other of the subtypes), otherwise I shall have to create 4 near identical viemodels, which seems a waste of course! The subtype entity name is available to the viewmodel but I've been unable to figure out how to make the above call convert this into a type. An issue with achieving what I want is that presumably the lambda expression being passed in wouldn't be able to resolve on a 'generic' call ?

    Read the article

  • Django generic relation field reports that all() is getting unexpected keyword argument when no args

    - by Joshua
    I have a model which can be attached to to other models. class Attachable(models.Model): content_type = models.ForeignKey(ContentType) object_pk = models.TextField() content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk") class Meta: abstract = True class Flag(Attachable): user = models.ForeignKey(User) flag = models.SlugField() timestamp = models.DateTimeField() I'm creating a generic relationship to this model in another model. flags = generic.GenericRelation(Flag) I try to get objects from this generic relation like so: self.flags.all() This results in the following exception: >>> obj.flags.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all return self.get_query_set() File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set return superclass.get_query_set(self).filter(**query) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q can_reuse=used_aliases) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter negate=negate, process_extras=process_extras) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins "Choices are: %s" % (name, ", ".join(names))) FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user >>> obj.flags.all(object_pk=obj.pk) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: all() got an unexpected keyword argument 'object_pk' What have I done wrong?

    Read the article

  • When/Why ( if ever ) should i think about doing Generic Programming/Meta Programming

    - by hotadvice
    Hi there IMHO to me OOPS, design patterns make sense and i have been able to apply them practically. But when it comes to "generic programming /meta programming" of the Modern C++ kind, i am left confused. -- Is it a new programming/design paradigm ? -- Is it just limited to "library development"? If not, What design/coding situations call for using meta programming/generic programming. -- Does using templates mean i am doing generic programming? I have googled a lot on this topic but do not grasp the BIG PICTURE fully. Also see this post. After reading dicussions here under, up till now, I am sure ( might still not be correct): a) Generic programming and meta programming are two different concepts.

    Read the article

  • Search one element of a list in another list recursively

    - by androidnoob
    I have 2 lists old_name_list = [a-1234, a-1235, a-1236] new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ] I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes. I have tried the following and it doesn't work for old_name, new_name in zip(old_name_list, new_name_list): if old_name in new_name[0]: print new_name[1] Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.

    Read the article

  • setting up linked list Java

    - by erp
    I'm working on some basic linked list stuff, like insert, delete, go to the front or end of the list, and basically i understand the concept of all of that stuff once i have the list i guess but im having trouble setting up the list. I was wondering of you guys could tell me if im going in the right direction. (mostly just the setup) this is what i have so far: public class List { private int size; private List linkedList; List head; List cur; List next; /** * Creates an empty list. * @pre * @post */ public List(){ linkedList = new List(); this.head = null; cur = head; } /** * Delete the current element from this list. The element after the deleted element becomes the new current. * If that's not possible, then the element before the deleted element becomes the new current. * If that is also not possible, then you need to recognize what state the list is in and define current accordingly. * Nothing should be done if a delete is not possible. * @pre * @post */ public void delete(){ // delete size--; } /** * Get the value of the current element. If this is not possible, throw an IllegalArgumentException. * @pre the list is not empty * @post * @return value of the current element. */ public char get(){ return getItem(cur); } /** * Go to the last element of the list. If this is not possible, don't change the cursor. * @pre * @post */ public void goLast(){ while (cur.next != null){ cur = cur.next; } } /** * Advance the cursor to the next element. If this is not possible, don't change the cursor. * @pre * @post */ public void goNext(){ if(cur.next != null){ cur = cur.next;} //else do nothing } /** * Retreat the cursor to the previous element. If this is not possible, don't change the cursor. * @pre * @post */ public void goPrev(){ } /** * Go to top of the list. This is the position before the first element. * @pre * @post */ public void goTop(){ } /** * Go to first element of the list. If this is not possible, don't change the cursor. * @pre * @post */ public void goFirst(){ } /** * Insert the given parameter after the current element. The newly inserted element becomes the current element. * @pre * @post * @param newVal : value to insert after the current element. */ public void insert(char newVal){ cur.setItem(newVal); size++; } /** * Determines if this list is empty. Empty means this list has no elements. * @pre * @post * @return true if the list is empty. */ public boolean isEmpty(){ return head == null; } /** * Determines the size of the list. The size of the list is the number of elements in the list. * @pre * @post * @return size which is the number of elements in the list. */ public int size(){ return size; } public class Node { private char item; private Node next; public Node() { } public Node(char item) { this.item = item; } public Node(char item, Node next) { this.item = item; this.next = next; } public char getItem() { return this.item; } public void setItem(char item) { this.item = item; } public Node getNext() { return this.next; } public void setNext(Node next) { this.next = next; } } } I got the node class alright (well i think it works alright), but is it necessary to even have that class? or can i go about it without even using it (just curious). And for example on the method get() in the list class can i not call that getItem() method from the node class because it's getting an error even though i thought that was the whole point for the node class. bottom line i just wanna make sure im setting up the list right. Thanks for any help guys, im new to linked list's so bear with me!

    Read the article

  • How to get rid of grub menu after boot?

    - by umpirsky
    Here is my /etc/default/grub: # If you change this file, run 'update-grub' afterwards to update # /boot/grub/grub.cfg. GRUB_DEFAULT=0 GRUB_HIDDEN_TIMEOUT=0 GRUB_HIDDEN_TIMEOUT_QUIET=true GRUB_TIMEOUT=10 GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian` GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" GRUB_CMDLINE_LINUX="" # Uncomment to disable graphical terminal (grub-pc only) #GRUB_TERMINAL=console # The resolution used on graphical terminal # note that you can use only modes which your graphic card supports via VBE # you can see them in real GRUB with the command `vbeinfo' #GRUB_GFXMODE=640x480 # Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux #GRUB_DISABLE_LINUX_UUID=true # Uncomment to disable generation of recovery mode menu entries #GRUB_DISABLE_LINUX_RECOVERY="true" # Uncomment to get a beep at grub start #GRUB_INIT_TUNE="480 440 1" I tried various things including: How do I hide the GRUB menu showing up in the beginning of boot? How to disable Grub's menu from showing up after failed boot http://www.itworld.com/software/306238/disable-grub-boot-menu-ubuntu-1210 But I still get grub menu each time I boot. My generated /boot/grub/grub.cfg: # # DO NOT EDIT THIS FILE # # It is automatically generated by grub-mkconfig using templates # from /etc/grub.d and settings from /etc/default/grub # ### BEGIN /etc/grub.d/00_header ### if [ -s $prefix/grubenv ]; then set have_grubenv=true load_env fi if [ "${next_entry}" ] ; then set default="${next_entry}" set next_entry= save_env next_entry set boot_once=true else set default="0" fi if [ x"${feature_menuentry_id}" = xy ]; then menuentry_id_option="--id" else menuentry_id_option="" fi export menuentry_id_option if [ "${prev_saved_entry}" ]; then set saved_entry="${prev_saved_entry}" save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=true fi function savedefault { if [ -z "${boot_once}" ]; then saved_entry="${chosen}" save_env saved_entry fi } function recordfail { set recordfail=1 if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi } function load_video { if [ x$feature_all_video_module = xy ]; then insmod all_video else insmod efi_gop insmod efi_uga insmod ieee1275_fb insmod vbe insmod vga insmod video_bochs insmod video_cirrus fi } if [ x$feature_default_font_path = xy ] ; then font=unicode else insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi font="/usr/share/grub/unicode.pf2" fi if loadfont $font ; then set gfxmode=auto load_video insmod gfxterm set locale_dir=$prefix/locale set lang=en_US insmod gettext fi terminal_output gfxterm if [ "${recordfail}" = 1 ] ; then set timeout=-1 else if [ x$feature_timeout_style = xy ] ; then set timeout_style=hidden set timeout=0 # Fallback hidden-timeout code in case the timeout_style feature is # unavailable. elif sleep --interruptible 0 ; then set timeout=0 fi fi ### END /etc/grub.d/00_header ### ### BEGIN /etc/grub.d/05_debian_theme ### set menu_color_normal=white/black set menu_color_highlight=black/light-gray if background_color 45,51,53; then clear fi ### END /etc/grub.d/05_debian_theme ### ### BEGIN /etc/grub.d/10_linux ### function gfxmode { set gfxpayload="${1}" if [ "${1}" = "keep" ]; then set vt_handoff=vt.handoff=7 else set vt_handoff= fi } if [ "${recordfail}" != 1 ]; then if [ -e ${prefix}/gfxblacklist.txt ]; then if hwmatch ${prefix}/gfxblacklist.txt 3; then if [ ${match} = 0 ]; then set linux_gfx_mode=keep else set linux_gfx_mode=text fi else set linux_gfx_mode=text fi else set linux_gfx_mode=keep fi else set linux_gfx_mode=text fi export linux_gfx_mode menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-ed6b32bc-ec1d-444c-a000-282fddd6d460' { recordfail load_video gfxmode $linux_gfx_mode insmod gzio insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro quiet splash $vt_handoff initrd /boot/initrd.img-3.13.0-29-generic } submenu 'Advanced options for Ubuntu' $menuentry_id_option 'gnulinux-advanced-ed6b32bc-ec1d-444c-a000-282fddd6d460' { menuentry 'Ubuntu, with Linux 3.13.0-29-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.13.0-29-generic-advanced-ed6b32bc-ec1d-444c-a000-282fddd6d460' { recordfail load_video gfxmode $linux_gfx_mode insmod gzio insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi echo 'Loading Linux 3.13.0-29-generic ...' linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro quiet splash $vt_handoff echo 'Loading initial ramdisk ...' initrd /boot/initrd.img-3.13.0-29-generic } menuentry 'Ubuntu, with Linux 3.13.0-29-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.13.0-29-generic-recovery-ed6b32bc-ec1d-444c-a000-282fddd6d460' { recordfail load_video insmod gzio insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi echo 'Loading Linux 3.13.0-29-generic ...' linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro recovery nomodeset echo 'Loading initial ramdisk ...' initrd /boot/initrd.img-3.13.0-29-generic } menuentry 'Ubuntu, with Linux 3.13.0-24-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.13.0-24-generic-advanced-ed6b32bc-ec1d-444c-a000-282fddd6d460' { recordfail load_video gfxmode $linux_gfx_mode insmod gzio insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi echo 'Loading Linux 3.13.0-24-generic ...' linux /boot/vmlinuz-3.13.0-24-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro quiet splash $vt_handoff echo 'Loading initial ramdisk ...' initrd /boot/initrd.img-3.13.0-24-generic } menuentry 'Ubuntu, with Linux 3.13.0-24-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.13.0-24-generic-recovery-ed6b32bc-ec1d-444c-a000-282fddd6d460' { recordfail load_video insmod gzio insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi echo 'Loading Linux 3.13.0-24-generic ...' linux /boot/vmlinuz-3.13.0-24-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro recovery nomodeset echo 'Loading initial ramdisk ...' initrd /boot/initrd.img-3.13.0-24-generic } } ### END /etc/grub.d/10_linux ### ### BEGIN /etc/grub.d/20_linux_xen ### ### END /etc/grub.d/20_linux_xen ### ### BEGIN /etc/grub.d/20_memtest86+ ### ### END /etc/grub.d/20_memtest86+ ### ### BEGIN /etc/grub.d/30_os-prober ### menuentry 'Ubuntu 14.04 LTS (14.04) (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' --class gnu-linux --class gnu --class os $menuentry_id_option 'osprober-gnulinux-simple-ed6b32bc-ec1d-444c-a000-282fddd6d460' { insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro splash quiet quiet splash $vt_handoff initrd /boot/initrd.img-3.13.0-29-generic } submenu 'Advanced options for Ubuntu 14.04 LTS (14.04) (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' $menuentry_id_option 'osprober-gnulinux-advanced-ed6b32bc-ec1d-444c-a000-282fddd6d460' { menuentry 'Ubuntu (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' --class gnu-linux --class gnu --class os $menuentry_id_option 'osprober-gnulinux-/boot/vmlinuz-3.13.0-29-generic.efi.signed--ed6b32bc-ec1d-444c-a000-282fddd6d460' { insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro splash quiet quiet splash $vt_handoff initrd /boot/initrd.img-3.13.0-29-generic } menuentry 'Ubuntu, with Linux 3.13.0-29-generic (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' --class gnu-linux --class gnu --class os $menuentry_id_option 'osprober-gnulinux-/boot/vmlinuz-3.13.0-29-generic.efi.signed--ed6b32bc-ec1d-444c-a000-282fddd6d460' { insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro splash quiet quiet splash $vt_handoff initrd /boot/initrd.img-3.13.0-29-generic } menuentry 'Ubuntu, with Linux 3.13.0-29-generic (recovery mode) (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' --class gnu-linux --class gnu --class os $menuentry_id_option 'osprober-gnulinux-/boot/vmlinuz-3.13.0-29-generic.efi.signed-root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro recovery nomodeset splash quiet-ed6b32bc-ec1d-444c-a000-282fddd6d460' { insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-29-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro recovery nomodeset splash quiet initrd /boot/initrd.img-3.13.0-29-generic } menuentry 'Ubuntu, with Linux 3.13.0-24-generic (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' --class gnu-linux --class gnu --class os $menuentry_id_option 'osprober-gnulinux-/boot/vmlinuz-3.13.0-24-generic.efi.signed--ed6b32bc-ec1d-444c-a000-282fddd6d460' { insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-24-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro splash quiet quiet splash $vt_handoff initrd /boot/initrd.img-3.13.0-24-generic } menuentry 'Ubuntu, with Linux 3.13.0-24-generic (recovery mode) (on /dev/mapper/isw_beaaegcdjh_ASUS_OS2)' --class gnu-linux --class gnu --class os $menuentry_id_option 'osprober-gnulinux-/boot/vmlinuz-3.13.0-24-generic.efi.signed-root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro recovery nomodeset splash quiet-ed6b32bc-ec1d-444c-a000-282fddd6d460' { insmod part_gpt insmod ext2 if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 else search --no-floppy --fs-uuid --set=root ed6b32bc-ec1d-444c-a000-282fddd6d460 fi linux /boot/vmlinuz-3.13.0-24-generic.efi.signed root=UUID=ed6b32bc-ec1d-444c-a000-282fddd6d460 ro recovery nomodeset splash quiet initrd /boot/initrd.img-3.13.0-24-generic } } set timeout_style=menu if [ "${timeout}" = 0 ]; then set timeout=10 fi ### END /etc/grub.d/30_os-prober ### ### BEGIN /etc/grub.d/30_uefi-firmware ### menuentry 'System setup' $menuentry_id_option 'uefi-firmware' { fwsetup } ### END /etc/grub.d/30_uefi-firmware ### ### BEGIN /etc/grub.d/40_custom ### # This file provides an easy way to add custom menu entries. Simply type the # menu entries you want to add after this comment. Be careful not to change # the 'exec tail' line above. ### END /etc/grub.d/40_custom ### ### BEGIN /etc/grub.d/41_custom ### if [ -f ${config_directory}/custom.cfg ]; then source ${config_directory}/custom.cfg elif [ -z "${config_directory}" -a -f $prefix/custom.cfg ]; then source $prefix/custom.cfg; fi ### END /etc/grub.d/41_custom ###

    Read the article

  • What You Said: What’s on Your Geeky Christmas List

    - by Jason Fitzpatrick
    Earlier this week we asked you to share what’s on your geeky Christmas list; you responded and we’re back to share your longed for tech goodies. The most requested item was this year’s hot introduction to the project board market: the Raspberry Pi. Dave writes: A Rapsberry Pi to tinker with, especially to see if I can get it up and running with OpenElec/Raspbmc and a torrent client for a low power media centre/htpc We just finished setting up a batch of new 512MB Raspberry Pi systems running the newest release of Rasbmbc and can’t recommend it enough–new refinements in Raspbmc and the extra 256MB of RAM really improve the media center experience. All John wants is a real keyboard so he can escape the torture of using a touch screen: How to Factory Reset Your Android Phone or Tablet When It Won’t Boot Our Geek Trivia App for Windows 8 is Now Available Everywhere How To Boot Your Android Phone or Tablet Into Safe Mode

    Read the article

  • Dynamic Code for type casting Generic Types 'generically' in C#

    - by Rick Strahl
    C# is a strongly typed language and while that's a fundamental feature of the language there are more and more situations where dynamic types make a lot of sense. I've written quite a bit about how I use dynamic for creating new type extensions: Dynamic Types and DynamicObject References in C# Creating a dynamic, extensible C# Expando Object Creating a dynamic DataReader for dynamic Property Access Today I want to point out an example of a much simpler usage for dynamic that I use occasionally to get around potential static typing issues in C# code especially those concerning generic types. TypeCasting Generics Generic types have been around since .NET 2.0 I've run into a number of situations in the past - especially with generic types that don't implement specific interfaces that can be cast to - where I've been unable to properly cast an object when it's passed to a method or assigned to a property. Granted often this can be a sign of bad design, but in at least some situations the code that needs to be integrated is not under my control so I have to make due with what's available or the parent object is too complex or intermingled to be easily refactored to a new usage scenario. Here's an example that I ran into in my own RazorHosting library - so I have really no excuse, but I also don't see another clean way around it in this case. A Generic Example Imagine I've implemented a generic type like this: public class RazorEngine<TBaseTemplateType> where TBaseTemplateType : RazorTemplateBase, new() You can now happily instantiate new generic versions of this type with custom template bases or even a non-generic version which is implemented like this: public class RazorEngine : RazorEngine<RazorTemplateBase> { public RazorEngine() : base() { } } To instantiate one: var engine = new RazorEngine<MyCustomRazorTemplate>(); Now imagine that the template class receives a reference to the engine when it's instantiated. This code is fired as part of the Engine pipeline when it gets ready to execute the template. It instantiates the template and assigns itself to the template: var template = new TBaseTemplateType() { Engine = this } The problem here is that possibly many variations of RazorEngine<T> can be passed. I can have RazorTemplateBase, RazorFolderHostTemplateBase, CustomRazorTemplateBase etc. as generic parameters and the Engine property has to reflect that somehow. So, how would I cast that? My first inclination was to use an interface on the engine class and then cast to the interface.  Generally that works, but unfortunately here the engine class is generic and has a few members that require the template type in the member signatures. So while I certainly can implement an interface: public interface IRazorEngine<TBaseTemplateType> it doesn't really help for passing this generically templated object to the template class - I still can't cast it if multiple differently typed versions of the generic type could be passed. I have the exact same issue in that I can't specify a 'generic' generic parameter, since there's no underlying base type that's common. In light of this I decided on using object and the following syntax for the property (and the same would be true for a method parameter): public class RazorTemplateBase :MarshalByRefObject,IDisposable { public object Engine {get;set; } } Now because the Engine property is a non-typed object, when I need to do something with this value, I still have no way to cast it explicitly. What I really would need is: public RazorEngine<> Engine { get; set; } but that's not possible. Dynamic to the Rescue Luckily with the dynamic type this sort of thing can be mitigated fairly easily. For example here's a method that uses the Engine property and uses the well known class interface by simply casting the plain object reference to dynamic and then firing away on the properties and methods of the base template class that are common to all templates:/// <summary> /// Allows rendering a dynamic template from a string template /// passing in a model. This is like rendering a partial /// but providing the input as a /// </summary> public virtual string RenderTemplate(string template,object model) { if (template == null) return string.Empty; // if there's no template markup if(!template.Contains("@")) return template; // use dynamic to get around generic type casting dynamic engine = Engine; string result = engine.RenderTemplate(template, model); if (result == null) throw new ApplicationException("RenderTemplate failed: " + engine.ErrorMessage); return result; } Prior to .NET 4.0  I would have had to use Reflection for this sort of thing which would have a been a heck of a lot more verbose, but dynamic makes this so much easier and cleaner and in this case at least the overhead is negliable since it's a single dynamic operation on an otherwise very complex operation call. Dynamic as  a Bailout Sometimes this sort of thing often reeks of a design flaw, and I agree that in hindsight this could have been designed differently. But as is often the case this particular scenario wasn't planned for originally and removing the generic signatures from the base type would break a ton of other code in the framework. Given the existing fairly complex engine design, refactoring an interface to remove generic types just to make this particular code work would have been overkill. Instead dynamic provides a nice and simple and relatively clean solution. Now if there were many other places where this occurs I would probably consider reworking the code to make this cleaner but given this isolated instance and relatively low profile operation use of dynamic seems a valid choice for me. This solution really works anywhere where you might end up with an inheritance structure that doesn't have a common base or interface that is sufficient. In the example above I know what I'm getting but there's no common base type that I can cast to. All that said, it's a good idea to think about use of dynamic before you rush in. In many situations there are alternatives that can still work with static typing. Dynamic definitely has some overhead compared to direct static access of objects, so if possible we should definitely stick to static typing. In the example above the application already uses dynamics extensively for dynamic page page templating and passing models around so introducing dynamics here has very little additional overhead. The operation itself also fires of a fairly resource heavy operation where the overhead of a couple of dynamic member accesses are not a performance issue. So, what's your experience with dynamic as a bailout mechanism? © Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Filter any mailing list in GMail using the "list:" meta-data

    - by Binary255
    Hi, If I ask GMail to create a filter for a mailing list it creates a rule containing list:mailing-list-identifier, in the case of the NAnt mailing list it wrote: Has the words: list: "nant-users.lists.sourceforge.net" Is there a way to filter any mailing list? I would like to filter conversations from any mailing list containing answers to things I've previously asked (or answered to). Part of that filter is identifying "anything which is part of a mailing list" and I'm wondering if there is a better way than adding another label to all mailing list posts (which is cumbersome).

    Read the article

  • SharePoint logging to a list

    - by Norgean
    I recently worked in an environment with several servers. Locating the correct SharePoint log file for error messages, or development trace calls, is cumbersome. And once the solution hit the cloud, it got even worse, as we had no access to the log files at all. Obviously we are not the only ones with this problem, and the current trend seems to be to log to a list. This had become an off-hour project, so rather than do the sensible thing and find a ready-made solution, I decided to do it the hard way. So! Fire up Visual Studio, create yet another empty SharePoint solution, and start to think of some requirements. Easy on/offI want to be able to turn list-logging on and off.Easy loggingFor me, this means being able to use string.Format.Easy filteringLet's have the possibility to add some filtering columns; category and severity, where severity can be "verbose", "warning" or "error". Easy on/off Well, that's easy. Create a new web feature. Add an event receiver, and create the list on activation of the feature. Tear the list down on de-activation. I chose not to create a new content type; I did not feel that it would give me anything extra. I based the list on the generic list - I think a better choice would have been the announcement type. Approximately: public void CreateLog(SPWeb web)         {             var list = web.Lists.TryGetList(LogListName);             if (list == null)             {                 var listGuid = web.Lists.Add(LogListName, "Logging for the masses", SPListTemplateType.GenericList);                 list = web.Lists[listGuid];                 list.Title = LogListTitle;                 list.Update();                 list.Fields.Add(Category, SPFieldType.Text, false);                 var stringColl = new StringCollection();                 stringColl.AddRange(new[]{Error, Information, Verbose});                 list.Fields.Add(Severity, SPFieldType.Choice, true, false, stringColl);                 ModifyDefaultView(list);             }         }Should be self explanatory, but: only create the list if it does not already exist (d'oh). Best practice: create it with a Url-friendly name, and, if necessary, give it a better title. ...because otherwise you'll have to look for a list with a name like "Simple_x0020_Log". I've added a couple of fields; a field for category, and a 'severity'. Both to make it easier to find relevant log messages. Notice that I don't have to call list.Update() after adding the fields - this would cause a nasty error (something along the lines of "List locked by another user"). The function for deleting the log is exactly as onerous as you'd expect:         public void DeleteLog(SPWeb web)         {             var list = web.Lists.TryGetList(LogListTitle);             if (list != null)             {                 list.Delete();             }         } So! "All" that remains is to log. Also known as adding items to a list. Lots of different methods with different signatures end up calling the same function. For example, LogVerbose(web, message) calls LogVerbose(web, null, message) which again calls another method which calls: private static void Log(SPWeb web, string category, string severity, string textformat, params object[] texts)         {             if (web != null)             {                 var list = web.Lists.TryGetList(LogListTitle);                 if (list != null)                 {                     var item = list.AddItem(); // NOTE! NOT list.Items.Add… just don't, mkay?                     var text = string.Format(textformat, texts);                     if (text.Length > 255) // because the title field only holds so many chars. Sigh.                         text = text.Substring(0, 254);                     item[SPBuiltInFieldId.Title] = text;                     item[Degree] = severity;                     item[Category] = category;                     item.Update();                 }             } // omitted: Also log to SharePoint log.         } By adding a params parameter I can call it as if I was doing a Console.WriteLine: LogVerbose(web, "demo", "{0} {1}{2}", "hello", "world", '!'); Ok, that was a silly example, a better one might be: LogError(web, LogCategory, "Exception caught when updating {0}. exception: {1}", listItem.Title, ex); For performance reasons I use list.AddItem rather than list.Items.Add. For completeness' sake, let us include the "ModifyDefaultView" function that I deliberately skipped earlier.         private void ModifyDefaultView(SPList list)         {             // Add fields to default view             var defaultView = list.DefaultView;             var exists = defaultView.ViewFields.Cast<string>().Any(field => String.CompareOrdinal(field, Severity) == 0);               if (!exists)             {                 var field = list.Fields.GetFieldByInternalName(Severity);                 if (field != null)                     defaultView.ViewFields.Add(field);                 field = list.Fields.GetFieldByInternalName(Category);                 if (field != null)                     defaultView.ViewFields.Add(field);                 defaultView.Update();                   var sortDoc = new XmlDocument();                 sortDoc.LoadXml(string.Format("<Query>{0}</Query>", defaultView.Query));                 var orderBy = (XmlElement) sortDoc.SelectSingleNode("//OrderBy");                 if (orderBy != null && sortDoc.DocumentElement != null)                     sortDoc.DocumentElement.RemoveChild(orderBy);                 orderBy = sortDoc.CreateElement("OrderBy");                 sortDoc.DocumentElement.AppendChild(orderBy);                 field = list.Fields[SPBuiltInFieldId.Modified];                 var fieldRef = sortDoc.CreateElement("FieldRef");                 fieldRef.SetAttribute("Name", field.InternalName);                 fieldRef.SetAttribute("Ascending", "FALSE");                 orderBy.AppendChild(fieldRef);                   fieldRef = sortDoc.CreateElement("FieldRef");                 field = list.Fields[SPBuiltInFieldId.ID];                 fieldRef.SetAttribute("Name", field.InternalName);                 fieldRef.SetAttribute("Ascending", "FALSE");                 orderBy.AppendChild(fieldRef);                 defaultView.Query = sortDoc.DocumentElement.InnerXml;                 //defaultView.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE' /><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>";                 defaultView.Update();             }         } First two lines are easy - see if the default view includes the "Severity" column. If it does - quit; our job here is done.Adding "severity" and "Category" to the view is not exactly rocket science. But then? Then we build the sort order query. Through XML. The lines are numerous, but boring. All to achieve the CAML query which is commented out. The major benefit of using the dom to build XML, is that you may get compile time errors for spelling mistakes. I say 'may', because although the compiler will not let you forget to close a tag, it will cheerfully let you spell "Name" as "Naem". Whichever you prefer, at the end of the day the view will sort by modified date and ID, both descending. I added the ID as there may be several items with the same time stamp. So! Simple logging to a list, with sensible a view, and with normal functionality for creating your own filterings. I should probably have added some more views in code, ready filtered for "only errors", "errors and warnings" etc. And it would be nice to block verbose logging completely, but I'm not happy with the alternatives. (yetanotherfeature or an admin page seem like overkill - perhaps just removing it as one of the choices, and not log if it isn't there?) Before you comment - yes, try-catches have been removed for clarity. There is nothing worse than having a logging function that breaks your site!

    Read the article

  • linq2sql : get generic type of table

    - by benpage
    i think this is a simple question but I've searched around and can't seem to find an answer easily. if you have var list = List<int>(); ... fill list ... and you want to get the generic type in list, i realise you could just type: var t = list.FirstOrDefault().GetType(); Is there another way to do this via just the list, rather than referring to the enumeration? Reason is, i have a System.Data.Linq.Table<TABLE1> and what i want to do is get the type of TABLE1 from it. so: var table = new DataContext().TABLE1s; // this is Table<TABLE1> var tableType = table.GetType().SomeMethod(); // i want tableType to equal TABLE1.GetType()

    Read the article

  • java: List wrapper where get()/set() is allowed but add/remove is not

    - by Jason S
    I need to wrap a List<T> with some class that allows calls to set/get but does not allow add/remove calls, so that the list remains "stuck" at a fixed length. I think I have a thin wrapper class (below) that will work, but I'm not 100% positive. Did I miss anything obvious? import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; class RestrictedListWrapper<T> implements List<T> { static <T> T fail() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } static private class IteratorWrapper<T> implements ListIterator<T> { final private ListIterator<T> iter; private IteratorWrapper(ListIterator<T> iter) { this.iter = iter; } static public <T> RestrictedListWrapper.IteratorWrapper<T> wrap(ListIterator<T> target) { return new RestrictedListWrapper.IteratorWrapper<T>(target); } @Override public void add(T e) { fail(); } @Override public boolean hasNext() { return this.iter.hasNext(); } @Override public boolean hasPrevious() { return this.iter.hasPrevious(); } @Override public T next() { return this.iter.next(); } @Override public int nextIndex() { return this.iter.nextIndex(); } @Override public T previous() { return this.iter.previous(); } @Override public int previousIndex() { return this.iter.previousIndex(); } @Override public void remove() { fail(); } @Override public void set(T e) { this.iter.set(e); } } final private List<T> list; private RestrictedListWrapper(List<T> list) { this.list = list; } static public <T> RestrictedListWrapper<T> wrap(List<T> target) { return new RestrictedListWrapper<T>(target); } @Override public boolean add(T arg0) { return fail(); } @Override public void add(int index, T element) { fail(); } @Override public boolean addAll(Collection<? extends T> arg0) { return fail(); } @Override public boolean addAll(int arg0, Collection<? extends T> arg1) { return fail(); } /** * clear() allows setting all members of the list to null */ @Override public void clear() { ListIterator<T> it = this.list.listIterator(); while (it.hasNext()) { it.set(null); it.next(); } } @Override public boolean contains(Object o) { return this.list.contains(o); } @Override public boolean containsAll(Collection<?> c) { return this.list.containsAll(c); } @Override public T get(int index) { return this.list.get(index); } @Override public int indexOf(Object o) { return this.list.indexOf(o); } @Override public boolean isEmpty() { return false; } @Override public Iterator<T> iterator() { return listIterator(); } @Override public int lastIndexOf(Object o) { return this.list.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return IteratorWrapper.wrap(this.list.listIterator()); } @Override public ListIterator<T> listIterator(int index) { return IteratorWrapper.wrap(this.list.listIterator(index)); } @Override public boolean remove(Object o) { return fail(); } @Override public T remove(int index) { fail(); return fail(); } @Override public boolean removeAll(Collection<?> c) { return fail(); } @Override public boolean retainAll(Collection<?> c) { return fail(); } @Override public T set(int index, T element) { return this.list.set(index, element); } @Override public int size() { return this.list.size(); } @Override public List<T> subList(int fromIndex, int toIndex) { return new RestrictedListWrapper<T>(this.list.subList(fromIndex, toIndex)); } @Override public Object[] toArray() { return this.list.toArray(); } @Override public <T> T[] toArray(T[] a) { return this.list.toArray(a); } }

    Read the article

  • Using a "white list" for extracting terms for Text Mining, Part 2

    - by [email protected]
    In my last post, we set the groundwork for extracting specific tokens from a white list using a CTXRULE index. In this post, we will populate a table with the extracted tokens and produce a case table suitable for clustering with Oracle Data Mining. Our corpus of documents will be stored in a database table that is defined as create table documents(id NUMBER, text VARCHAR2(4000)); However, any suitable Oracle Text-accepted data type can be used for the text. We then create a table to contain the extracted tokens. The id column contains the unique identifier (or case id) of the document. The token column contains the extracted token. Note that a given document many have many tokens, so there will be one row per token for a given document. create table extracted_tokens (id NUMBER, token VARCHAR2(4000)); The next step is to iterate over the documents and extract the matching tokens using the index and insert them into our token table. We use the MATCHES function for matching the query_string from my_thesaurus_rules with the text. DECLARE     cursor c2 is       select id, text       from documents; BEGIN     for r_c2 in c2 loop        insert into extracted_tokens          select r_c2.id id, main_term token          from my_thesaurus_rules          where matches(query_string,                        r_c2.text)>0;     end loop; END; Now that we have the tokens, we can compute the term frequency - inverse document frequency (TF-IDF) for each token of each document. create table extracted_tokens_tfidf as   with num_docs as (select count(distinct id) doc_cnt                     from extracted_tokens),        tf       as (select a.id, a.token,                            a.token_cnt/b.num_tokens token_freq                     from                        (select id, token, count(*) token_cnt                        from extracted_tokens                        group by id, token) a,                       (select id, count(*) num_tokens                        from extracted_tokens                        group by id) b                     where a.id=b.id),        doc_freq as (select token, count(*) overall_token_cnt                     from extracted_tokens                     group by token)   select tf.id, tf.token,          token_freq * ln(doc_cnt/df.overall_token_cnt) tf_idf   from num_docs,        tf,        doc_freq df   where df.token=tf.token; From the WITH clause, the num_docs query simply counts the number of documents in the corpus. The tf query computes the term (token) frequency by computing the number of times each token appears in a document and divides that by the number of tokens found in the document. The doc_req query counts the number of times the token appears overall in the corpus. In the SELECT clause, we compute the tf_idf. Next, we create the nested table required to produce one record per case, where a case corresponds to an individual document. Here, we COLLECT all the tokens for a given document into the nested column extracted_tokens_tfidf_1. CREATE TABLE extracted_tokens_tfidf_nt              NESTED TABLE extracted_tokens_tfidf_1                  STORE AS extracted_tokens_tfidf_tab AS              select id,                     cast(collect(DM_NESTED_NUMERICAL(token,tf_idf)) as DM_NESTED_NUMERICALS) extracted_tokens_tfidf_1              from extracted_tokens_tfidf              group by id;   To build the clustering model, we create a settings table and then insert the various settings. Most notable are the number of clusters (20), using cosine distance which is better for text, turning off auto data preparation since the values are ready for mining, the number of iterations (20) to get a better model, and the split criterion of size for clusters that are roughly balanced in number of cases assigned. CREATE TABLE km_settings (setting_name  VARCHAR2(30), setting_value VARCHAR2(30)); BEGIN  INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.clus_num_clusters, 20);  INSERT INTO km_settings (setting_name, setting_value)     VALUES (dbms_data_mining.kmns_distance, dbms_data_mining.kmns_cosine);   INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.prep_auto,dbms_data_mining.prep_auto_off);   INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.kmns_iterations,20);   INSERT INTO km_settings (setting_name, setting_value) VALUES     VALUES (dbms_data_mining.kmns_split_criterion,dbms_data_mining.kmns_size);   COMMIT; END; With this in place, we can now build the clustering model. BEGIN     DBMS_DATA_MINING.CREATE_MODEL(     model_name          => 'TEXT_CLUSTERING_MODEL',     mining_function     => dbms_data_mining.clustering,     data_table_name     => 'extracted_tokens_tfidf_nt',     case_id_column_name => 'id',     settings_table_name => 'km_settings'); END;To generate cluster names from this model, check out my earlier post on that topic.

    Read the article

  • Finding duplicates in a list using recursion?

    - by user1760892
    I'm suppose to find if there is duplicates in a list and return true or false using recursion only (no loops). So if ArrayList of char is used, [a,b,c,d,e] should return false. [a,a,b,c,d] or [a,b,b,c,c,d] should return true. I've tried and tested different ways and it worked for some cases but not all. I changed my code around and this is what I have now. (Has problem at the last if statement) Can anyone give me some hints? Thanks. public static <T> boolean duplicate(List<T> list) throws NullPointerException { return duplicateHelper(list, list.get(0)); } public static <T> boolean duplicateHelper(List<T> list, T t){ if (list == null) throw new NullPointerException(); if(list.isEmpty()) return false; if(list.size() > 1){ if(t.equals(list.get(1))) return true; } if(list.size() == 1) return false; if(!duplicateHelper(list.subList(1,list.size()), t)){ return duplicate(list.subList(1,list.size())); } return false; }

    Read the article

  • Help with understanding generic relations in Django (and usage in Admin)

    - by saturdayplace
    I'm building a CMS for my company's website (I've looked at the existing Django solutions and want something that's much slimmer/simpler, and that handles our situation specifically.. Plus, I'd like to learn this stuff better). I'm having trouble wrapping my head around generic relations. I have a Page model, a SoftwareModule model, and some other models that define content on our website, each with their get_absolute_url() defined. I'd like for my users to be able to assign any Page instance a list of objects, of any type, including other page instances. This list will become that Page instance's sub-menu. I've tried the following: class Page(models.Model): body = models.TextField() links = generic.GenericRelation("LinkedItem") @models.permalink def get_absolute_url(self): # returns the right URL class LinkedItem(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') title = models.CharField(max_length=100) def __unicode__(self): return self.title class SoftwareModule(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): # returns the right URL This gets me a generic relation with an API to do page_instance.links.all(). We're on our way. What I'm not sure how to pull off, is on the page instance's change form, how to create the relationship between that page, and any other extant object in the database. My desired end result: to render the following in a template: <ul> {% for link in page.links.all %} <li><a href='{{ link.content_object.get_absolute_url() }}'>{{ link.title }}</a></li> {% endfor%} </ul> Obviously, there's something I'm unaware of or mis-understanding, but I feel like I'm, treading into that area where I don't know what I don't know. What am I missing?

    Read the article

  • C#/.NET Little Wonders: The Generic Func Delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Back in one of my three original “Little Wonders” Trilogy of posts, I had listed generic delegates as one of the Little Wonders of .NET.  Later, someone posted a comment saying said that they would love more detail on the generic delegates and their uses, since my original entry just scratched the surface of them. Last week, I began our look at some of the handy generic delegates built into .NET with a description of delegates in general, and the Action family of delegates.  For this week, I’ll launch into a look at the Func family of generic delegates and how they can be used to support generic, reusable algorithms and classes. Quick Delegate Recap Delegates are similar to function pointers in C++ in that they allow you to store a reference to a method.  They can store references to either static or instance methods, and can actually be used to chain several methods together in one delegate. Delegates are very type-safe and can be satisfied with any standard method, anonymous method, or a lambda expression.  They can also be null as well (refers to no method), so care should be taken to make sure that the delegate is not null before you invoke it. Delegates are defined using the keyword delegate, where the delegate’s type name is placed where you would typically place the method name: 1: // This delegate matches any method that takes string, returns nothing 2: public delegate void Log(string message); This delegate defines a delegate type named Log that can be used to store references to any method(s) that satisfies its signature (whether instance, static, lambda expression, etc.). Delegate instances then can be assigned zero (null) or more methods using the operator = which replaces the existing delegate chain, or by using the operator += which adds a method to the end of a delegate chain: 1: // creates a delegate instance named currentLogger defaulted to Console.WriteLine (static method) 2: Log currentLogger = Console.Out.WriteLine; 3:  4: // invokes the delegate, which writes to the console out 5: currentLogger("Hi Standard Out!"); 6:  7: // append a delegate to Console.Error.WriteLine to go to std error 8: currentLogger += Console.Error.WriteLine; 9:  10: // invokes the delegate chain and writes message to std out and std err 11: currentLogger("Hi Standard Out and Error!"); While delegates give us a lot of power, it can be cumbersome to re-create fairly standard delegate definitions repeatedly, for this purpose the generic delegates were introduced in various stages in .NET.  These support various method types with particular signatures. Note: a caveat with generic delegates is that while they can support multiple parameters, they do not match methods that contains ref or out parameters. If you want to a delegate to represent methods that takes ref or out parameters, you will need to create a custom delegate. We’ve got the Func… delegates Just like it’s cousin, the Action delegate family, the Func delegate family gives us a lot of power to use generic delegates to make classes and algorithms more generic.  Using them keeps us from having to define a new delegate type when need to make a class or algorithm generic. Remember that the point of the Action delegate family was to be able to perform an “action” on an item, with no return results.  Thus Action delegates can be used to represent most methods that take 0 to 16 arguments but return void.  You can assign a method The Func delegate family was introduced in .NET 3.5 with the advent of LINQ, and gives us the power to define a function that can be called on 0 to 16 arguments and returns a result.  Thus, the main difference between Action and Func, from a delegate perspective, is that Actions return nothing, but Funcs return a result. The Func family of delegates have signatures as follows: Func<TResult> – matches a method that takes no arguments, and returns value of type TResult. Func<T, TResult> – matches a method that takes an argument of type T, and returns value of type TResult. Func<T1, T2, TResult> – matches a method that takes arguments of type T1 and T2, and returns value of type TResult. Func<T1, T2, …, TResult> – and so on up to 16 arguments, and returns value of type TResult. These are handy because they quickly allow you to be able to specify that a method or class you design will perform a function to produce a result as long as the method you specify meets the signature. For example, let’s say you were designing a generic aggregator, and you wanted to allow the user to define how the values will be aggregated into the result (i.e. Sum, Min, Max, etc…).  To do this, we would ask the user of our class to pass in a method that would take the current total, the next value, and produce a new total.  A class like this could look like: 1: public sealed class Aggregator<TValue, TResult> 2: { 3: // holds method that takes previous result, combines with next value, creates new result 4: private Func<TResult, TValue, TResult> _aggregationMethod; 5:  6: // gets or sets the current result of aggregation 7: public TResult Result { get; private set; } 8:  9: // construct the aggregator given the method to use to aggregate values 10: public Aggregator(Func<TResult, TValue, TResult> aggregationMethod = null) 11: { 12: if (aggregationMethod == null) throw new ArgumentNullException("aggregationMethod"); 13:  14: _aggregationMethod = aggregationMethod; 15: } 16:  17: // method to add next value 18: public void Aggregate(TValue nextValue) 19: { 20: // performs the aggregation method function on the current result and next and sets to current result 21: Result = _aggregationMethod(Result, nextValue); 22: } 23: } Of course, LINQ already has an Aggregate extension method, but that works on a sequence of IEnumerable<T>, whereas this is designed to work more with aggregating single results over time (such as keeping track of a max response time for a service). We could then use this generic aggregator to find the sum of a series of values over time, or the max of a series of values over time (among other things): 1: // creates an aggregator that adds the next to the total to sum the values 2: var sumAggregator = new Aggregator<int, int>((total, next) => total + next); 3:  4: // creates an aggregator (using static method) that returns the max of previous result and next 5: var maxAggregator = new Aggregator<int, int>(Math.Max); So, if we were timing the response time of a web method every time it was called, we could pass that response time to both of these aggregators to get an idea of the total time spent in that web method, and the max time spent in any one call to the web method: 1: // total will be 13 and max 13 2: int responseTime = 13; 3: sumAggregator.Aggregate(responseTime); 4: maxAggregator.Aggregate(responseTime); 5:  6: // total will be 20 and max still 13 7: responseTime = 7; 8: sumAggregator.Aggregate(responseTime); 9: maxAggregator.Aggregate(responseTime); 10:  11: // total will be 40 and max now 20 12: responseTime = 20; 13: sumAggregator.Aggregate(responseTime); 14: maxAggregator.Aggregate(responseTime); The Func delegate family is useful for making generic algorithms and classes, and in particular allows the caller of the method or user of the class to specify a function to be performed in order to generate a result. What is the result of a Func delegate chain? If you remember, we said earlier that you can assign multiple methods to a delegate by using the += operator to chain them.  So how does this affect delegates such as Func that return a value, when applied to something like the code below? 1: Func<int, int, int> combo = null; 2:  3: // What if we wanted to aggregate the sum and max together? 4: combo += (total, next) => total + next; 5: combo += Math.Max; 6:  7: // what is the result? 8: var comboAggregator = new Aggregator<int, int>(combo); Well, in .NET if you chain multiple methods in a delegate, they will all get invoked, but the result of the delegate is the result of the last method invoked in the chain.  Thus, this aggregator would always result in the Math.Max() result.  The other chained method (the sum) gets executed first, but it’s result is thrown away: 1: // result is 13 2: int responseTime = 13; 3: comboAggregator.Aggregate(responseTime); 4:  5: // result is still 13 6: responseTime = 7; 7: comboAggregator.Aggregate(responseTime); 8:  9: // result is now 20 10: responseTime = 20; 11: comboAggregator.Aggregate(responseTime); So remember, you can chain multiple Func (or other delegates that return values) together, but if you do so you will only get the last executed result. Func delegates and co-variance/contra-variance in .NET 4.0 Just like the Action delegate, as of .NET 4.0, the Func delegate family is contra-variant on its arguments.  In addition, it is co-variant on its return type.  To support this, in .NET 4.0 the signatures of the Func delegates changed to: Func<out TResult> – matches a method that takes no arguments, and returns value of type TResult (or a more derived type). Func<in T, out TResult> – matches a method that takes an argument of type T (or a less derived type), and returns value of type TResult(or a more derived type). Func<in T1, in T2, out TResult> – matches a method that takes arguments of type T1 and T2 (or less derived types), and returns value of type TResult (or a more derived type). Func<in T1, in T2, …, out TResult> – and so on up to 16 arguments, and returns value of type TResult (or a more derived type). Notice the addition of the in and out keywords before each of the generic type placeholders.  As we saw last week, the in keyword is used to specify that a generic type can be contra-variant -- it can match the given type or a type that is less derived.  However, the out keyword, is used to specify that a generic type can be co-variant -- it can match the given type or a type that is more derived. On contra-variance, if you are saying you need an function that will accept a string, you can just as easily give it an function that accepts an object.  In other words, if you say “give me an function that will process dogs”, I could pass you a method that will process any animal, because all dogs are animals.  On the co-variance side, if you are saying you need a function that returns an object, you can just as easily pass it a function that returns a string because any string returned from the given method can be accepted by a delegate expecting an object result, since string is more derived.  Once again, in other words, if you say “give me a method that creates an animal”, I can pass you a method that will create a dog, because all dogs are animals. It really all makes sense, you can pass a more specific thing to a less specific parameter, and you can return a more specific thing as a less specific result.  In other words, pay attention to the direction the item travels (parameters go in, results come out).  Keeping that in mind, you can always pass more specific things in and return more specific things out. For example, in the code below, we have a method that takes a Func<object> to generate an object, but we can pass it a Func<string> because the return type of object can obviously accept a return value of string as well: 1: // since Func<object> is co-variant, this will access Func<string>, etc... 2: public static string Sequence(int count, Func<object> generator) 3: { 4: var builder = new StringBuilder(); 5:  6: for (int i=0; i<count; i++) 7: { 8: object value = generator(); 9: builder.Append(value); 10: } 11:  12: return builder.ToString(); 13: } Even though the method above takes a Func<object>, we can pass a Func<string> because the TResult type placeholder is co-variant and accepts types that are more derived as well: 1: // delegate that's typed to return string. 2: Func<string> stringGenerator = () => DateTime.Now.ToString(); 3:  4: // This will work in .NET 4.0, but not in previous versions 5: Sequence(100, stringGenerator); Previous versions of .NET implemented some forms of co-variance and contra-variance before, but .NET 4.0 goes one step further and allows you to pass or assign an Func<A, BResult> to a Func<Y, ZResult> as long as A is less derived (or same) as Y, and BResult is more derived (or same) as ZResult. Sidebar: The Func and the Predicate A method that takes one argument and returns a bool is generally thought of as a predicate.  Predicates are used to examine an item and determine whether that item satisfies a particular condition.  Predicates are typically unary, but you may also have binary and other predicates as well. Predicates are often used to filter results, such as in the LINQ Where() extension method: 1: var numbers = new[] { 1, 2, 4, 13, 8, 10, 27 }; 2:  3: // call Where() using a predicate which determines if the number is even 4: var evens = numbers.Where(num => num % 2 == 0); As of .NET 3.5, predicates are typically represented as Func<T, bool> where T is the type of the item to examine.  Previous to .NET 3.5, there was a Predicate<T> type that tended to be used (which we’ll discuss next week) and is still supported, but most developers recommend using Func<T, bool> now, as it prevents confusion with overloads that accept unary predicates and binary predicates, etc.: 1: // this seems more confusing as an overload set, because of Predicate vs Func 2: public static SomeMethod(Predicate<int> unaryPredicate) { } 3: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } 4:  5: // this seems more consistent as an overload set, since just uses Func 6: public static SomeMethod(Func<int, bool> unaryPredicate) { } 7: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } Also, even though Predicate<T> and Func<T, bool> match the same signatures, they are separate types!  Thus you cannot assign a Predicate<T> instance to a Func<T, bool> instance and vice versa: 1: // the same method, lambda expression, etc can be assigned to both 2: Predicate<int> isEven = i => (i % 2) == 0; 3: Func<int, bool> alsoIsEven = i => (i % 2) == 0; 4:  5: // but the delegate instances cannot be directly assigned, strongly typed! 6: // ERROR: cannot convert type... 7: isEven = alsoIsEven; 8:  9: // however, you can assign by wrapping in a new instance: 10: isEven = new Predicate<int>(alsoIsEven); 11: alsoIsEven = new Func<int, bool>(isEven); So, the general advice that seems to come from most developers is that Predicate<T> is still supported, but we should use Func<T, bool> for consistency in .NET 3.5 and above. Sidebar: Func as a Generator for Unit Testing One area of difficulty in unit testing can be unit testing code that is based on time of day.  We’d still want to unit test our code to make sure the logic is accurate, but we don’t want the results of our unit tests to be dependent on the time they are run. One way (of many) around this is to create an internal generator that will produce the “current” time of day.  This would default to returning result from DateTime.Now (or some other method), but we could inject specific times for our unit testing.  Generators are typically methods that return (generate) a value for use in a class/method. For example, say we are creating a CacheItem<T> class that represents an item in the cache, and we want to make sure the item shows as expired if the age is more than 30 seconds.  Such a class could look like: 1: // responsible for maintaining an item of type T in the cache 2: public sealed class CacheItem<T> 3: { 4: // helper method that returns the current time 5: private static Func<DateTime> _timeGenerator = () => DateTime.Now; 6:  7: // allows internal access to the time generator 8: internal static Func<DateTime> TimeGenerator 9: { 10: get { return _timeGenerator; } 11: set { _timeGenerator = value; } 12: } 13:  14: // time the item was cached 15: public DateTime CachedTime { get; private set; } 16:  17: // the item cached 18: public T Value { get; private set; } 19:  20: // item is expired if older than 30 seconds 21: public bool IsExpired 22: { 23: get { return _timeGenerator() - CachedTime > TimeSpan.FromSeconds(30.0); } 24: } 25:  26: // creates the new cached item, setting cached time to "current" time 27: public CacheItem(T value) 28: { 29: Value = value; 30: CachedTime = _timeGenerator(); 31: } 32: } Then, we can use this construct to unit test our CacheItem<T> without any time dependencies: 1: var baseTime = DateTime.Now; 2:  3: // start with current time stored above (so doesn't drift) 4: CacheItem<int>.TimeGenerator = () => baseTime; 5:  6: var target = new CacheItem<int>(13); 7:  8: // now add 15 seconds, should still be non-expired 9: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(15); 10:  11: Assert.IsFalse(target.IsExpired); 12:  13: // now add 31 seconds, should now be expired 14: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(31); 15:  16: Assert.IsTrue(target.IsExpired); Now we can unit test for 1 second before, 1 second after, 1 millisecond before, 1 day after, etc.  Func delegates can be a handy tool for this type of value generation to support more testable code.  Summary Generic delegates give us a lot of power to make truly generic algorithms and classes.  The Func family of delegates is a great way to be able to specify functions to calculate a result based on 0-16 arguments.  Stay tuned in the weeks that follow for other generic delegates in the .NET Framework!   Tweet Technorati Tags: .NET, C#, CSharp, Little Wonders, Generics, Func, Delegates

    Read the article

  • How do i make/setup a mailing list?

    - by acidzombie24
    I know i could program it myself but maybe there is a simple (thats the keyword) package. I like to add a box, snippet, form or page to my site for users to input their email address. Then i'd like it to automatically send email saying you have successfully subscribe. I'd want an unsubscribe link and i would be using smtp on google apps. I would like to send email with html so i can have a simple sentence with a complex link such as this I dont know if i'll get marked as spam if i try to send everyone an email at once? so i'd like the software to manage it. Also i'd like to get the emails in a simple format like csv. Is there a simple app that does this? if not i can write a simple form which does a simple insert (or delete when unsubscribing) and write a 200-300line app to send my emails out for me.

    Read the article

  • using php to list some files in folders

    - by Terix
    I have collected many free themes from around internet. Each of them has a screenshot.jpg or png file on their folder. I want to scan all the folders for that file, and return the full file path to be used with an img html tag. I am not interested on partial path or folders where there are not screenshots. For example, if my fodler structure is: ./a/b/ ./c/d/e/screenshot.jpg ./f/ ./g/screenshot.jpg ./h/i/j/k/ ./l/m/screenshot.png ./n/o/ ./p/screenshot.jpg I want to get: ./c/d/e/screenshot.jpg ./g/screenshot.jpg ./l/m/screenshot.png ./p/screenshot.jpg I managed somehow to get a recursive function, but I figured only the way to return an array and then i can't get rid of what I don't need, and I miss png. Can anyone help me on that? the code I managed to put together is this: function getDirectoryTree( $outerDir , $x){ $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) ); $dir_array = Array(); foreach( $dirs as $d ){ if( is_dir($outerDir."/".$d) ){ $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x); }else{ if ($d==x) $dir_array[ $d ] = $d; } } return $dir_array; } $dirlist = getDirectoryTree('.','screenshot.jpg'); print_r($dirlist);

    Read the article

  • Origin of common list-processing function names

    - by Heatsink
    Some higher-order functions for operating on lists or arrays have been repeatedly adopted or reinvented. The functions map, fold[l|r], and filter are found together in several programming languages, such as Scheme, ML, and Python, that don't seem to have a common ancestor. I'm going with these three names to keep the question focused. To show that the names are not universal, here is a sampling of names for equivalent functionality in other languages. C++ has transform instead of map and remove_if instead of filter (reversing the meaning of the predicate). Lisp has mapcar instead of map, remove-if-not instead of filter, and reduce instead of fold (Some modern Lisp variants have map but this appears to be a derived form.) C# uses Select instead of map and Where instead of filter. C#'s names came from SQL via LINQ, and despite the name changes, their functionality was influenced by Haskell, which was itself influenced by ML. The names map, fold, and filter are widespread, but not universal. This suggests that they were borrowed from an influential source into other contemporary languages. Where did these function names come from?

    Read the article

  • Collect all extension methods to generic class in another generic class

    - by Hun1Ahpu
    I'd like to create a lot of extension methods for some generic class, e.g. for public class SimpleLinkedList<T> where T:IComparable And I've started creating methods like this: public static class LinkedListExtensions { public static T[] ToArray<T>(this SimpleLinkedList<T> simpleLinkedList) where T:IComparable { //// code } } But when I tried to make LinkedListExtensions class generic like this: public static class LinkedListExtensions<T> where T:IComparable { public static T[] ToArray(this SimpleLinkedList<T> simpleLinkedList) { ////code } } I get "Extension methods can only be declared in non-generic, non-nested static class". And I'm trying to guess where this restriction came from and have no ideas.

    Read the article

  • Cast to generic type in C#

    - by Andrej
    I have a Dictionary to map a certain type to a certain generic object for that type. For example: typeof(LoginMessage) maps to MessageProcessor<LoginMessage> Now the problem is to retrieve this generic object at runtime from the Dictionary. Or to be more specific: To cast the retrieved object to the specific generic type. I need it to work something like this: Type key = message.GetType(); MessageProcessor<key> processor = messageProcessors[key] as MessageProcessor<key>; Hope there is a easy solution to this. Edit: I do not want to use Ifs and switches. Due to performance issues I cannot use reflection of some sort either.

    Read the article

  • Generic Text Only printer driver mangles control codes

    - by Terry
    If an escape character (or most other characters < 0x20) is sent to the generic / text only printer it gets printed as a period. Using the code in the WinDDK is it possible to 'correct' this behaviour so that it passes it through unmodified? The general scenario for this is that some application ('user app') outputs a document to a windows printer. My application requires this data in plain text form and so what I do is run a generic / text only printer that talks to a virtual com port. This generally works fine except where the 'user app' outputs binary data to the print queue without using the correct mechanism (which seems to work fine on some printer drivers, such as the Epson POS ones, but not the generic / text only one). I've tried changing the print processor selection without success and also tried looking at the gtt files to see if I could readily map in these characters as though they were printable, but the minidriver tool won't let me do that. Any suggestions?

    Read the article

  • I have 6 updates that won't install on Ubuntu 12.04?

    - by Taylor
    I'm an Ubuntu novice, so any help here is greatly appreciated! I'm running Ubuntu 12.04, and I have six updates that just won't install. I've tried Update Manger, sudo apt-get upgrade, and sudo apt-get update. Nothing has worked so far. Here are the details I get from Update Manager: installArchives() failed: Setting up linux-image-3.2.0-24-generic-pae (3.2.0-24.37) ... Running depmod. sh: 1: /usr/sbin/update-initramfs: not found Failed to create initrd image. dpkg: error processing linux-image-3.2.0-24-generic-pae (--configure): subprocess installed post-installation script returned error exit status 2 Setting up linux-image-3.2.0-27-generic-pae (3.2.0-27.43) ... No apport report written because MaxReports is reached already Running depmod. sh: 1: /usr/sbin/update-initramfs: not found Failed to create initrd image. dpkg: error processing linux-image-3.2.0-27-generic-pae (--configure): subprocess installed post-installation script returned error exit status 2 No apport report written because MaxReports is reached already Setting up linux-image-3.2.0-29-generic-pae (3.2.0-29.46) ... Running depmod. sh: 1: /usr/sbin/update-initramfs: not found Failed to create initrd image. dpkg: error processing linux-image-3.2.0-29-generic-pae (--configure): subprocess installed post-installation script returned error exit status 2 No apport report written because MaxReports is reached already Setting up udev (175-0ubuntu9.1) ... udev stop/waiting udev start/running, process 3685 /var/lib/dpkg/info/udev.postinst: 87: /var/lib/dpkg/info/udev.postinst: update-initramfs: not found dpkg: error processing udev (--configure): subprocess installed post-installation script returned error exit status 127 No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of xserver-xorg-core: xserver-xorg-core depends on udev (= 149); however: Package udev is not configured yet. dpkg: error processing xserver-xorg-core (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of fglrx: fglrx depends on xserver-xorg-core; however: Package xserver-xorg-core is not configured yet. dpkg: error processing fglrx (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of fglrx-amdcccle: fglrx-amdcccle depends on fglrx; however: Package fglrx is not configured yet. dpkg: error processing fglrx-amdcccle (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of linux-image-generic-pae: linux-image-generic-pae depends on linux-image-3.2.0-24-generic-pae; however: Package linux-image-3.2.0-24-generic-pae is not configured yet. dpkg: error processing linux-image-generic-pae (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of linux-generic-pae: linux-generic-pae depends on linux-image-generic-pae (= 3.2.0.24.26); however: Package linux-image-generic-pae is not configured yet. dpkg: error processing linux-generic-pae (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of xserver-xorg-video-intel: xserver-xorg-video-intel depends on xorg-video-abi-11; however: Package xorg-video-abi-11 is not installed. Package xserver-xorg-core which provides xorg-video-abi-11 is not configured yet. xserver-xorg-video-intel depends on xserver-xorg-core (= 2:1.10.99.901); however: Package xserver-xorg-core is not configured yet. dpkg: error processing xserver-xorg-video-intel (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of fglrx-dev:No apport report written because MaxReports is reached already fglrx-dev depends on fglrx; however: Package fglrx is not configured yet. dpkg: error processing fglrx-dev (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already Errors were encountered while processing: linux-image-3.2.0-24-generic-pae linux-image-3.2.0-27-generic-pae linux-image-3.2.0-29-generic-pae udev xserver-xorg-core fglrx fglrx-amdcccle linux-image-generic-pae linux-generic-pae xserver-xorg-video-intel fglrx-dev Error in function: Setting up linux-image-3.2.0-24-generic-pae (3.2.0-24.37) ... Running depmod. sh: 1: /usr/sbin/update-initramfs: not found Failed to create initrd image. dpkg: error processing linux-image-3.2.0-24-generic-pae (--configure): subprocess installed post-installation script returned error exit status 2 Setting up linux-image-3.2.0-29-generic-pae (3.2.0-29.46) ... Running depmod. sh: 1: /usr/sbin/update-initramfs: not found Failed to create initrd image. dpkg: error processing linux-image-3.2.0-29-generic-pae (--configure): subprocess installed post-installation script returned error exit status 2 Setting up linux-image-3.2.0-27-generic-pae (3.2.0-27.43) ... Running depmod. sh: 1: /usr/sbin/update-initramfs: not found Failed to create initrd image. dpkg: error processing linux-image-3.2.0-27-generic-pae (--configure): subprocess installed post-installation script returned error exit status 2 Setting up udev (175-0ubuntu9.1) ... udev stop/waiting udev start/running, process 3782 /var/lib/dpkg/info/udev.postinst: 87: /var/lib/dpkg/info/udev.postinst: update-initramfs: not found dpkg: error processing udev (--configure): subprocess installed post-installation script returned error exit status 127 dpkg: dependency problems prevent configuration of linux-image-generic-pae: linux-image-generic-pae depends on linux-image-3.2.0-24-generic-pae; however: Package linux-image-3.2.0-24-generic-pae is not configured yet. dpkg: error processing linux-image-generic-pae (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of xserver-xorg-core: xserver-xorg-core depends on udev (= 149); however: Package udev is not configured yet. dpkg: error processing xserver-xorg-core (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of fglrx: fglrx depends on xserver-xorg-core; however: Package xserver-xorg-core is not configured yet. dpkg: error processing fglrx (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of linux-generic-pae: linux-generic-pae depends on linux-image-generic-pae (= 3.2.0.24.26); however: Package linux-image-generic-pae is not configured yet. dpkg: error processing linux-generic-pae (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of xserver-xorg-video-intel: xserver-xorg-video-intel depends on xorg-video-abi-11; however: Package xorg-video-abi-11 is not installed. Package xserver-xorg-core which provides xorg-video-abi-11 is not configured yet. xserver-xorg-video-intel depends on xserver-xorg-core (= 2:1.10.99.901); however: Package xserver-xorg-core is not configured yet. dpkg: error processing xserver-xorg-video-intel (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of fglrx-amdcccle: fglrx-amdcccle depends on fglrx; however: Package fglrx is not configured yet. dpkg: error processing fglrx-amdcccle (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of fglrx-dev: fglrx-dev depends on fglrx; however: Package fglrx is not configured yet. dpkg: error processing fglrx-dev (--configure): dependency problems - leaving unconfigured

    Read the article

  • Oracle 11g ??? – HM(Hang Manager)??

    - by Allen Gao
    Normal 0 7.8 ? 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 DefSemiHidden="true" DefQFormat="false" DefPriority="99" LatentStyleCount="267" UnhideWhenUsed="false" QFormat="true" Name="Normal"/ UnhideWhenUsed="false" QFormat="true" Name="heading 1"/ UnhideWhenUsed="false" QFormat="true" Name="Title"/ UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/ UnhideWhenUsed="false" QFormat="true" Name="Strong"/ UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/ UnhideWhenUsed="false" Name="Table Grid"/ UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/ UnhideWhenUsed="false" Name="Light Shading"/ UnhideWhenUsed="false" Name="Light List"/ UnhideWhenUsed="false" Name="Light Grid"/ UnhideWhenUsed="false" Name="Medium Shading 1"/ UnhideWhenUsed="false" Name="Medium Shading 2"/ UnhideWhenUsed="false" Name="Medium List 1"/ UnhideWhenUsed="false" Name="Medium List 2"/ UnhideWhenUsed="false" Name="Medium Grid 1"/ UnhideWhenUsed="false" Name="Medium Grid 2"/ UnhideWhenUsed="false" Name="Medium Grid 3"/ UnhideWhenUsed="false" Name="Dark List"/ UnhideWhenUsed="false" Name="Colorful Shading"/ UnhideWhenUsed="false" Name="Colorful List"/ UnhideWhenUsed="false" Name="Colorful Grid"/ UnhideWhenUsed="false" Name="Light Shading Accent 1"/ UnhideWhenUsed="false" Name="Light List Accent 1"/ UnhideWhenUsed="false" Name="Light Grid Accent 1"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/ UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/ UnhideWhenUsed="false" QFormat="true" Name="Quote"/ UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/ UnhideWhenUsed="false" Name="Dark List Accent 1"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/ UnhideWhenUsed="false" Name="Colorful List Accent 1"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/ UnhideWhenUsed="false" Name="Light Shading Accent 2"/ UnhideWhenUsed="false" Name="Light List Accent 2"/ UnhideWhenUsed="false" Name="Light Grid Accent 2"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/ UnhideWhenUsed="false" Name="Dark List Accent 2"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/ UnhideWhenUsed="false" Name="Colorful List Accent 2"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/ UnhideWhenUsed="false" Name="Light Shading Accent 3"/ UnhideWhenUsed="false" Name="Light List Accent 3"/ UnhideWhenUsed="false" Name="Light Grid Accent 3"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/ UnhideWhenUsed="false" Name="Dark List Accent 3"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/ UnhideWhenUsed="false" Name="Colorful List Accent 3"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/ UnhideWhenUsed="false" Name="Light Shading Accent 4"/ UnhideWhenUsed="false" Name="Light List Accent 4"/ UnhideWhenUsed="false" Name="Light Grid Accent 4"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/ UnhideWhenUsed="false" Name="Dark List Accent 4"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/ UnhideWhenUsed="false" Name="Colorful List Accent 4"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/ UnhideWhenUsed="false" Name="Light Shading Accent 5"/ UnhideWhenUsed="false" Name="Light List Accent 5"/ UnhideWhenUsed="false" Name="Light Grid Accent 5"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/ UnhideWhenUsed="false" Name="Dark List Accent 5"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/ UnhideWhenUsed="false" Name="Colorful List Accent 5"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/ UnhideWhenUsed="false" Name="Light Shading Accent 6"/ UnhideWhenUsed="false" Name="Light List Accent 6"/ UnhideWhenUsed="false" Name="Light Grid Accent 6"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/ UnhideWhenUsed="false" Name="Dark List Accent 6"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/ UnhideWhenUsed="false" Name="Colorful List Accent 6"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/ UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/ UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/ UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/ UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/ UnhideWhenUsed="false" QFormat="true" Name="Book Title"/ /* Style Definitions */ table.MsoNormalTable {mso-style-name:????; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:??; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt;} ??????????oracle 11g ???—hang ???(Hang Manager) ???????????,HM ??RAC ??????? ?????????????,??????????/?? hang???????hang???,????,??????????? ??(cycle)?????hang, ???????,???????? ?????(blocker) ?????????????????????,???????,?????blocker ????????(immediate blocker)??????(root blocker)??root blocker ?????????????? 2.1 ???????????,??????,????????????? 2.2 ????????????????????(??:??I/O),??????,????????????????,?????????,????????????? ??????????, oracle??????????? ???????????11g RAC???? hang????hang ?????????? 1.?????????????hang analyze dump ??? 2.????hang analyze dump??(?????) 3. ??????dump??,??????????hang? 4. ??????????hang??? ???,??????????????? ??1: ORACLE ??????????,????? hang analysis cache,???????hang analyze dump i?????????????????????????? ??2:oracle ?????hang analyze ??,??,HM?????RAC??????,hang analyze??????????????,??????dump ????????DIA0(?????11g????)???????3????????hang analyze dump, ?10 ???????hang analyze dump? ??3:??,????????hang analyze dump ??,??,??????????????DIA0??,???????hang ?????,??RAC???,??hang????????????????,??????????DIA0 ????master,???????????????????11g??,?????????DIA0?????HM?master?????,?????????????,?(master)DIA0 ???????????????????? ??hang???,HM????????????,?HM?????hang analyze dump(?30???????,????????)?,??????????????????(???????open chain),????????????????(??,???????????),??,???????,?????????hang??????????????,?????????????????,???????????(open chain)??????,???????????????????hang.??,????(dead lock)????,????????,???????????????????????????? Normal 0 7.8 ? 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 DefSemiHidden="true" DefQFormat="false" DefPriority="99" LatentStyleCount="267" UnhideWhenUsed="false" QFormat="true" Name="Normal"/ UnhideWhenUsed="false" QFormat="true" Name="heading 1"/ UnhideWhenUsed="false" QFormat="true" Name="Title"/ UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/ UnhideWhenUsed="false" QFormat="true" Name="Strong"/ UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/ UnhideWhenUsed="false" Name="Table Grid"/ UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/ UnhideWhenUsed="false" Name="Light Shading"/ UnhideWhenUsed="false" Name="Light List"/ UnhideWhenUsed="false" Name="Light Grid"/ UnhideWhenUsed="false" Name="Medium Shading 1"/ UnhideWhenUsed="false" Name="Medium Shading 2"/ UnhideWhenUsed="false" Name="Medium List 1"/ UnhideWhenUsed="false" Name="Medium List 2"/ UnhideWhenUsed="false" Name="Medium Grid 1"/ UnhideWhenUsed="false" Name="Medium Grid 2"/ UnhideWhenUsed="false" Name="Medium Grid 3"/ UnhideWhenUsed="false" Name="Dark List"/ UnhideWhenUsed="false" Name="Colorful Shading"/ UnhideWhenUsed="false" Name="Colorful List"/ UnhideWhenUsed="false" Name="Colorful Grid"/ UnhideWhenUsed="false" Name="Light Shading Accent 1"/ UnhideWhenUsed="false" Name="Light List Accent 1"/ UnhideWhenUsed="false" Name="Light Grid Accent 1"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/ UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/ UnhideWhenUsed="false" QFormat="true" Name="Quote"/ UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/ UnhideWhenUsed="false" Name="Dark List Accent 1"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/ UnhideWhenUsed="false" Name="Colorful List Accent 1"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/ UnhideWhenUsed="false" Name="Light Shading Accent 2"/ UnhideWhenUsed="false" Name="Light List Accent 2"/ UnhideWhenUsed="false" Name="Light Grid Accent 2"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/ UnhideWhenUsed="false" Name="Dark List Accent 2"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/ UnhideWhenUsed="false" Name="Colorful List Accent 2"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/ UnhideWhenUsed="false" Name="Light Shading Accent 3"/ UnhideWhenUsed="false" Name="Light List Accent 3"/ UnhideWhenUsed="false" Name="Light Grid Accent 3"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/ UnhideWhenUsed="false" Name="Dark List Accent 3"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/ UnhideWhenUsed="false" Name="Colorful List Accent 3"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/ UnhideWhenUsed="false" Name="Light Shading Accent 4"/ UnhideWhenUsed="false" Name="Light List Accent 4"/ UnhideWhenUsed="false" Name="Light Grid Accent 4"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/ UnhideWhenUsed="false" Name="Dark List Accent 4"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/ UnhideWhenUsed="false" Name="Colorful List Accent 4"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/ UnhideWhenUsed="false" Name="Light Shading Accent 5"/ UnhideWhenUsed="false" Name="Light List Accent 5"/ UnhideWhenUsed="false" Name="Light Grid Accent 5"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/ UnhideWhenUsed="false" Name="Dark List Accent 5"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/ UnhideWhenUsed="false" Name="Colorful List Accent 5"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/ UnhideWhenUsed="false" Name="Light Shading Accent 6"/ UnhideWhenUsed="false" Name="Light List Accent 6"/ UnhideWhenUsed="false" Name="Light Grid Accent 6"/ UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/ UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/ UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/ UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/ UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/ UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/ UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/ UnhideWhenUsed="false" Name="Dark List Accent 6"/ UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/ UnhideWhenUsed="false" Name="Colorful List Accent 6"/ UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/ UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/ UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/ UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/ UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/ UnhideWhenUsed="false" QFormat="true" Name="Book Title"/ /* Style Definitions */ table.MsoNormalTable {mso-style-name:????; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:??; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt;} ??4: ???hang??????,??hang???????????????HM ??,????hang?????????????,??HM???????hang. 1. ??????????????????hang??,??:asm?????? 2. ????????????,??:TX?? 3. ???? 4. ???????????:???????“log file switch ”(?????????????????filesystem??????????HM????????,hang??????????)? ??,hang?HM???????,??HM?????????? ???HM???????,??????????????????,?????????oracle ???????,?????????crash???,HM???hang???,??????????????????"_hang_resolution_scope" ???,??????????off(???,????HM?????hang),process(??HM??????,??????????????),instance(??HM??????,??????????????????????????)? ??,????HM ????????trace ?????????? ??: _hang_resolution=TRUE ?? FALSE?????????HM????hang? _hang_resolution_scope=OFF,PORCESS?? INSTANCE?????????HM???????? _hang_detection= <number>? HM??hang?????,????30(?)? ??????????,???????????,??“Oracle 11g ??? – HM(Hang Manager)??"?

    Read the article

  • Using list comprehension in Python to do something similar to zip()?

    - by jamieb
    I'm a Python newbie and one of the things I am trying to do is wrap my head around list comprehension. I can see that it's a pretty powerful feature that's worth learning. cities = ['Chicago', 'Detroit', 'Atlanta'] airports = ['ORD', 'DTW', 'ATL'] print zip(cities,airports) [('Chicago', 'ORD'), ('Detroit', 'DTW'), ('Atlanta', 'ATL')] How do I use list comprehension so I can get the results as a series of lists within a list, rather than a series of tuples within a list? [['Chicago', 'ORD'], ['Detroit', 'DTW'], ['Atlanta', 'ATL']] (I realize that dictionaries would probably be more appropriate in this situation, but I'm just trying to understand lists a bit better). Thanks!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >