text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Definition File Theory: A Deep Dive # Structuring modules to give the exact API shape you want can be tricky. For example, we might want a module that can be invoked with or without new to produce different types, has a variety of named types exposed in a hierarchy, and has some properties on the module object as well. By reading this guide, you’ll have the tools to write complex definition files that expose a friendly API surface. This guide focuses on module (or UMD) libraries because the options here are more varied. Key Concepts # You can fully understand how to make any shape of definition by understanding some key concepts of how TypeScript works. Types # If you’re reading this guide, you probably already roughly know what a type in TypeScript is. To be more explicit, though, a type is introduced with: - A type alias declaration ( type sn = number | string;) - An interface declaration ( interface I { x: number[]; }) - A class declaration ( class C { }) - An enum declaration ( enum E { A, B, C }) - An importdeclaration which refers to a type Each of these declaration forms creates a new type name. Values # As with types, you probably already understand what a value is. Values are runtime names that we can reference in expressions. For example let x = 5; creates a value called x. Again, being explicit, the following things create values: let, const, and vardeclarations - A namespaceor moduledeclaration which contains a value - An enumdeclaration - A classdeclaration - An importdeclaration which refers to a value - A functiondeclaration Namespaces # Types can exist in namespaces. For example, if we have the declaration let x: A.B.C, we say that the type C comes from the A.B namespace. This distinction is subtle and important – here, A.B is not necessarily a type or a value. Simple Combinations: One name, multiple meanings # Given a name A, we might find up to three different meanings for A: a type, a value or a namespace. How the name is interpreted depends on the context in which it is used. For example, in the declaration let m: A.A = A;, A is used first as a namespace, then as a type name, then as a value. These meanings might end up referring to entirely different declarations! This may seem confusing, but it’s actually very convenient as long as we don’t excessively overload things. Let’s look at some useful aspects of this combining behavior. Built-in Combinations # Astute readers will notice that, for example, class appeared in both the type and value lists. The declaration class C { } creates two things: a type C which refers to the instance shape of the class, and a value C which refers to the constructor function of the class. Enum declarations behave similarly. User Combinations # Let’s say we wrote a module file foo.d.ts: export var SomeVar: { a: SomeType }; export interface SomeType { count: number; } Then consumed it: import * as foo from './foo'; let x: foo.SomeType = foo.SomeVar.a; console.log(x.count); This works well enough, but we might imagine that SomeType and SomeVar were very closely related such that you’d like them to have the same name. We can use combining to present these two different objects (the value and the type) under the same name Bar: export var Bar: { a: Bar }; export interface Bar { count: number; } This presents a very good opportunity for destructuring in the consuming code: import { Bar } from './foo'; let x: Bar = Bar.a; console.log(x.count); Again, we’ve used Bar as both a type and a value here. Note that we didn’t have to declare the Bar value as being of the Bar type – they’re independent. Advanced Combinations # Some kinds of declarations can be combined across multiple declarations. For example, class C { } and interface C { } can co-exist and both contribute properties to the C types. This is legal as long as it does not create a conflict. A general rule of thumb is that values always conflict with other values of the same name unless they are declared as namespaces, types will conflict if they are declared with a type alias declaration ( type s = string), and namespaces never conflict. Let’s see how this can be used. Adding using an interface # We can add additional members to an interface with another interface declaration: interface Foo { x: number; } // ... elsewhere ... interface Foo { y: number; } let a: Foo = ...; console.log(a.x + a.y); // OK This also works with classes: class Foo { x: number; } // ... elsewhere ... interface Foo { y: number; } let a: Foo = ...; console.log(a.x + a.y); // OK Note that we cannot add to type aliases ( type s = string;) using an interface. Adding using a namespace # A namespace declaration can be used to add new types, values, and namespaces in any way which does not create a conflict. For example, we can add a static member to a class: class C { } // ... elsewhere ... namespace C { export let x: number; } let y = C.x; // OK Note that in this example, we added a value to the static side of C (its constructor function). This is because we added a value, and the container for all values is another value (types are contained by namespaces, and namespaces are contained by other namespaces). We could also add a namespaced type to a class: class C { } // ... elsewhere ... namespace C { export interface D { } } let y: C.D; // OK In this example, there wasn’t a namespace C until we wrote the namespace declaration for it. The meaning C as a namespace doesn’t conflict with the value or type meanings of C created by the class. Finally, we could perform many different merges using namespace declarations. This isn’t a particularly realistic example, but shows all sorts of interesting behavior: namespace X { export interface Y { } export class Z { } } // ... elsewhere ... namespace X { export var Y: number; export namespace Z { export class C { } } } type X = string; In this example, the first block creates the following name meanings: - A value X(because the namespacedeclaration contains a value, Z) - A namespace X(because the namespacedeclaration contains a type, Y) - A type Yin the Xnamespace - A type Zin the Xnamespace (the instance shape of the class) - A value Zthat is a property of the Xvalue (the constructor function of the class) The second block creates the following name meanings: - A value Y(of type number) that is a property of the Xvalue - A namespace Z - A value Zthat is a property of the Xvalue - A type Cin the X.Znamespace - A value Cthat is a property of the X.Zvalue - A type X Using with export = or import # An important rule is that export and import declarations export or import all meanings of their targets.
https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
CC-MAIN-2020-10
refinedweb
1,125
60.75
File Release Notes and Changelog Release Name: Npgsql 2.1.0 Release Notes Before talking about the changes in this release,! Major highlights ============= Version numbers ------------------------ Starting with this release, we are going to number our versions based on the semver schema. (). We may not follow strictly everything though. This is a work in progress. This version was supposed to be a continuation of the 2.0.13 series as we already have a 2.0.13 beta1 released. But we made so many changes since the 2.0.13 that we decided to jump the version number to 2.1. Entity Framework -------------------------- We added initial support for Entity Framework 6.0. We isolated the entity framework code in two other assemblies: Npgsql.LegacyEntityFramework.dll and Npgsql.EntityFramework.dll. The first one is for entity framework pre-6 version and the other one is for entity framework 6.0 and above. This was needed in order to facilitate the deployment and the code organization as the apis and namespaces change a lot depending on the entity framework version. Support for 6.0 isn't yet complete and is to be considered optional at the moment. We will add better support in upcoming versions. We already have Support for EFMigration and Database creation () and identity insert support () which will be made available in future releases of Npgsql App.config and Web.config configuration has been changed. It depends on the EF version you are using. More info about that can be found at: SSLStream support ---------------------------- In this release, we added support to use SSLStream. But it isn't used by default. To keep backward compatibility, we still use by default Mono.Security for SSL connections. But this may change in the future. We ask that you test your application with SSLStream and check if you get any problems. in order to use SSLStream, you have to ask Npgsql to use it by using the following line: NpgsqlConnection.UseSslStream = true This will make Npgsql use SSLStream for new ssl connections. Please, give it a try and let us know if it works ok for you. Project restructuring -----------------------------. Fixed bugs: [#176] 2.1 RC SSL and EF6 no work. [#174] GetResultSchema When current description is null [#164] Connection state throws error incorrectly [#28] [#1011338] Error in insert statement with new E6 version. Thanks cody82. [#27] Fixed connecting to Postgresql using client certificates. Check for more information. Thanks dreamlax Added VS2012 project file. Thanks Glen Parker [#35] Fixed array handling with prepared statements. Thanks Chen Huajun. [#33] [#1011346] BUGFIX: Thread synchronization inside GetPooledConnector [#57] Bytea handling optimizations. Thanks Rungee [#59] Bytea decoder optimizations. Thanks Glen Parker [#1000515] Prepare() makes command very slow. Thanks Glen Parker for optimizations. [#61] Async notification optimizations and fixes. Glen Parker [#63] [#1011334] NpgsqlConnection.GetSchema doesn't dispose connections [#69] Fix extra-float-digits setup for postgresql below 9.0 [#92] Added InvariantCulture to NpgsqlCopySerializer. Thanks djsubzero [#86] Rewrite query parameter substitution. Thanks Glen Parker [#118] Detection of Parameter Direction in DeriveParameters method. Thanks Noé Garcia and Shay Rojansky [#1011271] NpgsqlSchema: Use InvariantCulture on all return DataTables with schema data. Thanks Oskar Berggren for patch. [#1011305] Scope without prepared transactions. Thanks Shay Rojansky for the patch. [#1011310] Command timeouts after the first are not handled. Thanks Evan Martin for the patch. [#1011316] ConnectionTimeout fix, bypass the 2147 seconds limit of Socket.Poll method. Thanks Tasos Mamaloukos for patch. [#1011325] Escaped strings don't work with EF. Thanks Andrey Polyakov for patch and tests. Implements DateTime canonical functions for EntityFramework. Thanks Andrey Polyakov for patch. [#1011325] Escaped strings don't work with EF. Thanks Andrey Polyakov for patch and tests. [#1011321] Wrong BitString value. Thanks Jon Hanna for patch and support. [#1011326] Connection pooling timer (thus thread) is active even if connection pooling is disabled. Thanks Shay Rojansky for the patch. [#1011001] Bug in NpgsqlConnectionStringBuilder affects on cache and connection pool. Thanks Shay Rojansky for the patch. [#1011267] Monetary localization bug [#1011085] Money format is not set in accordance with the system locale format [#141] AlwaysPrepare does not works in some cases. Thanks @avb1987. [#153] Fixed wrong comma putting in AddFunctionColumnListSupport(). Thanks @tyler-nguyen. New features: Add support for new error fields added in PostgreSQL 9.3. See here for more information about those fields:;a=commit;h=991f3e5ab3f8196d18d5b313c81a5f744f3baaea Thanks David Rowley for patch. Initial support for Entity Framework 6. See for more information about it. [#30] Improved connection timeout handling. Thanks Glen Parker. [#41], [#52], [#77], [#72], [#80] Huge internal query handling which added a big performance boost for prepared statements and unprepared statements as well. Binary parameter codec infrastructure has been added, and several data types (currently bytea, text, boolean, integers, and gloats) can now use PG's binary coded support, including arrays of those types, which offers a dramatic performance boost for parameter and result values in prepared statements. Previously we didn't recommend using prepared statements with Npgsql, only for bytea data types. Thanks to Glen Parker, this is now a thing of the past. Huge directory and project structure.. [#74] Use new "Discard all" syntax when releasing connection from pool. Thanks Chen Huajun. New connection string parameter "AlwaysPrepare" to indicate to Npgsql to always prepare statements before executing. [#110] Added support for Entity Framework before version 6.0 and after 6.0. They are totally different things regarding APIs and namespaces. Thanks Shay Rojansky and Kenji Uno. Added nuget EFProvider installation. Thanks Shay Rojansky. Added EF6 ConnectionFactory class. Thanks Shay Rojansky. [#135] Fix for operators @@, @> and <@. Thanks Glen Parker and jjchiw. [#117] Command timeout improvements. Thanks Glen Parker.
http://pgfoundry.org/frs/shownotes.php?release_id=2074
CC-MAIN-2016-26
refinedweb
931
62.24
LINKED DATA STRUCTURES - Judith Hawkins - 2 years ago - Views: Transcription 1 LINKED DATA STRUCTURES 1 2 Linked Lists A linked list is a structure in which objects refer to the same kind of object, and where: the objects, called nodes, are linked in a linear sequence. we keep a reference to the first node of the list (called the front or head ). The nodes are used to store data. For example, here is a class for nodes in a linked list of ints: public class IntNode { public int value; public IntNode link; public IntNode(int v) { value = v; Note: having public instance variables is not as bad here as it might first look. Why? Drawing a linked list The next slide shows in detail how memory might look for a linked list containing 5 nodes. 2 3 Static area not of interest in this example. Assume we have a class LExample whose main builds a linked list for front to refer to. main:9 LExample xae IntNode int value 98 IntNode link null x7f IntNode int value 161 IntNode link xae IntNode front x88 x57 IntNode xd0 IntNode int value 5 int value 14 IntNode link x7f IntNode link x57 x88 IntNode int value -31 IntNode link xd0 3 4 A simpler picture front When drawing such diagrams, always be careful to anchor the references clearly, i.e., to show where they are stored. Note that there are several conventions for drawing a null reference, including: Preferred: Not as nice: 4 5 Tracing It s easy for linked structures to get all tangled up, so you will have to develop some new debugging skills for working with them. When writing, debugging, or understanding code with linked structures, it is extremely useful to trace by hand, using diagrams. Exercise: Trace this code. public class Example { public static void main(string[] args) { // Make a variable to refer to the list, // and put one element into the list. IntNode front = new IntNode(95); // Put another element into the list IntNode temp = new IntNode(104); temp.link = front; front = temp; // We can chain together dots: System.out.println(front.link.value); // 95 5 6 Questions and Exercises What happens if we repeat the 3 lines Put another... several times, using a different integer each time? Suppose you want to write a general method that inserts a new element at the front of a linked list of IntNodes, for use in the example code. What header would you use? Have you considered the case where the list is empty? Write your insert method. Write a general method that prints out the contents of a linked list of IntNodes. Write a test driver for your two methods and use it to test them. Think up other methods to practice using linked lists. 6 7 Hints for working with linked structures Trace your code by hand, using pictures, as you write it. If you are ever unsure of what some code does to references, make up fake memory addresses for the references and treat them like ordinary integers. Every time you write a line like this: blah.bloop to follow a reference, be sure the reference (in this case blah) is not null. Either (1) use an if, or (2) be sure that the reference cannot possibly be null in that context, and assert that fact in a comment. 7 8 Arrays are contiguous Linked Lists vs Arrays In an array, the elements have to be in a contiguous (connected and sequential) portion of memory. Memory immediately next to the array may already be in use for something else. So programming languages don t generally provide for arrays that can grow and shrink in place. Question: Doesn t Java s ArrayList do just that? Linked lists are not contiguous In a linked list, the reference in each node says where to find the next one. So the nodes can be all over memory. 8 9 Implications With an array, we must choose a size once and for all. (This can waste memory, or we could run out of spaces). With a linked list, we can add and remove elements at will. (Each one does take up a little more space for its link field, and it may take time to get to the insertion / removal spot). With an array, we can immediately access the n th element. With a linked list, we cannot. We have to follow n pointers. 9 10 Which is better? Neither arrays nor linked lists are best; it depends on what you re going to do most (e.g., search or update?), and what your priorities are (e.g., time or space?). Java also takes time managing the location of objects in memory. It has to find an empty range of memory when we construct a new object. And it looks for unreferenced objects, to reuse their memory. But this is outside the scope of our course. 10 11 Deletion from a Linked List Question: If the list is sorted, should we use binary search to find the element to delete? Unlike an array, there is no need to shift any elements up to fill the hole left by deletion. We just unlink the unwanted element. front 12 Implementing the queue ADT: Deletion /** A node in a linked list. */ class ListNode { public Object value; public ListNode link; /** A ListNode containing o. */ public ListNode(Object o) { value = o; /** Note: elements are compared by equals(object). */ interface ExtendedQueue extends Queue { /** Return whether I contain o. */ public abstract boolean contains(object o); /** Remove first (starting from the front) * occurrence of o from me if it s there. */ public abstract void delete(object o); public class LinkedQueue implements ExtendedQueue { /** Front node in my linked list. */ private ListNode front; // Methods go here. See next slide for delete. 12 13 Method details /** Remove first (starting from the front) * occurrence of o from me if it s there. */ public void delete(object o) { ListNode previous = null; ListNode current = front; // Follow links until we fall off, or until we // find the node to delete. while (current!= null &&! current.value.equals(o)) { previous = current; current = current.link; // If we didn t fall off, we found it. // Update either the front of the list or the previous link. if (current!= null) { if (current == front) { front = current.link; else { previous.link = current.link; 13 14 Questions: Why did we initialize previous? When implementing Queue with a linked list, should we keep a pointer to the end of the linked list? What about when implementing Stack? Exercises: Devise a thorough set of test cases for delete. Modify delete so that it handles null elements. In delete, previous is used to pass information from one iteration to the next: it remembers information from the previous iteration. Write delete using only one local variable, by looking ahead. Implement all Queue methods in LinkedQueue. Trace the code by hand for each method. 14 15 Other Linked Data Structures References can be used to create many different data structures. Circularly-linked lists front apple bee honey wasp tree The last element contains a reference to the first element, rather than null. 15 16 Doubly-linked lists Each element keeps both a frontwards and a backwards reference. front ace by hi /** A node for a doubly linked list of Strings. */ class DoubleNode { public String value; public DoubleNode next, prev; /** A DoubleNode containing v. */ public DoubleNode(String v) { value = v; This could be useful for a list presented on screen, so we can easily write code to scroll up and down. 16 17 When traversing a doubly-linked list to prepare for insertion or deletion, there is no need to use both a current and previous reference: each node has a built-in reference to the previous element. Deletion with a doubly-linked list: front deleterecord ace by hi Insertion with a doubly-linked list: front insertbefore ace by hi apple newrecord 17 18 Exercise: Write complete insertion and deletion methods for a sorted doublylinked list. /** Insert a new node containing s into the appropriate * position in the sorted, doubly-linked list whose * first node is front. * Return the (possibly new) first node. */ public static DoubleNode insert(doublenode front, String s) /** Delete s, if it exists, from the doubly-linked list * whose first node is front. * Return the (possibly new) first node. */ public static DoubleNode delete(doublenode front, String s) Questions: The above comments aren t clear about the behaviour in certain circumstances. What are those circumstances? Why do we make these methods static? Exercise: Think about the pros and cons of using a doubly-linked list of Comparables instead of Strings. 18 Algorithms and Data Structures Written Exam Proposed SOLUTION Algorithms and Data Structures Written Exam Proposed SOLUTION 2005-01-07 from 09:00 to 13:00 Allowed tools: A standard calculator. Grading criteria: You can get at most 30 points. For an E, 15 points are Chapter 13. Pointers and Linked Lists Chapter 13 Pointers and Linked Lists Overview 13.1 Nodes and Linked Lists 13.2 Stacks and Queues Slide 13-2 13.1 Nodes and Linked Lists Nodes and Linked Lists n A linked list is a list that can grow and 22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department 22c:31 Algorithms Ch3: Data Structures Hantao Zhang Computer Science Department Linear Data Structures Now we can now explore some convenient techniques for organizing Heap Algorithms CS Data Structures and Algorithms Lecture Slides Wednesday, April 5, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009 Glenn G. Chappell Data Structure. Lecture 3 Data Structure Lecture 3 Data Structure Formally define Data structure as: DS describes not only set of objects but the ways they are related, the set of operations which may be applied to the elements) Useful Java Collections Useful Java Collections Nathaniel Osgood MIT 15.879 May 9, 2012 Java.util Collection Hierarchies Collection Objects in AnyLogic Informal Collection Variables in AnyLogic Useful Collections Array ArrayList BM267 - Introduction to Data Structures BM267 - Introduction to Data Structures 3. Elementary Data Structures Ankara University Computer Engineering Department BLM267 1 Objectives Learn about elementary data structures - Data structures that 10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling) Overview of Data Structures UNIT 3 Concrete Data Types Classification of Data Structures Concrete vs. Abstract Data Structures Most Important Concrete Data Structures Arrays Records Linked Lists Binary Trees Overview of Data Structures Chapter 4: Linked Lists Chapter 4: Linked Lists Data Abstraction & Problem Solving with C++ Fifth Edition by Frank M. Carrano Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during International Journal Of Engineering Research & Management Technology International Journal Of Engineering Research & Management Technology ISSN: 2348-4039 September- 2014 Volume 1, Issue-5 Dynamic Implementation Using Linked List Karuna Department of Information and Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Test #1 Next Thursday During Class Cover through (near?) end of Chapter 5 Objectives Learn about linked lists Become aware of the basic properties of Lecture 6b Linked List Variations. Similar but not the same Lecture 6b Linked List Variations Similar but not the same Linked List Variations: Overview The linked list implementation used in List ADT is known as Singly (Single) Linked List Each node has one pointer Data Structures and Algorithms Lists Data Structures and Algorithms Lists Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/19 5-0: Abstract Data Types An CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris 1 Collections - Set What is a Set? A Set is an unordered sequence of data with no duplicates Not like a List where you Data Structures. Topic #4 Topic #4 Today s Agenda Stack and Queue ADTs What are they Like Ordered Lists, are position oriented Use of Data Structures for Stacks and Queues arrays (statically & dynamically allocated) linear linked Lecture 1: Data Storage & Index Lecture 1: Data Storage & Index R&G Chapter 8-11 Concurrency control Query Execution and Optimization Relational Operators File & Access Methods Buffer Management Disk Space Management Recovery Manager > Algorithms and Data Structures Basic Data Structures Page 1 BFH-TI: Softwareschule Schweiz Basic Data Structures Dr. CAS SD01 Basic Data Structures Page 2 Outline Data Structures and Abstract Data Types Linear Data Structures Implementing Linked Lists Linked Lists, Queues, and Stacks Linked Lists Linked Lists, Queues, and Stacks CSE 10: Introduction to C Programming Fall 200 Dynamic data structure Size is not fixed at compile time Each element of a linked list: holds a value points Data Structures Using Java Data Structures Using Java D. S. Malik P. S. Nair THOMSON COURSE TECHNOLOGY Australia Canada Mexico Singapore Spain United Kingdom United States TABLE OF Contents PREFACE XXV 1.Software Engineering Principles AP Computer Science AB Syllabus 1 AP Computer Science AB Syllabus 1 Course Resources Java Software Solutions for AP Computer Science, J. Lewis, W. Loftus, and C. Cocking, First Edition, 2004, Prentice Hall. Video: Sorting Out Sorting, PES Institute of Technology-BSC QUESTION BANK PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions Linked Data Structures Linked Data Structures 17 17.1 NODES AND LINKED LISTS 733 Nodes 733 Linked Lists 738 Inserting a Node at the Head of a List 740 Pitfall: Losing Nodes 743 Inserting and Removing Nodes Inside a List 743 ! Each node two basic attributes: The Linked List ADT head:! Class #11: Linked Lists Software Design III (CS 340): M. Allen, 17 Feb. 16! General idea: an implementation of List interface/adt, using a set of linked nodes, with size() == Summary. Pre requisition. Content Details: 1. Basics in C++ Summary C++ Language is one of the approaches to provide object-oriented functionality with C like syntax. C++ adds greater typing strength, scoping and other tools useful in object-oriented programming. CHAPTER 4 ESSENTIAL DATA STRUCTRURES CHAPTER 4 ESSENTIAL DATA STRUCTURES 72 CHAPTER 4 ESSENTIAL DATA STRUCTRURES In every algorithm, there is a need to store data. Ranging from storing a single value in a single variable, to more complex Multi-Way Search Trees (B Trees) Multi-Way Search Trees (B Trees) Multiway Search Trees An m-way search tree is a tree in which, for some integer m called the order of the tree, each node has at most m children. If n Symbol Tables. IE 496 Lecture 13 Symbol Tables IE 496 Lecture 13 Reading for This Lecture Horowitz and Sahni, Chapter 2 Symbol Tables and Dictionaries A symbol table is a data structure for storing a list of items, each with a key and Node-Based Structures Linked Lists: Implementation Linked Lists: Implementation CS 311 Data Structures and Algorithms Lecture Slides Monday, March 30, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org Data Structures and Algorithms Data Structures and Algorithms CS245-2016S-05 Abstract Data Types and Lists David Galles Department of Computer Science University of San Francisco 05-0: Abstract Data Types Recall that an Abstract Data Zabin Visram Room CS115 CS126 Searching. Binary Search Zabin Visram Room CS115 CS126 Searching Binary Search Binary Search Sequential search is not efficient for large lists as it searches half the list, on average Another search algorithm Binary search Very Linked Lists, Stacks, Queues, Deques. It s time for a chainge! Linked Lists, Stacks, Queues, Deques It s time for a chainge! Learning Goals After this unit, you should be able to... Differentiate an abstraction from an implementation. Define and give examples of problems Priority Queues. Client, Implementation, Interface. Priority Queues. Abstract Data Types Client, Implementation, Interface Priority Queues Priority Queue ADT Binary heaps Heapsort Reference: Chapter 6, Algorithms in Java, 3 rd Edition, Robert Sedgewick. Separate interface and implementation Chapter 8: Bags and Sets Chapter 8: Bags and Sets In the stack and the queue abstractions, the order that elements are placed into the container is important, because the order elements are removed is related to the order in which School of Informatics, University of Edinburgh Computer Science 1 Ah [03 04] School of Informatics, University of Edinburgh Computer Science 1 Ah [03 04] CS1Ah Lecture Note 25 Binary Search Trees This lecture studies binary trees in more detail, in particular their application recursion, O(n), linked lists 6/14 recursion, O(n), linked lists 6/14 recursion reducing the amount of data to process and processing a smaller amount of data example: process one item in a list, recursively process the rest of the list Project 4 DB A Simple database program Project 4 DB A Simple database program Due Date April (Friday) Before Starting the Project Read this entire project description before starting Learning Objectives After completing this project you should Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction dictionary find definition word definition book index find relevant pages term list of page numbers ROBERT SEDGEWICK KEVI WAYE F O U R T H E D I T I O ROBERT SEDGEWICK KEVI WAYE ROBERT SEDGEWICK KEVI WAYE Symbol tables Symbol table applications Key-value pair abstraction. Insert a value with specified. Ordered Lists and Binary Trees Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6 Class 28: Binary Search Trees. Binary Search Trees Introduction to Computation and Problem Solving Class 2: Binary Search Trees Prof. Steven R. Lerman and Dr. V. Judson Harward Binary Search Trees In the previous lecture, we defined the concept of binary CSE 2123: Collections: Maps. Jeremy Morris CSE 2123: Collections: Maps Jeremy Morris 1 Collections - Map A map is another kind of collection Different from previously discussed examples Lists, Queues, Stacks are all linear collections Some meaning Anatomy of a linked list Linked Lists Anatomy of a linked list A linked list consists of: A sequence of nodes mylist a b c d Each node contains a value and a link (pointer or reference) to some other node The last node contains CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects Introduction to Programming System Design. CSCI 455x (4 Units) Introduction to Programming System Design CSCI 455x (4 Units) Description This course covers programming in Java and C++. Topics include review of basic programming concepts such as control Objective Specification, design and implementation of an ADT in C/C++. Using generic elements and iterators. ADTs containers of generic elements and iterators Objective Specification, design and implementation of an ADT in C/C++. Using generic elements and iterators. Theoretical aspects Representation of an ADT Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 17 October 23, 2014 1 Introduction In this lecture, we will continue considering associative Java Memory Management Java Memory Management 1 Tracing program execution Trace: To follow the course or trail of. When you need to find and fix a bug or have to understand a tricky piece of code that your coworker wrote, Structure with C Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation Dynamic Storage Allocation CS 44 Operating Systems Fall 5 Presented By Vibha Prasad Memory Allocation Static Allocation (fixed in size) Sometimes we create data structures that are fixed and don t need Data Structures. Level 6 C30151.. Module Descriptor The Further Education and Training Awards Council (FETAC) was set up as a statutory body on 11 June 2001 by the Minister for Education and Science. Under the Qualifications (Education & Training) Act, 406 memory pool memory allocation handle memory deallocation dynamic storage allocation 406 Chap. 12 Lists and Arrays Revisited 12.4 Memory Management Most of the data structure implementations described in this book store and access objects all of the same size, such as integers stored in Language Examples of ADT: C++ Language Examples of ADT: C++ Based on C struct type and Simula 67 classes All of the class instances of a class share a single copy of the member functions Each instance of a class has its own copy of RECURSIVE BST OPERATIONS. with more Java generics RECURSIVE BST OPERATIONS with more Java generics 1 Let s implement a BST class, avoiding iteration. This will give us more practice with trees, and with recursion. It will also give us a chance for a continued Memory Management. Memory Areas and their use. Memory Manager Tasks: Free List Implementations. acquire release Memory Management Memory Areas and their use Memory Manager Tasks: acquire release Free List Implementations Singly Linked List Doubly Linked List Buddy Systems Memory Management Memory areas: In languages Structures and Algorithms Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list
http://docplayer.net/80934-Linked-data-structures.html
CC-MAIN-2017-51
refinedweb
3,698
51.18
The. “Bit banging” is the most basic method of producing sound from an Arduino. Just connect a digital output pin to a small speaker and then rapidly and repeatedly flip the pin between high and low. This is how the Arduino’s tone() statement works. The output pins can even drive a small (4cm or less) 8-ohm speaker connected directly between the pin and ground without any amplification.. The Arduino’s analogWrite() function, which outputs a square wave at a fixed frequency of 490Hz, is handy to illustrate the concept. Connect your speaker to pin D9 and ground (Figure B) and run this sketch: void setup() { pinMode(9,OUTPUT); } void loop() { for (int i=0; i<255; i++) { analogWrite(9,i); delay(10); } } You should hear a tone of constant pitch, with a timbre slowly changing from thin and reedy (mostly space time) to round and fluty (equal mark and space time), and back to thin and reedy again (mostly mark time). A square wave with a variable duty cycle is properly called a pulse-width modulated (PWM) wave. Altering the duty cycle to change timbre may serve very basic sound functions, but to produce more complex output, you’ll need a more advanced approach. PWM waves are strictly digital, either high or low. For analog waves, we need to generate voltage levels that lie between these 2 extremes. This is the job of a digital-to-analog converter (DAC). There are several types of DAC. The simplest is probably the R-2R ladder (Figure C). In this example, we have 4 digital inputs, marked D0–D3. D0 is the least significant bit and D3 the most significant. If you set D0 high, its current has to pass through a large resistance of 2R + R + R + R = 5R to reach the output. Some of the current also leaks to ground through the relatively small resistance 2R. Thus a high voltage at D0 produces a much smaller output voltage than a high voltage at D3, which faces a small resistance of only 2R to reach the output, and a large resistance of 5R to leak to ground. Setting D0–D3 to binary values from 0000 to 1111 (0–15 decimal), and then back down to 000 in quick succession, ought to output the triangle wave shown in Figure D. To produce other waveforms, in theory, we must simply present the right sequence of binary numbers to D0–D3 at the right rate. Unfortunately, there are drawbacks to using an R-2R DAC, foremost probably that it requires very precise resistor values to prevent compound errors from adding up and distorting the waveform. The jagged “steps” must also be smoothed, using a low-pass filter, to prevent a discordant metallic sound. Finally, an R-2R DAC uses up more output pins than are strictly necessary. Though a bit harder to understand, the “1-bit” DAC produces very smooth, high-quality waveforms using just one output pin with a single resistor and capacitor as a filter. It also leaves the Arduino free to do other things while the sound is playing. If you replace the speaker from the bit-banging sketch with an LED, you’ll see it increase in brightness as the duty cycle increases from 0 to 100%. Between these 2 extremes, the LED is really flashing at around 490Hz, but we see these flashes as a continuous brightness. This “smoothing” phenomenon is called “persistence of vision,” and it can be thought of as a visual analogy to the low-pass filter circuit shown in Figure E. You can use this filter to smooth the output from a 1-bit DAC. The mark time of the incoming PWM wave determines the voltage at Vout from moment to moment. For example, a mark/space ratio of 50:50 outputs 50% of the high voltage of the incoming signal, a 75:25 ratio outputs 75% of that voltage, and so on. An Arduino’s digital pins produce a high of 5V, so a 50% duty cycle, for example, would give 2.5V at Vout. For best sound quality, the frequency of the PWM signal should be as high as possible. Luckily, the Arduino can produce fast PWM waves up to 62.5KHz. The hardware also provides a handy mechanism for updating the mark time from a lookup table at absolutely regular intervals, while leaving the Arduino free to do other things. The ATmega328 chip at the heart of the Arduino Nano 3 contains 3 hardware timers. Each timer includes a counter that increments at each clock tick, automatically overflowing back to 0 at the end of its range. The counters are named TCNTn, where n is the number of the timer in question. Timer0 and timer2 are 8-bit timers, so TCNT0 and TCNT2 repeatedly count from 0 to 255. Timer1 is a 16-bit timer, so TCNT1 repeatedly counts from 0 to 65535, and can also be made to work in 8-bit mode. In fact, each timer has a few different modes. The one we need is called “fast PWM,” which is only available on timer1. In this mode, whenever TCNT1 overflows to zero, the output goes high to mark the start of the next cycle. To set the mark time, timer1 contains a register called OCR1A. When TCNT1 has counted up to the value stored in OCR1A, the output goes low, ending the cycle’s mark time and beginning its space time. TCNT1 keeps on incrementing until it overflows, and the process begins again. This process is represented graphically in Figure F. The higher we set OCR1A, the longer the mark time of the PWM output, and the higher the voltage at Vout. By updating OCR1A at regular intervals from a pre-calculated lookup table, we can generate any waveform we like. Listing 1 (download Listings 1–6 as a .zip file) contains a sketch that uses a lookup table, fast PWM mode, and a 1-bit DAC to generate a sine wave. #include <avr/interrupt.h> // Use timer interrupt library /******** Sine wave parameters ********/ #define PI2 6.283185 // 2*PI saves calculation later #define AMP 127 // Scaling factor for sine wave #define OFFSET 128 // Offset shifts wave to all >0 values /******** Lookup table ********/ #define LENGTH 256 // Length of the wave lookup table byte wave[LENGTH]; // Storage for waveform void setup() { /* Populate the waveform table with a sine wave */ for (int i=0; i<LENGTH; i++) { // Step across wave table float v = (AMP*sin((PI2/LENGTH)*i)); // Compute value wave[i] = int(v+OFFSET); // Store value as integer } /****Set timer1 for 8-bit fast PWM output ****/ pinMode(9, OUTPUT); // Make timer’s PWM pin an output TCCR1B = (1 << CS10); // Set prescaler to full 16MHz TCCR1A |= (1 << COM1A1); // Pin low when TCNT1=OCR1A TCCR1A |= (1 << WGM10); // Use 8-bit fast PWM mode TCCR1B |= (1 << WGM12); /******** Set up timer2 to call ISR ********/ TCCR2A = 0; // No options in control register A TCCR2B = (1 << CS21); // Set prescaler to divide by 8 TIMSK2 = (1 << OCIE2A); // Call ISR when TCNT2 = OCRA2 OCR2A = 32; // Set frequency of generated wave sei(); // Enable interrupts to generate waveform! } void loop() { // Nothing to do! } /******** Called every time TCNT2 = OCR2A ********/ ISR(TIMER2_COMPA_vect) { // Called when TCNT2 == OCR2A static byte index=0; // Points to each table entry OCR1AL = wave[index++]; // Update the PWM output asm(“NOP;NOP”); // Fine tuning TCNT2 = 6; // Timing to compensate for ISR run time } First we calculate the waveform and store it in an array as a series of bytes. These will be loaded directly into OCR1A at the appropriate time. We then start timer1 generating a fast PWM wave. Because timer1 is 16-bit by default, we also have to set it to 8-bit mode. We use timer2 to regularly interrupt the CPU and call a special function to load OCR1A with the next value in the waveform. This function is called an interrupt service routine (ISR), and is called by timer2 whenever TCNT2 becomes equal to OCR2A. The ISR itself is written just like any other function, except that it has no return type. The Arduino Nano’s system clock runs at 16MHz, which will cause timer2 to call the ISR far too quickly. We must slow it down by engaging the “prescaler” hardware, which divides the frequency of system clock pulses before letting them increment TCNT2. We’ll set the prescaler to divide by 8, which makes TCNT2 update at 2MHz. To control the frequency of the generated waveform, we simply set OCR2A. To calculate the frequency of the resulting wave, divide the rate at which TCNT2 is updated (2MHz) by the value of OCR2A, and divide the result by the length of the lookup table. Setting OCR2A to 128, for example, gives a frequency of: which is roughly the B that’s 2 octaves below middle C. Here’s a table of values giving standard musical notes. The ISR takes some time to run, for which we compensate by setting TCNT2 to 6, rather than 0, just before returning. To further tighten the timing, I’ve added the instruction asm(“NOP;NOP”), executing 2 “no operation” instructions using one clock cycle each. Run the sketch and connect a resistor and capacitor (Figure G). You should see a smooth sine wave on connecting an oscilloscope to Vout. If you want to hear the output through a small speaker, add a transistor to boost the signal (Figure H, below). Once you know how to “play” a wave from a lookup table, creating any sound you want is as easy as storing the right values in the table beforehand. Your only limits are the Arduino’s relatively low speed and memory capacity. Listing 2 contains a waveform() function to prepopulate the table with simple waveforms: SQUARE, SINE, TRIANGLE, RAMP, and RANDOM. Play them to see how they sound (below). A SQUARE waveform can have a timbre ranging from round and fluty to thin and reedy, depending on its duty cycle. From our initial experiments with bit banging, we already know that a 50% duty cycle gives a flute-like sound. A SINE waveform consists of a smoothly oscillating curved signal representing the graph of the trigonometric function. It produces a clear, glassy tone that sounds very much like a tuning fork. A TRIANGLE waveform looks a little like a sine wave with sharp points and straight lines, or 2 ramp waveforms squashed back to back. It has a more interesting, rounded sound than a sine wave, a little like an oboe. A RAMP waveform consists of steadily increasing values, starting at zero. At the end of the waveform the value suddenly drops to zero again to begin the next cycle. The result is a sound that’s bright and brassy. A RANDOM waveform can sound like anything, in theory, but usually sounds like noisy static. The Arduino produces only pseudorandom numbers, so a particular randomSeed() value always gives the same “random” waveform. The RANDOM function just fills the table with pseudorandom integers based on a seed value. Changing the seed value using the randomSeed() function allows us to generate different pseudorandom sequences and see what they sound like. Some sound thin and weedy, others more organic. These random waveforms are interesting but noisy. We need a better way of shaping complex waves. In the 19th century, Joseph Fourier showed that we can reproduce, or synthesize, any waveform by combining enough sine waves of different amplitudes and frequencies. These sine waves are called partials or harmonics. The lowest-frequency harmonic is called the first harmonic or fundamental. The process of combining harmonics to create new waveforms is called additive synthesis. Given a complex wave, we can synthesize it roughly by combining a small number of harmonics. The more harmonics we include, the more accurate our synthesis. Professional additive synthesizers can combine over 100 harmonics this way, and adjust their amplitudes in real time to create dramatic timbre changes. This is beyond the power of Arduino, but we can still do enough to load our wave table with interesting sounds. Figure J—Adding the third harmonic creates a waveform that has a distinctly square look and sound, though still very rounded. Consider the loop in Listing 1 that calculates a sine wave. Call that the fundamental. To add, say, the third harmonic at 1/4 amplitude (Figure J), we add a new step: for (int i=0; i<LENGTH; i++) { // Step across table float v = (AMP*sin((PI2/LENGTH)*i)); // Fundamental v += (AMP/4*sin((PI2/LENGTH)*(i*3))); // New step wave[i]=int(v+OFFSET); // Store as integer } In this new step, we multiply the loop counter by 3 to generate the third harmonic, and divide by an “attenuation” factor of 4 to reduce its amplitude. Listing 3 (available at makezine.com/35) contains a general version of this function. It includes 2 arrays listing the harmonics we want to combine (including 1, the fundamental) and their attenuation factors. Figure K—Adding the first 8 odd harmonics gives a fairly good approximation of a square wave. Individual sine waves appear as little ripples. Combining more partials would reduce the size of these ripples. To change the timbre of the sound loaded into the lookup table, we just alter the values in the 2 arrays. A zero attenuation means the corresponding harmonic is ignored. The arrays in Listing 3, as written, produce a fairly good square wave (Figure K). Experiment with the arrays and see what sounds result. Professional synthesizers contain circuits or programs to “filter” sound for special effects. For instance, most have a low-pass filter (LPF) that gives a certain “waa” to the start and “yeow” to the end of sounds. Basically, an LPF gradually filters out the higher partials. Computationally, true filtering is too much for Arduino, but there are things we can do to the sound, while it’s playing, to give similar effects. Listing 4 includes a function that compares each value in the wave table to a corresponding value in a second “filter” table. When the values differ, the function nudges the wave value toward the filter value, slowly “morphing” the sound as it plays. Using a sine wave as the “filter” approximates true low-pass filtering. The harmonics are gradually removed, adding an “oww” to the end. If we morph the other way — by loading the wave table with a sine wave and the “filter” table with a more complex wave — we add a “waa” quality to the start. You can load the 2 tables with any waves you like. What if we want to make a sound fade away, like a real instrument that’s been plucked, strummed, or struck? Listing 5 contains a function that “decays” the sound to silence by steadily nudging the wave table values back toward a flat line. It steps across the wave table, checking each value — if it’s more than 127, it’s decremented, and if less, incremented. The rate of decay is governed by the delay() function, called at the end of each sweep across the table. Once the wave is “squashed,” running the ISR just ties up the CPU without making sound; the cli() function clears the interrupt flag set in setup by sei(), switching it off. The Arduino’s Atmel processor is based on the “Harvard” architecture, which separates program memory from variable memory, which in turn is split into volatile and nonvolatile areas. The Nano only has 2KB of variable space, but a (relatively) whopping 30KB, or so, of usable program space. It is possible to store wave data in this space, greatly expanding our repertoire of playable sounds. Data stored in program space is read only, but we can store a lot of it and load it into RAM to manipulate during playback. Listing 6 demonstrates this technique, loading a sine wave from an array stored in program space into the wave table. We must include the pgmspace.h library at the top of the sketch and use the keyword PROGMEM in our array declaration: prog_char ref[256] PROGMEM = {128,131,134,…}; Prog_char is defined in pgmspace.h and is the same as the familiar “byte” data type. If we try to access the ref[] array normally, the program will look in variable space. We must use the built-in function pgm_read_byte instead. It takes as an argument the address of the array you want to access, plus an offset pointing to individual array entries. If you want to store more than one waveform this way, you can access the array in pgm_read_byte like a normal two-dimensional array. If the array has, say, dimensions of [10][256], you’d use pgm_read_byte(&ref[4][i]) in the loop to access waveform 4. Don’t forget the & sign before the name of the array! To read wave table data from program memory, you have to hard-code it into your sketch and can’t generate it during runtime. So where does it come from? One method is to generate wave table data in a spreadsheet and paste it into your sketch. We’ve created a spreadsheet that will allow you to generate wave tables using additive synthesis, to see the shape of the resulting waves, and to copy out raw wave table data to insert into your sketch. Download it here. Audio feedback is an important way of indicating conditions inside a running program, such as errors, key presses, and sensor events. Sounds produced by your Arduino can be recorded into and manipulated by a software sampler package and used in music projects Morphing between stored waveforms, either in sequence, randomly, or under the influence of performance parameters, could be useful in interactive art installations. If we upgrade to the Arduino Due, things get really exciting. At 84MHz, the Due is more than 5 times faster than the Nano and can handle many more and higher-frequency partials in fast PWM mode. In theory, the Due could even calculate partials in real time, creating a true additive synthesis engine.
http://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/
CC-MAIN-2015-32
refinedweb
3,009
61.06
Opened 9 years ago Closed 8 years ago Last modified 8 years ago #7497 closed enhancement (fixed) I18N/L10N support for plugins Description I'm opening this ticket to get some opinions on how the localization of trac plugins should be done. There are several options: - Merge trac catalogs and plugin catalogs at runtime, but this might be a disadvantage because while merging catalogs, if 2 of them share the same msgid, the one being merged will override the existing one, ie, the trac one, allowing plugins to introduce translation errors which might make users create new ticket's for trac and not the plugin in question. - Make use of msgctxt. Each plugin will have it's name as it's context but this might be abusing a bit of the msgctxt. Defenition here. - Make use of domains. Each plugin will have it's own domain, and all localization calls must include the domain. Now, some more problems: - Babel's msgctxtsupport is close to Nonecurrently and it's meant for 1.0, only some minor work has been done. - Genshi's msgctxtsupport is non-existant mostly because Babel does not yet support it. - Regarding the domain option, while this is easy inside python files, it won't be that easy regarding templates; perhaps a i18n:domainattribute should be added to genshi allowing a template to define it's domain and thus, allowing genshi to pass the domain when translating the message. I'm tending towards the domain option, nothing will have to change regarding Babel and changes regarding genshi shouldn't be that much. Also, regarding plugin developers, this would just mean using another translation function other than gettext or _ for example, and passing an extra arg; perhaps one could even do some code magic to ease this. A new extension point would probably also be created so that plugins can register their domain and respective catalogs into trac's translator. Attachments (5) Change History (35) comment:1 Changed 9 years ago by comment:2 Changed 9 years ago by Oh, the only thing is that plugins must not have their catalog's domain be messages, they should be for the above example, my_module_messages. comment:3 Changed 9 years ago by comment:4 Changed 9 years ago by Updated patch. comment:5 Changed 9 years ago by This latest patch depends on ticket:137. Changed 9 years ago by Changed 9 years ago by comment:6 Changed 9 years ago by You can now disregard the support_genshi_i18n_choose.patch, that one would only work for python code. The really good patch is the plugin_i18n_support.patch. This one also depends on ticket:137 and ticket:129, both this tickets have patches not yet applied to their sources. Those patches reached good working point and are just waiting for cmlenz to review and check them in. Do note that with all 3 patches applied to all sources, plugin developers will then have the change to provide translations on a separate domain for their plugins. This works for both python code and genshi templates. comment:7 Changed 8 years ago by In plugin_i18n_support.patch, I don't like so much the sys._getframe(1).f_globals.get('domain') hack. What about this alternative, e.g.: (in myplugin/__init__.py) from trac.util.translation import dgettext def _(string, **kwargs): return dgettext('mydomain', string, **kwargs) (in myplugin/backend.py) from trac.core import Component from myplugin import _ class MyPlugin(Component): def __init__(self): self.log.info(_("MyPlugin %(version)s loaded ", version="0.1")) Also, what's the status of the dependencies? Is using Babel:milestone:0.9.4 and Genshi:r954 (trunk) enough for experimenting with the attachment:plugin_i18n_support.patch? comment:8 Changed 8 years ago by Looks like Genshi:source:branches/experimental/advanced-i18n is needed. I had to fix a few conflicts for the patch above, due to recent changes in trunk. The add_domain could probably benefit from some locking, as it manipulates a global, otherwise this seems risky (IIUC, that add_domain has to be called from plugins in their __init__ method). Finally, looking at Babel:r448, it seems that the way to add a domain to the translations has changed since you wrote the patch. I'm posting a work-in-progress patch which at least applies cleanly, but I have yet to try the domains with a plugin. Changed 8 years ago by Updated patch - applies cleanly on current trunk, normal translations are working but I've not yet tested add_domain comment:9 Changed 8 years ago by Ah yes, the patch also introduce a bug by using translation.get_translations() when creating the Translator object: That will associate permanently the currently activated Translations object with the template as the TemplateLoader will only call the callback on first load. From then on, the template will be retrieved from the cache and the filter will keep using the original Translations object, not the currently activated one. This can be easily verified, e.g. on the preference page itself, if you start in German, then switch to French: the translations coming from the html template will stay in german, those obtained from the code will be in french. Suggested fix: we should instead pass a Translations "proxy" that has its translation methods delegating the call to the currently active Translations instance. comment:10 Changed 8 years ago by Sorry for not helping that much now, but I've started a clean install on my laptop yesterday and my development environment is not yet up and running. I also thought I had submited a reply which I'm now not seeing but I guess you did find the right branch :) I'll test what you propose as soon as possible. Changed 8 years ago by Version améliorée, well, improved version of the i18n support for plugin comment:11 follow-up: 12 Changed 8 years ago by In attachment:plugin_i18n_support-r7678.patch, I did several refactorings: - fixed the bug explained in comment:9 by introducing a TranslationsProxyclass. - removed the sys._getframe(1)...hack from the TranslationsProxy*gettext methods Also, I tested the add_domain capability on the Mercurial plugin, along the way suggested in comment:7. The tracext.hg.__init__.py contains the translation marker/substitution functions: import pkg_resources from trac.util.translation import dgettext, dtgettext, add_domain domain = "tracmercurial" def _(string, **kwargs): return dgettext(domain, string, **kwargs) def tag_(string, **kwargs): return dtgettext(domain, string, **kwargs) def N_(arg): return arg def add_plugin_domain(env_path): locale_dir = pkg_resources.resource_filename(__name__, '../locale') add_domain(env_path, domain, locale_dir) The adaptations to the tracext.hg.backend.py are minimal: # ... from tracext.hg import _, tag_, N_, add_plugin_domain # only the add_plugin_domain() line is new: class MercurialConnector(Component): implements(IRepositoryConnector, IWikiSyntaxProvider) def __init__(self): self._version = None self.ui = None add_plugin_domain(self.env.path) Also the setup.cfg contains the domain spec: [extract_messages] add_comments = TRANSLATOR: msgid_bugs_address = cboos@neuf.fr output_file = tracext/locale/messages.pot keywords = _ ngettext:1,2 N_ tag_ width = 72 [init_catalog] input_file = tracext/locale/messages.pot output_dir = tracext/locale domain = tracmercurial [compile_catalog] directory = tracext/locale domain = tracmercurial [update_catalog] input_file = tracext/locale/messages.pot output_dir = tracext/locale domain = tracmercurial I have yet to test what happens for a conflict (i.e. when a translation in the tracmercurial catalog differs from one in the base trac message catalog), but other than that it seems to work fine. comment:12 Changed 8 years ago by Follow-up to comment:11 I have yet to test what happens for a conflict (i.e. when a translation in the tracmercurial catalog differs from one in the base trac message catalog), Conflicts are handled correctly, domain translation is preferred, falling back to the main catalog if not found in the domain catalog. Nicely done on the Babel level! Now, I came up with a helper function that simplifies the setup for domain specific translations functions. One has simply the following to do in his/her plugin, e.g. for tracext/hg/backend.py: from trac.util.translation import domain_functions _, tag_, N_, add_domain = domain_functions('tracmercurial', '_', 'tag_', 'N_', 'add_domain') # use _, tag_ and N_ as usual, e.g. _("this is a diff") class MercurialConnector(Component): implements(IRepositoryConnector, IWikiSyntaxProvider) def __init__(self): self._version = None self.ui = None # bind the 'tracmercurial' catalog to the specified locale directory locale_dir = pkg_resources.resource_filename(__name__, '../locale') add_domain(self.env.path, locale_dir) There are a few things left to be done on the patch: - add locking for add_domain(comment:8) - add a dummy domain_functionsfor the case Babel is not present See attachment:plugin_i18n_support-domain_functions.patch Changed 8 years ago by Same as previous patch, with a new helper function domain_functions to ease the setup of plugins. comment:13 follow-ups: 14 attributes everywhere in Trac? In the meantime, I'm using Genshi 0.5.1 for the extraction. comment:14 follow-up:attributes everywhere in Trac? In the meantime, I'm using Genshi 0.5.1 for the extraction. Well,? You should now use genshi.filters.i18n.setup_i18n. Ie, trac should be doin' something like this. comment:15 Changed 8 years ago by comment:16 follow-up: 17 Changed 8 years ago by …? Well, I'm talking about the Trac codebase. I use latest trunk + the patch above, which seems to call setup_i18n as appropriate (but maybe not, I didn't touch that part of the original patch). That's on the usage side, though.? comment:17 Changed 8 years ago by? I've added a testcase to genshi's advanced i18n branch(have a look)with a code snippet grabbed from macros.html which succeeds, I'll see if I can catch the bug(lack of code/i18n setup) somehere else. comment:18 Changed 8 years ago by heh, failed the macros.html link :) comment:19 Changed 8 years ago by Ok, found the bug!!! The issue happens because of the py:strip used, must be something failing on the genshi's advanced i18n branch. Here's the failing testcase which reproduces the problem you noticed. comment:20 Changed 8 years ago by The issue is happening because currently I'm pop'ing the strip directive while extracting, something that was needed by some reason which I know don't remember now, but has something to do with the 3 failing testcases if I don't pop it ;) I'll see what I can do regarding this issue. comment:21 Changed 8 years ago by Please update your genshi advanced i18n branch and see if latest changes fix the problems you found. comment:22 follow-up: 23 Changed 8 years ago by Works fine with Genshi:r966, thanks! Now, any suggestion about the patch itself and domain_functions or can I finalize it as presented in comment:12? comment:23 Changed 8 years ago by Works fine with Genshi:r966, thanks! Now, any suggestion about the patch itself and domain_functionsor can I finalize it as presented in comment:12? Nope, no suggestions, your solution is much cleaner, go for it! comment:24 follow-up: 27 Changed 8 years ago by comment:25 follow-ups: 26 28 Changed 8 years ago by comment:26 Changed 8 years ago by There's a problem with [7705], as it tries to import setup_i18nfrom genshi.filters, but this symbol is present neither in 0.5.1 nor in Genshi trunk, only in the advanced-i18nbranch. Maybe setup_i18nshould be imported conditionally? Push cmlenz to review the branch and include those changes into trunk ;) comment:27 Changed 8 years ago by comment:28 Changed 8 years ago by comment:29 Changed 8 years ago by Unfortunately, this was not enough, in the case where Babel is not installed: - The various d(|n|t|tn)gettext()functions are missing. - There's a typo in domain_functions(). activate()is missing the second argument. - There was a regression of the fix from [7480]. I fixed these in [7713]. All unit tests pass here, but it looks like Bitten is still choking on something. Ah, got it, the functools module was introduced in 2.5. Fixed in [7714]. comment:30 Changed 8 years ago by Thanks for fixing the breakage, I'm focusing on the Python 2.5/Babel-0.9.4/Genshi advanced-i18n combination for now… About partial: we have it in compat, i.e. from trac.util.compat import partial. For the i18n ns error, I was looking in the wrong direction, thought we had to tweak something at the lxml level, I probably missed [7480]. The above patch allows plugins to provide their own translations. Unlike other projects which just merge catalogs together possibly overriding a good translation for a bad one, this patch "detects" if the caller of the function has a domainvariable defined on top of file, if it has, it switches to that domain, translates and then switches back to trac's domain. So, plugin developers should start defining the domain. As an example, consider the following file my_module/web_ui.py: So, imagine a request to the above component comes in using pt_PTfor the locale. What happens is that the pt_PTtranslations on MyPackage/my_module/localeare loaded, "Foo" is translated and then the trac translations are loaded back.
https://trac.edgewall.org/ticket/7497
CC-MAIN-2017-17
refinedweb
2,193
55.74
Forum:Official PLS Category Vote - Vote Now or Forever Hold Your Peace From Uncyclopedia, the content-free encyclopedia Alrighty, it's go time. Let's try to get this cleaned up by Monday so the competition can begin. This is an attempt to finalize public opinion on which categories should be in the upcoming Poo Lit Surprise. We're going to 5 Categories this year, and I think it'd be best to keep the 4 we've had so far, just for consistency's sake. We can always switch 'em next time if we feel the need. So basically this vote is for what the 5th Article Category should be. My personal preference, and I think we should go with, is Best Alternate Namespace, that is, best article with something in front of it, say UnNews, UnScript, UnPoetia, UnTunes, whatever. But I want a little bit of public opinion before making my final decision, so shoot. I want get this settled by the end of Sunday so we can get this deal rolling on Monday. So here it is, go forth and vote for the final category. Sir ENeGMA (talk) GUN WotM PLS 03:31, 24 June 2007 (UTC) Discussion In order to save some header space, I'll discuss my reasoning here, as to why I support the Best Alternate Namespace idea. I think this is the best because, after having talked it over with some people, it seems like the least restrictive, most creative category currently on the table. I would really like to see stuff like UnPoetia in the PLS, and this seems like a good way to do it. We need more content from the obscure namespaces, and this might help us grow a sector of the site that isn't that large right now. So that's why I really like this idea, and I hope you do too. Sir ENeGMA (talk) GUN WotM PLS 03:35, 24 June 2007 (UTC) - I second that. After discussing things in the chatroom, I do feel that an alternative namespace category would be best so as to promote things like UnPoetia, UnNews, and other namespaces and to give them an opportunity to enter. I'd prefer this over style and topic-specific categories like "Best First Person Article" or "Best Article About A Historical Event". My only concern is that UnPoetia or UnNews may not be able to compete against an article in the UnBook, HowTo, or Why? namespace. But I have faith in whoever will be judging that category, and I think this would be best. --Hotadmin4u69 [TALK] 03:53, 24 June 2007 (UTC) - I think that e|m|c's concerns, while not unfounded, are not going to be problematic. I say this because, in our history, the two most favored articles for feature have been from UnPoetia and Why?.-Sir Ljlego, GUN VFH FIYC WotM SG WHotM PWotM AotM EGAEDM ANotM + (Talk) 20:38, 24 June 2007 (UTC) - Good point. --Hotadmin4u69 [TALK] 20:40, 24 June 2007 (UTC) - Woo! Why? namespace, you go girl. —Braydie 00:32, 25 June 2007 (UTC) - Bitch, just step off!12:33, 25 June 2007 Aside from the obvious Best Article by Mhaille, you've missed out the No Fifth Category've took the liberty of making that decision already, as I received on objections to it that I can recall. Sir ENeGMA (talk) GUN WotM PLS 00:43, 25 June 2007 (UTC) - Also, Most Mediocre Article. - June 2007 (UTC) - I vote for Best ICUed Article, or Best Supporting Act of Vandalism. --Whhhy?Whut?How? *Back from the dead* 10:08, 25 June 2007 (UTC)
http://uncyclopedia.wikia.com/wiki/Forum:Official_PLS_Category_Vote_-_Vote_Now_or_Forever_Hold_Your_Peace?t=20130519041305
CC-MAIN-2016-40
refinedweb
606
68.91
🔑 GetKey Function Tutorial 🔑 [deleted] 🔑 GetKey Function Tutorial 🔑 Hope you are enjoying school Importing from getch import getche as getkey For the getkey part, you don't need to do what I did. Name it whatever you want. Name your getkey[or whatever the name is] function name_here = getkey() Ending Now since you have your function ready, do whatever you want with it here is a thing you can do: I hoped you enjoyed the tutorial! [email protected] Voters well that was short lol.. perhaps include a program with explanation? :) @Bookie0 okay added some explanation in the program @XThacker what does os.system('clear')do? and what do you mean importing something as something? and what does the elsedo? ofc I know those, but imagine those who don't. ;) @Bookie0 k, fixed. great @XThacker @Bookie0 thanks yep! @XThacker @Bookie0 not relatedHow did you get 5061 cycles?! @XThacker How did you get 42? It's cycles earned with my posts/comments/answers I've made. And I recently made this tutorial.
https://repl.it/talk/learn/GetKey-Function-Tutorial/116955
CC-MAIN-2021-10
refinedweb
169
77.64
Interface IMXMLObject cannot be imported or found I am developing one game with robotlegs 2 and i just faced with a strange problem, it says there is not IMXMLObject interface to be implemented inside ContextBuilderTag class of RobotLegs2. I am using Intellij with air sdk 3.8 and pure action script with no flex component. Comments are currently closed for this discussion. You can start a new one. Keyboard shortcuts Generic Comment Form You can use Command ⌘ instead of Control ^ on Mac Support Staff 1 Posted by Ondina D.F. on 01 Jul, 2013 01:44 PM Hi Rafael, The ContextBuilderTag is meant to be used with Flex, inside the declaration tag:If you’re not using Flex, create the context like this: Ondina Support Staff 2 Posted by Ondina D.F. on 01 Jul, 2013 01:55 PM In the previous post I mistakenly wrote: private var _context:AppConfig; I corrected it: private var _context: IContext; see:... 3 Posted by Rafael Felisbin... on 01 Jul, 2013 03:13 PM That´s not my problem, i am already creating my context like this. The thing is that i just cloned it and i got an error telling that there is no interface IMXMLObject at the package 'mx.core.IMXMLObject;' Here is the declaration of class "ContextBuilderTag": 'package robotlegs.bender.mxml{' 'public class ContextBuilderTag implements IMXMLObject{}}' Support Staff 4 Posted by Ondina D.F. on 01 Jul, 2013 04:25 PM Are you using the release build of rl2? Is it possible to paste the code where you create the context? Are other rl projects working as expected? Are you compiling against the rl’s source?... I don’t know if there are Intellij specific settings regarding metadata that you might take under consideration. I’m using FlashBuilder. If that’s not it, then I have no idea what’s going on :) Support Staff 5 Posted by Shaun Smith on 01 Jul, 2013 04:57 PM The simplest solution is to use the official, released RL SWC from If you want to compile the source yourself you have to use the Flex compiler. Even though RL will work with plain AS3 projects, it has to be compiled with the Flex SDK. 6 Posted by Rafael Felisbin... on 02 Jul, 2013 05:35 AM i am now using only the swc and i dont get the error anymore. Maybe i was missing some libraries, i dont know, but now its ok and i am creating my context like this: _context=new Context().install(MVCSBundle, StarlingViewMapExtension, SignalCommandMapExtension) .configure(ClassConfig, new ContextView(this)); Support Staff 7 Posted by Ondina D.F. on 02 Jul, 2013 06:38 AM Rafael, it’s good to hear it’s working. I’m closing this for now. Feel free to reopen this discussion, if you're still having problems. Please open new threads for new issues. Ondina D.F. closed this discussion on 02 Jul, 2013 06:38 AM.
http://robotlegs.tenderapp.com/discussions/robotlegs-2/3694-interface-imxmlobject-cannot-be-imported-or-found
CC-MAIN-2019-22
refinedweb
491
73.47
Y: $ sudo yum install yara -y Ubuntu, Debian: $ apt install yara Yara help information can be listed simply like below. $ yara -h We can see also the usage of yara command like below. Yara supports target as binary file, directory or process id as we see below. yara [OPTION]... RULES_FILE FILE | DIR | PID rule dummy { condition: true } Download Binary Sample We will download our binary samples from web. Our sample binary is popular ssh client named Putty . Download following link to get. We use wget for Linux for download operation. $ wget Run Yara Now we can run our first rule with yara. $ yara myrule putty.exe The result is not se exiting but it works. This rule file simply print text dummy and the file name in this example putty.exe Rule Yara rule syntax is similar to C programming language. Here is a simple rule named myrule . rule myrule { strings: $my_text_string = "text here" $my_hex_string = { E2 34 A1 C8 23 FB } condition: $my_text_string or $my_hex_string }. //Single line commen /* Multi line . rule name_putty { strings: $pname="putty" condition: $pname } If we run the rule like below the rule matches the condition and prints the rule name with the binary name. $ yara myrule putty.exe. rule name_putty { strings: $pname=/p[0-9a-zA-Z]tty/ condition: $pname }. rule name_putty { strings: $pname=/p[0-9a-zA-Z]tty/ condition: $pname and filesize > 500KB }>) For example in this example we will check whether given file is a Portable Executable (PE) file. rule ThisIsPE { condition: // MZ signature at offset 0 and ... uint16(0) == 0x5A4D and // ... PE signature at offset stored in MZ header at 0x3C uint32(uint32(0x3C)) == 0x00004550 }. global rule SizeLimit { condition: filesize < 2MB } Private Rules Yara provides inheritance like feature to create basic rules and create super rules which inherits these basic rules conditions. In this situations we can use private keyword before rule definition. We will use private rules for building blocks of other rules. private rule PrivateRuleExample { ... } Rules Tags Tags are used while printing the matched rules in order to filter. They have no effect on matching. There is no restriction about tag count. In this rules Foo , Bar and Baz are tags of the rules. rule TagsExample1 : Foo Bar Baz { ... } rule TagsExample2 : Bar { ... } Metadata We may need to specify additional information about the rule. We can use metadata for this work. We will create a new section with meta: keyword like below. rule MetadataExample { meta: my_identifier_1 = "Some string data" my_identifier_2 = 24 my_identifier_3 = true strings: $my_text_string = "text here" $my_hex_string = { E2 34 A1 C8 23 FB } condition: $my_text_string or $my_hex_string } Modules Modules are extensions for YARA. We can use some modules like PE or Cuckoo those comes with YARA. We can also write our own modules too. Modules can be imported with import statement. In this example we will import and use PE module. import "pe" rule Test { strings: $a = "some string" condition: $a and pe.entry_point == 0x1000 } Including Other Files We can include other rule files with include keyword. We will simply include other yara rule files in the following example. We can use relative or absolute path without a problem. include "/home/poftut/basics.yara"
https://www.poftut.com/yara-identify-classify-malware-samples/
CC-MAIN-2020-50
refinedweb
524
68.36
How to close QDialog Hi, Which is the best way of closing a dialog? In my program when someone filled out a form have an option to fill out an other one or stop entering new data, in which case I need to close the dialog includes the data entry form. Please help me to find the best way. (I tried to use QDialog::~QDialog, and reject() but didn't work.) Thank you. @gabor53 Isn't the user closing the dialog? Or why do you want to do it? If you really need to do it you can call QDialog::accepted() or reject() as you said. Why did reject() not work? What was the problem? And how do you actually call it? Can you show relevant code? - raven-worx Moderators last edited by @gabor53 can you please be more specific than "didn't work"? accept()/reject()/done() should all work perfectly fine... @jsulm I have 3 dialogs: mainwindow, additem and review. additem is opened from mainwindow using a pushbutton using the following code: void MainWindow::on_actionAdd_Item_triggered() { Additem *mAddItem = new Additem; mAddItem->exec (); } Additem is a data entry form. When the user finished, he has an option to click on a pushbutton and review the entries in a different dialog, called review. review is opened with this code: review *mReview = new review(this); mReview->dispRev (sID,name,fileName, newWhat,newMaterial, newColor, description, month, day, year, newSignedby, history, age, notes); mReview->show (); When data is reviewed there is an option to add the data to the database: void review::on_submit_Button_clicked() { QMessageBox reviewMsgBox; reviewMsgBox.setText ("<b><font size='16' color='green'> Is everything correct? (Choosing yes will add the Friend to the database.)</font></b>"); reviewMsgBox.setStandardButtons (QMessageBox::Yes | QMessageBox::No); int ret = reviewMsgBox.exec (); switch(ret) { case QMessageBox::Yes: { qDebug() << "Yes was clicked."; qDebug() << "Name from review.cpp: " << AdoptDater; Additem *mAdditem = new Additem; mAdditem->FunctAddtoDb (sIDr, namer, newWhatr, newMaterialr, newColorr, descriptionr, monthr, dayr, yearr, newSignedbyr, historyr, ager, notesr, byteArrayr); review::close (); } break; case QMessageBox::No: { qDebug() << "No was clicked!"; review::close (); } break; } } When it is all done and the data added to the database, and if the user does not want to add more data all data QDialogs review and Additem should be closed (the problem is they do not close). This is the code: QMessageBox addMoreMsgBox; addMoreMsgBox.setText ("<b><font size='16' color='green'>The Friend is added to the database. Do you want to add some more?</font></b>"); addMoreMsgBox.setStandardButtons (QMessageBox::Yes | QMessageBox::No); int ret = addMoreMsgBox.exec (); switch(ret) { case QMessageBox::Yes: { SubmitButton->setDisabled (false); SubmitButton->setStyleSheet ("QPushButton{" "background-color: rgb(0, 255, 0);" "border-style: outset;" "border-width: 2px;" "border-radius: 10px;" "border-color: beige;" "font: bold 14px;" "min-width: 10em;" "padding: 6px;}" ); Addcontent(); } break; case QMessageBox::No: { qDebug() << "Close from messagebox"; Additem::close (); } } } void Additem::Addcontent() { SubmitButton->setDisabled (false); SubmitButton->setStyleSheet ("QPushButton{" "background-color: rgb(0, 255, 0);" "border-style: outset;" "border-width: 2px;" "border-radius: 10px;" "border-color: beige;" "font: bold 14px;" "min-width: 10em;" "padding: 6px;}" ); QFont g("Arial", 16, QFont::Normal); @gabor53 You did not post code for your dialogs. How are Additem and review implemented? Do you have any buttons user can press to close the dialogs? Either accept() or reject() must be called. And this code should actually show Additem dialog as a modal dialog: mAddItem->exec (); So, at least this dialog is closed, right? Else you cannot proceed with anything else. @jsulm You are right that one closes. Here are the codes: mainwindow.cpp additem.cpp review.cpp Thank you for your help. @jsulm There is a button on the review.ui they can click and close. One of my issue is that is it possible to click on close on review.ui and close both review and additem? You can call accept() or reject() on additem when you close review. First of all it will be quite unexpected behaviour if you would close addItem when user closes review! As user I would expect that if I close review only review is closed. If I understand your code correctly the flow is: add an Item via addItem, from addItem open review to review the item (optional?), then close review, close addItem. So, closing child dialog should not close parent dialog. But if you really want to do it this way then just call mAddItem->accept(); You would need to pass the pointer to AddItem instance to review. mAddItem->accept(); doesn't do anything. The surrounding code: QMessageBox::StandardButton reply; reply = QMessageBox::information(this, "Confirmation","<b><font size='16' color='green'>The Friend is added to the database. Would you like to add more Friends?</font></b>",QMessageBox::Yes | QMessageBox::No); Additem *mAdditem = new Additem; if(reply == QMessageBox::Yes) { qDebug() << "Yes was clicked."; } else { mAdditem->accept (); } @gabor53 What is this code supposed to do? You create an instance of Additem, but you do not show it - at least you do not call mAdditem->show() or mAdditem->exec() @jsulm Im trying to close the additem dialog that originally generated the review. So it was called from mainwindow. I created a new project with 2 dialogs, the sources are mainwindow.cpp and dialog.cpp. The code in dialog.cpp looks like this: #include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog() { delete ui; } void Dialog::message() { QMessageBox::StandardButton reply; reply = QMessageBox::information(this, "Confirmation","<b><font size='16' color='green'>Do you want to close the 2nd window?</font></b>",QMessageBox::Yes | QMessageBox::No); if(reply == QMessageBox::Yes) { qDebug() << "Yes was clicked. Close 2nd."; this->reject(); } else { qDebug() << "No was clicked. Don't close 2nd."; } } void Dialog::on_pushButton_clicked() { message(); } When I click yes, it does what I want, it closes dialog. When I use the same code in my original application, it does nothing (no error message either). What can cause this completely different behavior? Thank you.
https://forum.qt.io/topic/67693/how-to-close-qdialog/16
CC-MAIN-2019-47
refinedweb
986
58.48
Extension board's PIN Hi, I am struggling to find out which PIN the extension board's button is connected to. I've tried every PIN I found in machine.PIN.boards but without success. Could you help please? Thanks, Hans With a LoPy updated to 0.9.1.b1 (the only one to succeed of four attempted so far), the GPIO (including IRQs) work better. This sample uses an interrupt to make the LED toggle: import machine led=machine.Pin("G16",machine.Pin.OUT) button=machine.Pin("G17",machine.Pin.IN, pull=machine.Pin.PULL_UP) def handler(button): led.toggle() irq=button.irq(trigger=button.IRQ_FALLING, handler=handler) Note that the button itself will bounce, so this won't reliably toggle just once per press. I've managed to read the button, with some effort. It looks like MicroPython 0.9.0.b2 on the LoPy is a little confused about the GPIO functionality. The button is on expansion board G17 (G16 is the LED), which internally maps to GPIO 10 (luckily this is done for us). However, it needs to be configured to input with pullup, and that's where the example fails us. It was supposed to be: button = Pin("G17", mode=Pin.IN, pull=Pin.PULL_UP) However, the PULL_UP mode isn't correctly mapped in this version. I succeeded using mode 3, which it thinks means OPEN_DRAIN: button = Pin("G17", mode=3) After that, button()or button.value()read correctly (0 when pressed, otherwise 1). This is a firmware bug where pullup is not enabled by the pull setting. Hopefully it will be fixed so later versions don't need such hacks. Dear Hans, The Pin is G16. The details can be found in: Cheers, Daniel
https://forum.pycom.io/topic/8/extension-board-s-pin/1
CC-MAIN-2019-22
refinedweb
290
68.77
Analyzer increases process as more data loaded, using only stop Hi. I've developed an analyzer that uses a data list with 1700 stocks. Each stock has a pandas dataframe with information of his latest ticks OHLC and some indicators. All this information is created outside of cerebro. At stop method I look for different conditions, as for example if today's close is above the close of three days ago. As the length of each stock dataframe increases, the process time of the cerebro.run is worse (by seconds). I don't understand why does it happen if at stop I am iterating only the stocks, not each row of their pandas. How can improve the process time? (I've tried to define 'next' with pass, ...). The process is: - For all symbols I've in a database, I load their ticks and compute his indicators ... df['rsi'] = btalib.rsi(df, period=14).df df['atr'] = btalib.atr(df).df df = df.tail(5) data_list.append((df, symbol)) - This datafeed is added at cerebro: def execute_analysis(data_list, queries): start_time = timeit.default_timer() cerebro = bt.Cerebro() for i in range(len(self.data_list)): data = PandasData( dataname=data_list[i][0], # Pandas DataFrame name=data_list[i][1] # The symbol ) cerebro.adddata(data) cerebro.addanalyzer(ScreenerAnalyzer, _name="screener", queries=queries) - The run analyzer has only defined the method 'stop': class ScreenerAnalyzer(bt.Analyzer): def stop(self): print('{}: Results'.format(self.datas[0].datetime.date())) print('-'*80) self.rets = list() for i, d in enumerate(self.datas): ... Hi, again. Sorry, but I am stuck. Anyone has any suggestion? No sure I fully understand your confusion - but it is probably my confusion after all. The basic thing is that Cerebro.runwill iterate through all of your datas' dataframes anyway - regardless of whether or not you are implementing nextor stopin your strategy/analyzer or just leave the default nextor stopimplementation (which does nothing btw) in the corresponding inherited classes. So if the size of the dataframe increases so will the time it takes to iterate it. Is it what you've been missing? or is it me that doesn't understand your question? @vladisld My goal is to find stocks by technical indicators and other conditions (integrated in a React web app). My first implementation was to use a single cached pandas dataframe with one row for each stock. Each row had all the information needed for each stock (ATR, ATR(-1), ...). Each search lasted between 1 and 2 seconds. As I discovered Backtrader I liked a lot his architecture so I migrated everything to it. Now the query lasts 7-8 seconds, but if I increase one day the information for each stock dataframe, 1 second is increased (more or less). Are you telling then that all dataframes are iterated? I would like to create all information before run, so I can get information directly at stop. Thanks a lot for your support. Backtrader is working best for, well... back testing. So, neutralizing its main functionality in order to just iterate over all symbols just once seems to be sub optimal. I doubt it was designed for this scenario. IMHO it is better to just use native pandas/numpy apsi for whatever algo you are using for symbol selection.
https://community.backtrader.com/topic/3240/analyzer-increases-process-as-more-data-loaded-using-only-stop/1
CC-MAIN-2022-40
refinedweb
542
59.8
Warning: Wikipedia contains spoilers. 42 is the answer to the Question of Life, the Universe and Everything, as given by the supercomputer Deep Thought to a group of mice in Douglas Adams's The Hitchhikers Guide to the Galaxy.: 42. The computer informs the researchers that it will build them a second and greater computer, incorporating living beings as part of its computational matrix, to tell them what the question is. That computer was called Earth and was so big that it was often mistaken for a planet. The question was lost minutes before it was to be outputted, by the Vogons' demolition of the Earth, supposedly to build a hyperspace bypass. (Later in the series, it is revealed that the Vogons had been hired to destroy the Earth by a consortium of philosophers and psychiatrists who feared for their jobs should the meaning of life become common knowledge.) Lacking a real answer, the mice proposed to use "How many roads must a man walk down?" as the question for talk-shows (having rejected the question, "What's yellow and dangerous?" - actually a riddle whose answer, not given by Adams, is "Shark-infested custard"). At the end of the book The Restaurant at the End of the Universe (volume 2 of the Hitchhiker's trilogy),". Since 6 xans, which could account for the irrational nature of the question in Arthur's mind (as he himself is a descendant of the Golgafrinchans). However, it was later pointed out that 6 x 9 = 42 if the calculations are performed in base 13, not base 10. Douglas Adams was not aware of this at the time, and has denied that base 13 has anything to do with it. On the BBC Radio show of the book, the caveman spells in scrabble stones, "What is 6 times 9?" The man answers, "Forty-two. I always knew there was something fundamentally wrong about the Universe!" (And a faint voice can be heard shouting, "Base 13!") - Actually this last statement is untrue. Having carefully listened to the CD release of the radio series, no such shout is present, though there are sound effects at that point which while quite innocuous might be misheard if one really wanted to hear it that way (a bit like interpretations of the end of Sgt Pepper's Lonely Hearts Club Band). There is a joke amongst computer programmers that Deep Thought may have had some order of operations issues. The following code in the programming language C defines the variable SIX as "1 + 5" and NINE as "8 + 1", and then performs the computation "SIX * NINE". It returns the answer "42", because "SIX * NINE" is expanded by the computer to "1 + 5 * 8 + 1", and the multiplication takes precedence[?] over the additions. #include <stdio.h> #define SIX 1 + 5 #define NINE 8 + 1 int main() { printf( "The meaning of life: %d\n", SIX * NINE ); return( 0 ); } See also: Meaning of life
http://encyclopedia.kids.net.au/page/th/The_Answer_to_Life%2C_the_Universe%2C_and_Everything
CC-MAIN-2019-51
refinedweb
491
68.1
An model that manages a list of strings. More... #include <Wt/WStringListModel> An model that manages a list of strings. This model only manages a unidimensional list of items and is optimized for usage by view widgets such as combo-boxes. It supports all features of a typical item model, including data for multiple roles, editing and addition and removal of data rows. You can populate the model by passing a list of strings to its consructor, or by using the setStringList() method. You can set or retrieve data using the setData() and data() methods, and add or remove data using the insertRows() and removeRows() methods. Adds a string. Returns data at a specified model index for the given role. You should check the role to decide what data to return. Usually a View class will ask for data for several roles which affect not only the contents (Wt::DisplayRole) but also icons (Wt::DecorationRole), URLs (Wt::LinkRole), and other visual aspects. If your item does not specify data for a particular role, it should simply return a boost::any(). Implements Wt::WAbstractItemModel. Returns the flags for an item. This method is reimplemented to return flags set in setFlags(). Reimplemented from Wt::WAbstractItem. Inserts a string.. Returns the number of rows. This returns the number of rows at index parent. Implements Wt::WAbstractItemModel. Sets data at the given model index. Returns true if the operation was successful. The default implementation returns false. The model implementation must emit the dataChanged() signal after data was changed. Reimplemented from Wt::WAbstractItemModel. Sets model flags for an item. The default item flags are ItemIsSelectable | ItemIsEditable. Sets a new string list. Replaces the current string list with a new list. Sorts the model according to a particular column. If the model supports sorting, then it should emit the layoutAboutToBeChanged() signal, rearrange its items, and afterwards emit the layoutChanged() signal. Reimplemented from Wt::WAbstractItemModel. Returns the string list.
https://webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1WStringListModel.html
CC-MAIN-2021-31
refinedweb
322
60.92
This” where the web content is available to anonymous users. There are a lot of misconceptions about what is possible. This post will dive into some of the gory details of CSOM with anonymous access. This demonstration will use an on-premises lab environment instead of O365. Setting Up the Demonstration I created a new web application that allows anonymous access () and a site collection using the Publishing template. I then enabled anonymous access for the entire site by going to Site Settings/ Site Permissions and clicking the Anonymous Access button in the ribbon. Notice that checkbox “Require Use Remote Interfaces permission” that is checked by default… leave it checked for now. Next, I created a SharePoint-hosted app. I just slightly modified the out of box template. 'use strict'; var context = SP.ClientContext.get_current(); var user = context.get_web().get_currentUser(); $(document).ready(function () { getUserName(); }); function getUserName() { context.load(user); context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail); } function onGetUserNameSuccess() { if (null != user) { //The user is not null var userName = null; try { userName = user.get_title(); } catch (e) { userName = "Anonymous user!"; } } $('#message').text('Hello ' + userName); } function onGetUserNameFail(sender, args) { alert('Failed to get user name. Error:' + args.get_message()); } Next, I add a client app part to the project. The client app part isn’t going to do anything special, it just says Hello World. <%@.8> <h1>Hello, world!</h1> </body> </html> Next, I went to Central Administration / Apps / Manage App Catalog and created an app catalog for the web application. I published the SharePoint-hosted app in Visual Studio (which just generates the .app package) and then uploaded the .app package to the App Catalog. Next, as the site collection administrator, I added the app to the publishing site. Finally, I edit the main page of the publishing site and add the client app part and test that it works. Check in the page and publish and you should see something like this: What Do Anonymous Users See? The question on everybody’s mind is what happens if there is not an authenticated user. In our simple test, recall that the only thing we are showing is a simple IFRAME with some styling obtained from SharePoint. The only thing our IFRAME is showing is a page that contains static HTML, “Hello, world!”. I highlighted the “Sign In” link to show that I really am an anonymous user. Now, click the link “SPHostedClientWebPart Title” (yeah, I know, I am lazy… I should have given it a better name) and you are taken to the full-page experience for the app. What do we see? We get an error. That error is saying that the anonymous user does not have access to use the Client Side Object Model. Just for grins, let’s try the REST API with the URL. First, you get a login prompt. Next, you see error text that says you do not have access. This makes sense because the CSOM and REST API are not available by default to anonymous users. Enabling CSOM for Anonymous Users Let me start this section by saying what I am about to show you comes with some risk that you will need to evaluate for your environment. Continue reading the entire article to learn about the risks. That said, go back to Site Settings / Site Permissions and then click the Anonymous Access button in the ribbon. Remember that rather cryptic-sounding checkbox Require Use Remote Interfaces permission? Uncheck it and click OK. That check box decouples use of CSOM from the Use Remote Interfaces permission. When checked, it simply means that the user must possess the Use Remote Interfaces permission which allows access to SOAP, Web DAV, the Client Object Model. You can remove this permission from users, disabling their ability to use SharePoint Designer. There are cases where you still want to remove this permission, such as for anonymous users, but you still want to use the CSOM. This is exactly what the checkbox is letting you do; you are enabling use of CSOM without requiring the users to have that permission. To test the change, go back to the main page for your site. Of course, we still see the IFRAME from before, that’s not doing anything with CSOM. Click the title of the web part to see the full-page immersive experience. This time, we do not see an error message, instead we see that our code fell into an exception handler because the Title property of the User object was not initialized. Our error handling code interprets this as an anonymous user. You just used the app model in a public-facing SharePoint site with anonymous users. In case you are interested, you can set the same property with PowerShell using a comically long yet self-descriptive method UpdateClientObjectModelUseRemoteAPIsPermissionSetting. PS C:\> $site = Get-SPSite PS C:\> $site.UpdateClientObjectModelUseRemoteAPIsPermissionSetting($false) How about that REST API call? What happens with anonymous users now? Now that you know how to fire the shotgun, let’s help you move it away from your foot. All Or Nothing There is no way to selectively enable parts of the CSOM EXCEPT search. UPDATE: Thanks to Sanjay for pointing out that it is possible to enable search for anonymous without enabling the entire CSOM or REST API, and thanks to Waldek Matykarz for a great article showing how to do it. Enabling use of CSOM for anonymous users presents a possible information disclosure risk in that it potentially divulges much more information than you would anticipate. Let me make that clear: If you remove the require remote interface permission for an anonymous site, the entire CSOM is now available to anonymous users. Of course, that doesn’t mean they can do anything they want, SharePoint permissions still apply. If the a list is not made available to anonymous users, then you can’t use the CSOM to circumvent that security requirement. Similarly, an anonymous user will only be able to see lists or items that have been explicitly made available to anonymous users. It’s important to know that more than just what you see on the web page is now available via CSOM or REST. ViewFormPagesLockDown? Ha! In a public-facing web site using SharePoint, you want to make sure that users cannot go to form pages such as Pages/Forms/AllItems.aspx where we would see things like CreatedBy and ModifiedBy. The ViewFormPagesLockDown feature is enabled by default for publishing sites to prevent against this very scenario. This feature reduces fine-grained permissions for the limited access permission level, removing the permission to View Application Pages or Use Remote Interfaces. This means that an anonymous user cannot go to Pages/Forms/AllItems.aspx and see all of the pages in that library. If we enable CSOM for anonymous users, you still wont’ be able to access the CreatedBy and ModifiedBy via the HTML UI in the browser, but you can now access that information using CSOM or REST. To demonstrate, let’s use the REST API as an anonymous user to look through the items in the Pages library by appending _api/Web/Lists/Pages/Items to the site. I’ll give you a moment to soak that one in. Let me log in as Dan Jump, the CEO of my fictitious Contoso company in my lab environment. Dan authors a page and publishes it. An anonymous user now uses the REST API (or CSOM, but if you are reading this hopefully you get that they are the same endpoint) using the URL: The resulting text shows his domain account (contoso\danj) and his name (Dan Jump). This may not be a big deal in many organizations, but for some this would be a huge deal and an unintended disclosure of personally identifiable information. Understand that if you enable the CSOM for your public-facing internet site, you run the risk of information disclosure. For those that might be confused about my using the term “CSOM” but showing examples using REST, here is some code to show you it works. I don’t need OAuth or anything here, and I run this from a non-domain joined machine to prove that you can now get to the data. using Microsoft.SharePoint.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (ClientContext ctx = new ClientContext()) { ctx.Credentials = System.Net.CredentialCache.DefaultCredentials; Console.WriteLine("Enter the list name: "); string listName = Console.ReadLine(); List list = ctx.Web.Lists.GetByTitle(listName); Console.WriteLine("Enter the field name: "); string fieldName = Console.ReadLine(); CamlQuery camlQuery = new CamlQuery(); ListItemCollection listItems = list.GetItems(camlQuery); ctx.Load( listItems, items => items .Include( item => item[fieldName], item => item["Author"], item => item["Editor"])); try { ctx.ExecuteQuery(); foreach (var myListItem in listItems) { Console.WriteLine("{0} = {1}, Created By={2}, Modified By={3}", fieldName, myListItem[fieldName], ((FieldUserValue)myListItem["Author"]).LookupValue, ((FieldUserValue)myListItem["Editor"]).LookupValue ); } } catch (Exception oops) { Console.WriteLine(oops.Message); } } } } } This code simply asks for a list name and a column name that you would like to query data for, such as “Title”. I also include the Created By and Modified By fields as well to demonstrate the potential disclosure risk. Since the CSOM is available to anonymous users, I can call it from a remote machine and gain information that was not intended to be disclosed. You see that CSOM and REST are calling the same endpoint and getting the same data. Security Trimming Still in Effect At this point I have probably freaked a few readers out who didn’t understand the full consequences when they unchecked that checkbox (or, more likely, people who skimmed and did not read this section). Does this mean that anonymous users can do ANYTHING they want to with the CSOM? Of course not. When you configured anonymous access for the web application, you specified the anonymous policy, likely with “Deny Write – Has no write access”. This means what it says: Anonymous users cannot write, even with the REST API or by using CSOM code. Further, anonymous users can only see the information that you granted them to see when you configured anonymous access for the site. If there is content in the site that you don’t want anonymous users to access, you have to break permission inheritance and remove the right for viewers to read. Additionally, there is some information that is already locked down. Logged in as the site collection administrator, I can go to the User Information List and see information about the site users.(‘User%20Information%20List’)/Items If I try that same URL as an anonymous user, I simply get a 404 not found. To summarize this section and make it perfectly clear: security trimming is still in effect. Unpublished pages are not visible by default to anonymous users. They can only see the lists that enable anonymous access. If, despite what I’ve written so far, you decide to enable CSOM for anonymous users, then you will want to make sure that you don’t accidentally grant access for anonymous users to things they shouldn’t have access to. Potential for DoS When you use SharePoint to create web pages, you carefully construct the information that is shown on the page and you control how frequently it is queried or seen. Hopefully you perform load tests to confirm your environment can sustain the expected traffic load before putting it into production. With CSOM enabled for anonymous users, all that testing was pointless. There is no caching with the CSOM, so this would open up the possibility for me to do things like query batches of information to query 2000 items from multiple lists simultaneously, staying under the default list view threshold while taxing your database. Now if I can get a few other people to run that code, say by using some JavaScript exploit and posting it to Twitter, then I now have the makings for a DoS attack… or at least one hell of a stressful day for my databases. You Really Need to Understand How OAuth Works Hopefully by now I have convinced you that enabling the CSOM for anonymous users to directly access is not advised (and hence why it is turned off by default). At this point in the conversation, I usually hear someone chime in about using the app only policy. Let me tell you why this is potentially a MONUMENTALLY bad idea. With provider-hosted apps, I can use this thing called the App Only Policy. This lets my app perform actions that the current user is not authorized to do. As an example, an administrator installs the app and grants it permission to write to a list. A user who has read-only permission can use the app, and the app can still write to the list even though the user does not have permission. Pretty cool! I have presented on the SharePoint 2013 app model around the world, and I can assure you that it all comes down to security and permissions. Simply put, you must invest the time to understand how OAuth works in SharePoint 2013. Watch my Build 2013 talk Understanding Authentication and Permissions with Apps for SharePoint and Office as a good starter. The part to keep in mind is how OAuth works and why we say you ABSOLUTELY MUST USE SSL WITH SHAREPOINT APPS. It works by the remote web site sending an access token in the HTTP header “Authorization” with a value of “Bearer “ + a base64 encoded string. Notice I didn’t say encrypted, I said encoded. That means that the information can easily be decoded by anybody who can read the HTTP header value. I showed a working example of this when I wrote a Fiddler extension to inspect SharePoint tokens. It isn’t that hard to crack open an access token to see what’s in it. If you have a public-facing web site, you are likely letting everyone access it using HTTP and not requiring HTTPS (of course, you are doing this). If you tried to use a provider-hosted app without using SSL, then anyone can get to the Authorization token and replay the action, or worse. They could create a series of tests against lists, the web, the root web, the site collection, additional site collections, or the tenant to see just what level of permission the app had. If the app has been granted Full Control permission to a list, it has the ability to do anything it wants to that list including delete it. Even though your app may only be writing a document to the list, your app is authorized to do anything with that list. Start playing around with CSOM and REST, and I can do some nasty stuff to your environment. One more thing… the access token is good for 12 hours. That’s a pretty large window of time for someone to get creative and make HTTP calls to your server, doing things that you never intended. Doing It The Right Way Suffice to say, you DO NOT want to try using CSOM calls in a provider-hosted app to an anonymous site, and you DO NOT want to enable CSOM for anonymous users. Does this completely rule out using the app model? You could set up a different zone with a different URL that uses SSL, and your app will communicate to SharePoint using only server-side calls to an SSL protected endpoint. To achieve this, the app would have to use the app-only policy because no user information would be passed as part of the token (see my blog post, SharePoint 2013 App Only Policy Made Easy for more information). The reason that I stressed server-side calls in the previous paragraph is simple: if they were client-side calls using the Silverlight CSOM or JavaScript CSOM implementation, we’d be back at the previous problem of exposing the CSOM directly to anonymous users. This pattern means there are certain interactions with apps that are not going to work easily. For instance, using this pattern with an ACS trust means that a context token will not be passed to your app because your app is using HTTP. You can still communicate with SharePoint, but the coding is going to look a bit different. clientContext = TokenHelper.GetClientContextWithAccessToken( siteUri.ToString(),accessToken)) { //Do work here } Instead of reading information from the context token, we are simply making a request to Azure ACS to get the access token based on the realm and the URL of the SharePoint site. This keeps the access token completely away from users, uses SSL when communicating with SharePoint, and allows you to control the frequency and shape of information that is queried rather than opening access to the whole API to any developer who wants to have a go at your servers. Enabling Search for Anonymous Users Sanjay Narang pointed out in the comments to this post that it is possible to enable anonymous search REST queries without removing the requires remote interface permission setting. This is detailed in the article SharePoint Search REST API overview. administrators can restrict what query parameters to expose to anonymous users by using a file called queryparametertemplate.xml. To demonstrate, I first make sure that the site has the requires remote interface permission. Next, I make sure that search results will return something. I have a library, Members Only, that contains a single document. That document contains the following text. I break permissions for the library and remove the ability for anonymous users to access it. A search for “dan” returns two results if I am an authenticated user. A search for “dan” only returns 1 result as an anonymous user. If I attempt to use the search REST API as an authenticated user, I get results. If I attempt it as an anonymous user, I get an HTTP 500 error. Looking in the ULS logs, you will see that the following error occurs. Microsoft.Office.Server.Search.REST.SearchServiceException: The SafeQueryPropertiesTemplateUrl "The SafeQueryPropertiesTemplateUrl "{0}" is not a valid URL." is not a valid URL. To address this, we will use the approach detailed by Waldek Mastykarz in his blog post Configuring SharePoint 2013 Search REST API for anonymous users. I copy the XML from the SharePoint Search REST API overview article and paste into notepad. As instructed in that article, you need to replace the farm ID, site ID, and web ID. You can get those from PowerShell. PS C:\> Get-SPFarm | select ID Id -- bfa6aff8-2dd4-4fcf-8f80-926f869f63e8 PS C:\> Get-SPSite | select ID ID -- 6a851e78-5065-447a-9094-090555b6e855 PS C:\> Get-SPWeb | select ID ID -- 8d0a1d1a-cdae-4210-a794-ba0206af1751 Given those values, I can now replace them in the XML file. Save the XML file to a document library named QueryPropertiesTemplate. Finally, append &QueryTemplatePropertiesUrl=’sp’ to the query. Now try the query as an anonymous user, and you get results even though we still require the use remote interfaces permission. The rest of the CSOM and REST API is not accessible, only search is, and only for the properties allowed through that file. Summary This was a long read (took even longer to write), but hopefully it helps to answer the question if you should use apps for your public-facing site. As you saw, you can easily create client app parts and even custom actions. You should not enable CSOM for anonymous access unless you are OK with the risks and can mitigate against them. You can still use the app model, but it’s going to take a little more engineering and will require your SharePoint site have an endpoint protected by SSL that is different than the endpoint that users will access. For More Information Understanding Authentication and Permissions with Apps for SharePoint and Office SharePoint 2013 App Only Policy Made Easy Fiddler extension to inspect SharePoint tokens Configuring SharePoint 2013 Search REST API for anonymous users. SharePoint Search REST API overview Great description of the challenges for using Apps in an anonymous context with clear reasons as to why it may be a bad idea. Just one quick question, what do you think of requiring HTTPS access only to the anonymous site? Would that alleviate the issues you described with provider hosted apps and the app only permission? @Gavin – Using HTTPS would protect the access token in flight and would alleviate the problem. However, if you have a public-facing site, chances are that you are not using HTTPS. That's the point I was trying to make at the end of the article. @Kirk: Absolutely great post! Clears up a lot of debates we have been having around Apps and Anonymous access. I assume that CSOM and REST are not allowed for O365 public facing sites due to the very same reasons you mentioned. Excellent post, as usual Kirk. On Office365, that leak of information via CSOM would be even worse, as the account name would contain the email address of the user (i:0#.f|membership|user@company.com). Yuck. @Gavin – readdressing your question. The only way I would use an app with a public-facing site is if multiple zones were set up for the web application, one with a URL for anonymous users using HTTP, and one for authenticated users using SSL. I would only have the app communicate with the SSL endpoint using the app only policy, and I would not uncheck the checkbox for Require Remote Interfaces Permission. The app could still use the CSOM to communicate with the site, and the anonymous users over HTTP could still use the data that was updated by the app. Perhaps that is a follow-up post, showing how to do all of this with two zones. Hi Kirk – thanks so much for such a useful post. another question – what do you feel for enabling SharePoint 2013 Search REST API for anonymous users as described here msdn.microsoft.com/…/jj163876.aspx – do we have similar issue there also. link doesn't work I have a public facing website. The image carousel is an app that only has read access to lists. Is using an app for the image carousel the wrong thing to do? Wondering if this method would prevent user info leaking: get-spscripts.com/…/mask-createdmodified-user-name-from.html In other words, if lockdown mode was turned off for the site collection and this flag was set to false for all lists in the site collection, could you still return user info via the web services. HI Kirk, I have a customer who is considering clearing "Require Use Remote Interface Permission" as a security vulnerability for anonymous users. Anonymous users have to use the CSOM as per my implementation, should i tell them that we need to live with this issue or there is better solution Jamil Haddadin @Jamil – See the section "Doing It the Right Way" for a better solution. The better solution is by writing server side code in the Provider hosted app with elevated privilege with App only policy? Please confirm
https://blogs.msdn.microsoft.com/kaevans/2013/10/24/what-every-developer-needs-to-know-about-sharepoint-apps-csom-and-anonymous-publishing-sites/
CC-MAIN-2017-34
refinedweb
3,867
62.07
in reply to Re: Re: Re: Re: This is why I use Perlin thread This is why I use Perl To me this is not about the ability or capability of a given language, but about the principles of encapsulation, OO programming and the best practice for OO programming. You don't do things that's doable, if they are not the best practice. I strongly suspect that you misunderstood the point of what I was trying to say. Probably because I didn't describe it in enough detail for you to clearly visualize what I described. So here it is in detail. In Ruby it is customary that if you want to write get/set methods for an attribute named, say, bar, you name the get method bar, and the set method bar=. The reason is that Ruby has a nice piece of syntactic sugar, foo.bar = baz is translated into foo.bar=(baz). Therefore people can use your get/set methods in a simple way. Now lets take a simple piece of working Ruby to show this in practice: # Example simple class class Foo def initialize (aBar) @bar = aBar; end def bar @bar; end def bar= (aBar) @bar = aBar; end end # Example usage foo = Foo.new("Hello"); puts foo.bar; # prints "Hello\n" foo.bar = "World"; puts foo.bar; # prints "World\n" [download] Now let me write the same class in a different way: class Foo attr_accessor :bar; # Could add , :baz, :and, :others... def initialize (aBar) @bar = aBar; end end [download] Therefore in Ruby if you have decided to write loads of public get/set methods, there is absolutely no reason to write them yourself. Just declare a bunch of public (yes, Ruby allows you to differentiate between public, private, and protected) ones with attr_accessor instead. If one of those accessors needs to do something more complex later (like add validation), that is easily enough changed later, transparently to existing code. The decision about whether to have public get/set methods is an entirely tangential question. In Perl you can do something similar, but the case for doing it is far weaker than it is in Ruby. If you have created your objects like most people do, as anonymous hashes, then you can move the implementation elsewhere and replace the anonymous hashes with anonymous tied hashes. You now get the ability in your FETCH, STORE, DELETE etc methods to hide specific fields, sanity check others, etc. All transparently to existing code. One way that you could do it is take what I did at Class::FlyweightWrapper and modify it by having the wrapping objects be references to tied anonymous hashes (with an arbitrary tying class) rather than anonymous scalars. This is doable, but takes a fair amount of work, and as I said, is clearly a suboptimal approach. I might consider it as a retroactive fix for a bad situation, but I wouldn't plan on doing things that way. In Java if someone has decided to allow the properties of an object be directly exposed, I don't believe that you can later replace that with get/set methods without having to visit existing code that used the old API. Therefore the possibility that you might some day, maybe, want to change your implementation and do something sophisticated in your get/set methods means that you must now hide properties and write get/set methods. Therefore while the principles of encapsulation, OO programming, etc do not change between languages, best practices may. In particular what is best practice in Java (writing lots of simple get/set methods) is not best in Ruby because the capabilities of the language give you a better option. In Perl if you get it wrong, you theoretically can fix things afterwards, but probably don't want to because the ways of doing it are problematic. The decision about whether to have public get/set methods is an entirely tangential question. This is sometimes called the "Uniform Access Principle" (coined, I think, by Meyer in his Object Oriented Software Construction - my copy's gone walk about so I can't check). As tilly points out, by keeping the attribute and method syntax identical we're free to change our implementation without having to change the API..
https://www.perlmonks.org/?node_id=305611
CC-MAIN-2018-47
refinedweb
713
58.92
During the transition to a micro service based approach at Qualislabs I saw new faces joining my team. There was definitely a learning curve involved and generally it reduces the effectiveness of the team. A newcomer should not feel stranded and burdened with a lot to work with. Dependency and Environment Hell Originally we had a monolithic application either in python or node and I must say we were able to debug and fix issues easily even on each others machine. However as our number increased, the number of differing environments became an issue which meant that every machine had to have the correct dependencies and environment. 12 Factor Applications If you have worked on making applications cloud friendly then you may have encountered the 12 factors. We were trying to ensure that every service within our application adhered to all of these factors in order to easily scale and deploy our services with very little to no manual effort. The Issue Setting appropriate dependencies and environment variables for all members was becoming a bit of a burden and there were times when tests were run against production resources. This was due to developers forgetting to set environment variables back to development values. Docker to our rescue I later found out about docker. I must admit it felt like love at first sight. With containerization we were able to overcome most of the challenges we had but still missed our former days of monoliths. Developers now only had to build their code with a well documented README file then I would later do the system integration on Friday evening. This was hard since my friends had a better plan for me that evening but I have stayed faithful to docker. We have had our ups and downs but we still care for each other 😁. We later converted our apps to micro services written in different languages from the wrath C to the lovely python and Go. Minimizing images So this is what led me to write this. Most of the developers starting out follow what every Indian guy tells them on YouTube like a Church mass. But they encounter many problems which they don’t know how to solve. One of these problems is when you have large images you have a slower run time and also it takes a lot of time to build and test to production. Large images may hog your memory if you write simple apps with a base image of Ubuntu or Debian yet it would have been better to convert the system to a monolith and they would have shared the requirements. 101 Docker is a set of platforms as a service products that uses OS-level virtualization to deliver software in packages called containers. Docker image is a template to create docker container. It is built using Dockerfile and can be shared to others through a repository. Dockerfile is a set of instructions to build an image. It starts from base image and every instruction creates a layer which is cached for future builds. Docker container is created from docker images. We add a writable layer to it and the allocated resources. Registry is where we store docker images remotely. Lets create a python Flask app for demonstration purposes: from flask import Flaskapp = Flask(__name__)@app.route("/") def hello_world(): return "Hello world from container"if __name__ == "__main__": app.run(host="0.0.0.0", port=5000) We create a virtualenv as we used to do in the monolith days to track our dependencies. virtualenv venv --python=python3 We activate the virtual environment. source venv/bin/activate We install flask in order to run our web application. pip3 install flask We finally write the dependencies to a requirements file. pip freeze > requirements.txt The requirements consist of : click==7.1.1 Flask==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.1 MarkupSafe==1.1.1 Werkzeug==1.0.0 We write a first Dockerfile: FROM ubuntu LABEL Maintainer="Rodney Osodo" WORKDIR /app RUN apt-get update RUN apt-get install python3-pip COPY . /app RUN pip3 install -r requirements.txt WORKDIR EXPOSE 5000 CMD ['python3','app.py'] and finally build the images, docker build -t flask_test:1.0.0 . Our docker images size is 1.28GB, which isn’t that bad but is extremely bad. 😂 Build process Lets make another dockerfile from python as the base image: FROM python WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD ["python", "app.py"] Our image size has now reduces to 1GB. Isn’t that great? Optimization objectives - Reduce image size - Reduce build time Priorities - Fast builds during development - Smaller image for production Base image Use slim-stretch as base when you care about build time. Use alpine as base when you care about image size. Lets try reducing the images. Ahh we should all be happy now, right? FROM python:3.7-slim WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD ["python", "app.py"] Image size is 209MB FROM python:3.7-slim-stretch WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD ["python", "app.py"] Image size is 186MB Definitely slim-stretch is better than slim. What about our alpine base image? FROM python:3.7-alpine WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD ["python", "app.py"] The image size is 127MB First take home is that build dependancies are not needed and only include the necessary files, not all your project files. Unfortunately we had only three files. When copying use dockerignore to exclude files that are not needed. Tips - Combine multiple RUN statements into a single one then delete them in the same layer. - To benefit from caching arrange statements in ascending order depending on system level dependencies. - Do not save dependencies - pip3 — no-cache-dir - apk — no-cache FROM python:3.7-alpine WORKDIR /app COPY . . RUN pip3 install --no-cache-dir -r requirements.txtCMD ["python", "app.py"] Size 107MB Docker multi stage - Build a docker image with all your deps then install your app. - Copy the result to a fresh image and label is as the final image. # Stage 1 - Install build dependencies FROM python:3.7-alpine AS builder WORKDIR /app RUN python -m venv .venv && .venv/bin/pip install --no-cache-dir -U pip setuptools COPY requirements.txt . RUN .venv/bin/pip install --no-cache-dir -r requirements.txt && find /app/.venv ( -type d -a -name test -o -name tests \) -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) -exec rm -rf '{}' \+# Stage 2 - Copy only necessary files to the runner stage FROM python:3.7-alpine WORKDIR /app COPY --from=builder /app /app COPY app.py . ENV PATH="/app/.venv/bin:$PATH" CMD ["python", "app.py"] Results a smaller image with no build deps. Bind mount source code instead of COPY in local dev environment. Our benchmark Our benchmark app was a go app with the same functionality. The beauty of using a compiled code is that it runs faster than interpreted code. The compiled program was checked for errors during compilation. package main import ( "fmt" "net/http" ) func main(){ http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, "Hello from conatiner") }) http.ListenAndServe(":5000", nil) } We compile the program then it will generated an executable file which we can ran from a scratch image: FROM scratch COPY app / CMD ["/app"] This results to an image size of 25Mb. Hopefully you found this story both entertaining and enlightening! I’m hoping this helped to highlight the benefits of minimising docker images and how you could utilize it for everyday applications to improve developer workflow. If you found this useful then please let me know in the comments section or by tweeting me @b1ackd0t. I’d be more than happy to hear any feedback!
https://rodneyosodo.medium.com/minimizing-python-docker-images-cf99f4468d39
CC-MAIN-2021-43
refinedweb
1,307
67.65
This is the fourth post in a series about building a podcast application using GRANDstack. Check out the previous episodes here: In this post we turn our attention to the frontend of the podcast application we've been building on the Neo4j livestream. So far we’ve focused on the backend and GraphQL API layer. This week we got started on the front end, using the Next.js React framework. You can find the livestream recording embedded below or on the Neo4j Youtube channel. In this post we'll focus on getting started with Next.js, fetching data using GraphQL in our Next.js application, and setting up client-side authentication with GraphQL in Next.js so we can sign in and make authenticated requests to our GraphQL API. What Is Next.js? Next.js is a web framework built on top of React that adds many features and conventions that aren't available by default with React. Things like server side rendering, file based routing, image optimization, code splitting and bundling, and adding server-side API routes are things we eventually need to deal with as our React application becomes more complex. With Next.js we have all these things (and lots more) available out of the box. I like to think of Next.js as React with batteries included. Getting Started With Next.js The easiest way to get started with Next.js is using the create-next-app CLI. Similar to create-react-app or create-grandstack-app, we can create an initial Next.js application from the command line. npx create-next-app next-app The create-next-app command can take an example argument to specify an example template to use. There are two example Next.js templates for using Next.js with Neo4j: We're going to skip these Neo4j specific templates since we've already built out our GraphQL API. In a future post we'll see how we can move our GraphQL API into Next.js, taking advantage of the serverless function deployment built into Next.js API routes. To start our Next.js application we'll run npm run dev which will start a local server at localhost:3000 serving our Next.js application. GraphQL Data Fetching With Next.js The first thing we want to do is make data fetching queries with GraphQL and display podcast data in our Next.js application. To do this we'll use Apollo Client. First, let's install Apollo Client, by default this will include the React hooks integration for Apollo Client as well. npm i @apollo/client In React applications we make use of the Provider pattern and the React Context API to make data available throughout the React component hierarchy. The React integration for Apollo Client includes an ApolloProvider component that we can use to inject an Apollo Client instance into the React component hierarchy, which will make Apollo Client available to any component in our application. To do this we need to create an Apollo Client instance and wrap our application's root component in the ApolloProvider component. In Next.js we can do this in the _app.js file. import '../styles/globals.css' import { ApolloProvider, ApolloClient, InMemoryCache, HttpLink, } from '@apollo/client' function createApolloClient() { const link = new HttpLink({ uri: '', }) return new ApolloClient({ link, cache: new InMemoryCache(), }) } function MyApp({ Component, pageProps }) { return ( <ApolloProvider client={createApolloClient()}> <Component {...pageProps} /> </ApolloProvider> ) } export default MyApp Note the use of an HttpLink instance. With Apollo Client, links are composable units, similar to middleware, that allow us to inject logic into the networking layer of a GraphQL request. Here we create a link to point Apollo Client to our GraphQL API running at localhost:4001/graphql. Later, we'll use the link to add an authorization header that includes an auth token once a user has signed in to the application, but for now we'll start with making unauthenticated GraphQL requests. Making GraphQL Queries With Apollo Client In A Next.js Page With Next.js' file based routing system we can create new pages just by creating a file in the pages directory and exporting a React component. Let's create a podcasts page to display a list of available podcasts. We'll make use of the useQuery Apollo Client hook to execute a GraphQL query to find all podcasts in the database and return their title. import { useQuery, gql } from '@apollo/client' const PodcastQuery = gql` { Podcast { title } } ` const Podcasts = () => { const { data } = useQuery(PodcastQuery) return ( <div> <ul> {data?.Podcast.map((v) => { return <li key={v.title}>{v.title}</li> })} </ul> </div> ) } export default Podcasts Next.js will automatically add a route at /podcasts to render our new page. There are only a few podcasts in the database since they are only added to the database when a user subscribes. Refer to Episode 2 to see how we implemented podcast subscribe functionality. Slight Detour - Setting Up The GraphQL VS Code Extension If you use the VS Code editor it can be helpful to make use of the GraphQL VS Code extension. This extension will enable syntax highlighting in .graphql files, gql template tags, and can also be used to execute GraphQL queries that are tagged in your JavaScript files. To use the GraphQL VS Code extension you'll need to install it from the extension marketplace here. Then you'll also need to configure your project's GraphQL APIs in a GraphQL config file. Here's a simple example for this project: schema: 'api/src/schema.graphql' extensions: endpoints: default: url: This will now allow us to execute GraphQL queries from VS Code that we've tagged with the gql template tag: Authenticated GraphQL Requests In Next.js We've seen how to make use of Apollo Client in our Next.js application to render a list of available podcasts, however this only works for unauthenticated GraphQL requests. We need to allow users to sign in to our application and then once they've signed in expose the user-specific functionality that we've built into our GraphQL API layer: podcast subscribe, new episode feeds, and create/view/update episode playlists. To handle authentication and the associated state (Is the user signed in? What is the user's auth token?) we will make use of the React Context API and the Provider pattern again, this time creating our own AuthProvider that will allow us to keep track of and update authentication related state. Specifically, we'll need to: - Execute the loginGraphQL mutation operation to sign a user into the application. - The loginGraphQL mutation will return a JWT token when a user successfully signs in. We'll need to keep track of that token. - When a user is signed in and a valid JWT is generated we need to add the token to all GraphQL requests as an authentication header. - Allow a user to sign out. All of this functionality will then be made available to any of our application components by importing the useAuth hook that we will create in our authentication provider. import React, { useState, useContext, createContext } from 'react' import { ApolloProvider, ApolloClient, InMemoryCache, HttpLink, gql, } from '@apollo/client' const authContext = createContext() export function AuthProvider({ children }) { const auth = useProvideAuth() return ( <authContext.Provider value={auth}> <ApolloProvider client={auth.createApolloClient()}> {children} </ApolloProvider> </authContext.Provider> ) } export const useAuth = () => { return useContext(authContext) } function useProvideAuth() { const [authToken, setAuthToken] = useState(null) const isSignedIn = () => { if (authToken) { return true } else { return false } } const getAuthHeaders = () => { if (!authToken) return null return { authorization: `Bearer ${authToken}`, } } const createApolloClient = () => { const link = new HttpLink({ uri: '', headers: getAuthHeaders(), }) return new ApolloClient({ link, cache: new InMemoryCache(), }) } const signIn = async ({ username, password }) => { const client = createApolloClient() const LoginMutation = gql` mutation signin($username: String!, $password: String!) { login(username: $username, password: $password) { token } } ` const result = await client.mutate({ mutation: LoginMutation, variables: { username, password }, }) console.log(result) if (result?.data?.login?.token) { setAuthToken(result.data.login.token) } } const signOut = () => { setAuthToken(null) } return { setAuthToken, isSignedIn, signIn, signOut, createApolloClient, } } Note how we make use of the HttpLink to add the authentication header to GraphQL requests when a user is signed in. We also wrap the ApolloProvider component in our AuthProvider which will make Apollo Client and the authentication functionality available to any child components in the React component hierarchy. We'll need to update _app.js to use this new AuthProvider: import '../styles/globals.css' import { AuthProvider } from '../lib/auth.js' function MyApp({ Component, pageProps }) { return ( <AuthProvider> <Component {...pageProps} /> </AuthProvider> ) } export default MyApp The Sign In Flow Now that we've implemented authentication functionality in our AuthProvider we can implement the sign in flow in our index page. First, we'll want to import the new useAuth hook we created: import { useAuth } from '../lib/auth.js' Now, let's add a SignIn component with a form for the user to submit their username and password. When the user submits the form we'll call the auth.js which will execute the login GraphQL mutation and generate an auth JSON Web Token (JWT). const SignIn = () => { const [username, setUsername] = useState('') const [password, setPassword] = useState('') const { signIn, signOut } = useAuth() function onSubmit(e) { e.preventDefault() signIn({ username, password }) } return ( <div> <form onSubmit={onSubmit}> <input type="text" placeholder="username" onChange={(e) => setUsername(e.target.value)} ></input> <input type="password" placeholder="password" onChange={(e) => setPassword(e.target.value)} ></input> <button type="submit">Sign In</button> </form> </div> ) } Once a user is signed in we want to show their podcast episode feed - the most recent podcast episodes across all the podcasts they subscribe to. This is available via the episodeFeed GraphQL query field. We'll create a FeedQuery component to execute this query and render the results in a list. Since the user is signed in, the appropriate auth token will be added in the header of the GraphQL request, making this an authenticated GraphQL request against our API. const FeedQuery = gql` { episodeFeed(first: 50) { id title audio podcast { title } } } ` const EpisodeFeed = () => { const { data } = useQuery(FeedQuery) const { signOut } = useAuth() return ( <div> <h1>Episode Feed</h1> <ul> {data?.episodeFeed.map((v) => { return <li key={v.id}>{v.title}</li> })} </ul> <button onClick={() => signOut()}>Sign Out</button> </div> ) } Next, we'll make use of the isSignedIn function made available via useAuth to determine whether to render the sign in form or the episode feed component. export default function Home() { const { isSignedIn } = useAuth() return ( <div className={styles.container}> <Head> <title>GRANDcast.FM</title> <link rel="icon" href="/favicon.ico" /> </Head> <main className={styles.main}> <h1>GRANDcast.FM</h1> {!isSignedIn() && <SignIn />} {isSignedIn() && <EpisodeFeed />} </main> </div> ) } Now, when we first load the page we're presented with a sign in form that will execute the login GraphQL mutation when submitted. If a successful login, then the GraphQL server will generate an authorization JWT and return the token to the client. Our auth provider will store that token and attach it in the authorization header of all future GraphQL requests, until we log out. Once we're authenticated, instead of the login form, we're presented with a list of the most recent podcast episodes for all podcasts to which we subscribe. We can click the "Sign Out" button, which will update the authentication state in our application, remove the token from future GraphQL requests, and we'll be presented with the sign in form again. Now that we've set up client-side authentication in our Next.js application we can start to explore the different data-fetching patterns available to us in Next.js. We skipped over this functionality in this post but the different server data-fetching models in Next.js are some of the most interesting features of the framework. We'll dig into this in the next episode. Be sure to subscribe to the Neo4j livestream on Twitch or Youtube to keep up to date as we build out more features in GRANDcast.FM. What else would you like us to explore on the livestream? Let us know on Twitter. Discussion (1) Nice!
https://dev.to/lyonwj/getting-started-with-next-js-and-graphql-authentication-building-grandcast-fm-episode-4-14em
CC-MAIN-2021-10
refinedweb
1,984
56.25
kill python listener which opened matplotlib figure [closed] Hello, i wrote a visualization with matplotlib in python. import matplotlib.pyplot as plt def callback(data): do something plt.show() def listener(): rospy.Subscriber('topic', data, callback) rospy.spin() Main function. if __name__ == '__main__': # Initialize the node and name it. rospy.init_node('pylistener', anonymous = True) # Go to the main loop. listener() i want to print my figure. The problem is when he get a message he stop till i close the figure. That is fine. But when i want to close the program with ctrl+c the program crash and i have to close the terminal. It is possible to kill the node and the python program after i close the figure? Or what i can do against this crashing? It is really annoying that i have to close the terminal and restart it. thank you for your help and sry i am new on python Also, where do you define data?
https://answers.ros.org/question/60883/kill-python-listener-which-opened-matplotlib-figure/
CC-MAIN-2022-33
refinedweb
161
78.14
CPU Multi-Processor Usage w/o Performance Counters Started by Ascend4nt, 18 posts in this topic You need to be a member in order to leave a comment Sign up for a new account in our community. It's easy! Register a new account Already have an account? Sign in here. Similar Content - By trademaid Im looking to measure cpu usage thats free, and measure cpu usage of a program. My goal is to turn intel speed step off under light cpu load. I think I can do that, if I can find the cpu usage. - By rm65453 Hi years old and did not work for me. Thanks - all this is a part from my script #include <Misc.au3> $dll = DllOpen("user32.dll") While 1 If _IsPressed("31", $dll) Then one() If _IsPressed("32", $dll) Then two() WEnd Func one() MsgBox(0, "", "1") While _IsPressed("31") or _IsPressed("61") Sleep(1) WEnd EndFunc Func two() MsgBox(0,"", "2") While _IsPressed("32") or _IsPressed("62") Sleep(1) WEnd EndFunc it is working fine but it takes 30 % of the CPU usage and it is a small simple script when i put sleep(100) in the while loop the CPU is 1% i think that this is a good solution but not for my case cuz the rest of my script really depends on time and 100 msec will matter can i reduce the CPU usage without using sleep ?
https://www.autoitscript.com/forum/topic/151831-cpu-multi-processor-usage-wo-performance-counters/
CC-MAIN-2017-51
refinedweb
237
74.53
Steve Ognibene is your TypeScript tutor Welcome to Part This episode looks at the third module form this course TypeScript Migration Toolbox and Workflow Reimplementing Coins as a Class Steve create a new file coins.ts and moves the coins array declaration to here. TypeScript isn’t happy with Big.js so Steve uses Nuget to download big.js.TypeScript.DefinitelyTyped, and this fixes all the errors. coins is an array of objects, and each of the objects has the following properties: - name (e.g. “Penny”) - value (e.g. Big(‘0.01’)) - imgSrc (e.g. “penny.png”) - count (e.g. ko.observable(0)) - max (e.g. ko.observable(10)) In coins.ts, we want to refactor our code to eliminate duplication. Steve adds a new class Coin with a constructor. The constructor has arguments for the name, style and value properties that exist in the coins array. We use the public keyword on each constructor property, and also specify the type of each property. We know that name and style will have the string type, but what about value? By hovering over value in our original code, TypeScript tells us that the type is BigJsLibrary.BigJS TypeScript can’t always know what type this refers to (although I understand that there have been improvements made here since the recording). However, inside our constructor, TypeScript knows that this refers to the class. Using our new class, our coins definition is much more terse. We run it up to test that it works, and see the runtime error : “Object doesn’t support this action” What this obscure message is trying to tell us is we are trying to use Coin before it has been assigned its value. The undefined variable Coin doesn’t support the action of calling new on it. Fortunately this is an easy fix, and now everything works. Migrating CoinCounterViewModel as a Function Almost as soon as we rename to the TypeScript extension we get 27 errors. First off, we have: Cannot find name ‘$’. To fix this, go to Nuget and install jquery.TypeScript.DefinitelyTyped Using Visual Commander, we perform the Quick Reload action, and get down to 18 errors. Most of these are of the form: Parameter ‘x’ implictly has an ‘any’ type For callback, Steve defines it as callback: (viewModel: typeof self) => void For coin, we simply give it the Coin type. For coinName, it is a string zeroBasedIndex is a number We have errors for coin.addCoinEnabled and coin.removeCoinEnabled TypeScript really doesn’t like you adding things to an object that it doesn’t expect, and neither of these properties have been previously defined. Steve adds them as properties of our Coin class. Okay down to 5 errors: Property ‘modal’ does not exist on type ‘jQuery’ This refers to our Bootstrap modal. We fix this by installing bootstrap.TypeScript.DefinitelyTyped. Type ‘string’ is not assignable to type Location. We should be assigning our string value to Location.href, rather than Location. Steve says using TypeScript makes you wonder how your JavaScript worked at all before. With all errors fixed, we see that the game still works well. Converting CoinCounterViewModel to a Class Steve renames gametests.js to gametests.ts and reloads the project. Only one distinct errors this time: ‘new’ expression, whose target lacks a construct signature, implicitly has an ‘any’ type What this means is CoinCounterViewModel isn’t a class even though we are calling new on it. Rather than eliminating this error using the “light touch” interface technique that we saw before, we convert CoinCounterViewModel to a TypeScript class. This is several minutes of work, and after we clear all the compiler errors we get one at run time: Error: Unable to get property ‘isRunning’ of undefined or null reference. Steve says we need to use a lambda, and that we’re probably wondering what the hell he’s going on about. Lambdas and How ‘this’ Works in TypeScript The way that this works in JavaScript is often confusing. It is contextually bound – it depends on how you call the code that contains it. With this hopefully understood, Steve explains what a Lambda (or “Arrtow function”) is in JavaScript, and how they differ from standard functions. When you’re using standard function calls, this in TypeScript works identically to how this works in JavaScript. But when we use a lambda, TypeScript automatically emits some extra JavaScript to capture this from the scope where the lambda is declared. If you want your this to be contextually bound (i.e. normal JavaScript), use the function keyword. If you want your this to be lexically bound, use a lambda. Don’t fall into the trap of thinking lambdas are just syntactic sugar. They work differently. Steve rewrites the functions as lambdas, clears down the errors, and the emitted javascript includes: Completing the Migration and Internal Modules Okay that was a lot of work, but now we’re on the home straight. We’re going to do our final migration and refactoring: - Remove JavaScript from index.html - Implement “CoinCounter” module - Improve confusion of concerns with Coin We cut our $(document).ready block of code out of our html file and paste it in index.ts. This just works. In app.ts we embed all of code in a new module: module CoinCounter { … } Steve explains that we must remember to add the export keyword to var app. This pattern is also applied to other files. When we run up our app we see another run time error: Error: ‘spacesToUnderscore’ is undefined We find this code is part of a data-bind attribute value in index.html – this is not TypeScript code so TypeScript cannot understand it’s type. Steve refactors this to call our TypeScript function instead. TypeScript Internal Modules vs. External Modules Many people find the term internal modules confusing. Steve discusses the Github thread on renaming from internal modules to namespaces. External modules are now just called modules, and Steve likes to think of them as File-based modules. The two flavours of modules are Common JS and AMD and Steve describes both of these systems here. Steve says he hears a lot of developers asking “What Style of Modules Should I Choose?” We are advised that our aim is to keep the project complexity down to a minimum. Namespaces work well for low to medium complexity projects. Modules help automate interdependency resolution, but they introduce problems of their own, especially when using TypeScript. In this clip we see a chart to help us make the right choice for our project. This is entirely consistent with my experience of modules and namespaces and makes me feel better about using namespaces for so long when some developers say that everyone should be using modules in JavaScript. That said, due to the ES2015 effect, modules are becoming more and more common. Separating Coin and ViewModel Concerns Steve removes the body of the Qunit tests and rename contests.js to cointests.ts. We see each test created using the Red Green Refactor pattern of test driven development. If you are new to Test Driven Development, or would like to learn it in even more detail, see Learning Unit Testing and Test Driven Development. We see all tests are passing, and our manual testing works well too. Extracting a Class from CoinCounterViewModel Steve creates a new file called HighScore.ts and moves the starterHighScoreList code from app.ts into here. He moves the interface into this class, and exports it so that is can also be used elsewhere. We have some more problems, and Steve says while TypeScript does its best, occasionally APIs have places where it’s easy to make a mistake and TypeScript can’t help you because the code you wrote is technically valid. In the final episode of this series, we’ll see how we can take advantage of some free tools to improve our website’s performance, and make our TypeScript development experience even better. Part 4 is coming soon
https://zombiecodekill.com/2016/06/10/practical-typescript-migration-typescript-migration-toolbox-and-workflow/
CC-MAIN-2017-30
refinedweb
1,335
65.52
On 11 May 2012 07:38, Stefan Behnel <stefan_ml at behnel.de> wrote: > Hi, > > thing. > I noticed that the > code generates a declaration of PyErr_Clear() into the outside environment. > When used in cdef classes, this leads to an external method being declared > in the class, essentially like this: > > cdef class MyClass: > cdef extern from *: > void PyErr_Clear() > > Surprisingly enough, this actually works. Cython assigns the real C-API > function pointer to it during type initialisation and even calls the > function directly (instead of going through the vtab) when used. A rather > curious feature that I would never had thought of. Yes, normally the parser catches that. > Anyway, this side effect is obviously a bug in the fused types dispatch, > but I don't have a good idea on how to fix it. I'm sure Mark put some > thought into this while trying hard to make it work and just didn't notice > the impact on type namespaces. I. > I've put up a pull request to remove the Py3 specialisation code, but this > is worth some more consideration. Looks good to me, I'll merge it. > Stefan > _______________________________________________ > cython-devel mailing list > cython-devel at python.org >
https://mail.python.org/pipermail/cython-devel/2012-May/002587.html
CC-MAIN-2017-04
refinedweb
197
64.2
Identifying Dataset Sample Rates Today’s example is rather simple, but it answers a common question I’ve heard… What is the sample rate of my dataset? For many ocean observatory datasets, the rates are usually pretty well defined and constant in time. For example, most NDBC offshore buoys are sampled hourly, while CMAN and NOS Water Level stations record every 6 minutes. However, the OOI – with its wide variety of instruments, array locations and telemetry methods – is much more complicated than that. Sampling rates vary from hourly down to 20Hz, with a lot of rates in-between. In addition, the sampling rates aren’t always constant over time. They depend on how precise the data loggers are and whether scientists have requested changes to system configurations based on new scientific goals. Plus, the rates can be different depending on whether you’re working with telemetered (real-time) or recovered datasets. Of course, the proof is in the pudding. Once you’ve downloaded a dataset from the OOI data portal, this notebook provides a quick example to help you calculate the sample rate of the dataset you have in hand. Identifying the Sampling Frequency¶ By Sage Lichtenwalner, May 20, 2020 How often does the OOI sample the ocean? The short answer is, a lot. The sample rates for each instrument depends on its location, power availability and ultimately its science goals. Most fixed-depth instruments sample at least every 15 minutes. But many instruments, like those on profilers or cabled platforms, sample every minute or even every second! And in many cases, an instrument that sends back data at one resolution in real-time, may have higher resolution data available after engineers recover the raw data files. If you want to check out the intended sample rate for a particular instrument, your best resource is the OOI Observation and Sampling Approach document. But know that things change, so to really know the rate, you should download the dataset yourself and check it out. Luckily, thanks to my old colleague Friedrich, all you need is one line of python code to figure it out. First things first...¶ Before we can use a dataset, we first need to request and load it. I'm just going to load some libraries and define some functions and data URLs here. For more details on how all this works, check out the How to Request OOI Data notebook. # Notebook setup import requests import os import re import xarray as xr !pip install netcdf4 import pandas as pd import matplotlib.pyplot as plt # Supress open_mfdataset warnings import warnings warnings.filterwarnings('ignore').4) def get_datalist(url): '''Function to grab all data from specified directory''' tds_url = '' datasets = requests.get(url).text urls = re.findall(r'href=[\'"]?([^\'" >]+)', datasets) x = re.findall(r'(ooi/.*?.nc)', datasets) for i in x: if i.endswith('.nc') == False: x.remove(i) for i in x: try: float(i[-4]) except: x.remove(i) datasets = [os.path.join(tds_url, i) for i in x] # Remove extraneous data files if necessary catalog_rms = url.split('/')[-2][20:] selected_datasets = [] for d in datasets: if catalog_rms == d.split('/')[-1].split('_20')[0][15:]: selected_datasets.append(d + '#fillmismatch') # Add #fillmismatch to the URL to deal with a bug selected_datasets = sorted(selected_datasets) return selected_datasets Example 1: Station Papa Flanking Mooring B - CTD¶ First, let's take a look at the 30m CTD dataset we used in last week's example. As before, we'll specify the dataset URL, then generate the list of files available, and load them. data_url = '[email protected]/20200512T164128069Z-GP03FLMB-RIM01-02-CTDMOG060-recovered_inst-ctdmo_ghqr_instrument_recovered/catalog.html' data_files = get_datalist(data_url) data = xr.open_mfdataset(data_files).swap_dims({'obs': 'time'}) And now, here are the magical lines of code. Note, depending on how big your dataset is, this may take a while to run. df = data.to_dataframe() result = (pd.Series(df.index[1:]) - pd.Series(df.index[:-1])).value_counts() result 00:15:00 35100 00:15:01 5 00:14:59 5 -1 days +06:15:00 1 Name: time, dtype: int64 Basically, all this code is doing is taking the difference between one timestamp and the next, and then summarizing those differences with the .value_counts() function. The result is an array with the time differences in the first column, and the number of times those differences were found in the second. As we can see, for this dataset, we have 35,100 instances where the difference between one point and the next is 15 minutes exactly. For whatever reason, the precision is off by one second for 10 rows in our dataset (5 on one side of 15 minutes, and 5 on the other). We also found one datapoint that was over 1 day different then it's neighbor. This is likely the datapoint where the mooring was recovered and redeployed. We can confirm this by taking a quick look at the pressure record. data.ctdmo_seawater_pressure.plot(); So, give the results above, we can safely say, that the sampling rate for this dataset is 15 minutes. data_url = '[email protected]/20200505T154746379Z-CP01CNSM-SBD11-06-METBKA000-telemetered-metbk_a_dcl_instrument/catalog.html' data_files = get_datalist(data_url) data = xr.open_mfdataset(data_files).swap_dims({'obs': 'time'}) df = data.to_dataframe() result = (pd.Series(df.index[1:]) - pd.Series(df.index[:-1])).value_counts() result 00:01:04.237000 7841 00:01:04.236999 6424 00:01:04.226999 5893 00:01:04.236000 5544 00:01:04.238000 5286 ... 00:01:06.831000 1 00:01:02.745000 1 00:00:35.652000 1 00:01:08.285000 1 00:01:01.423999 1 Name: time, Length: 41928, dtype: int64 So this is interesting... there are apparently almost 42,000 different intervals. But as we can see from the first 5 rows it seems like many are around 1 minute and 4 seconds. Here's an example where precise timing actually makes things a bit more complicated than necessary. Suffice it to say, the Build Meteorology sensor is sampling about every minute. data_url = '[email protected]/20200520T212720777Z-RS03AXPS-SF03A-2A-CTDPFA302-streamed-ctdpf_sbe43_sample/catalog.html' data_files = get_datalist(data_url) data = xr.open_mfdataset(data_files).swap_dims({'obs': 'time'}) df = data.to_dataframe() result = (pd.Series(df.index[1:]) - pd.Series(df.index[:-1])).value_counts() result 00:00:01.000007 28275 00:00:01.000111 19208 00:00:01.000008 18736 00:00:01.000112 15989 00:00:00.999903 15981 ... 00:00:01.000238 1 00:00:00.998835 1 00:00:00.997089 1 00:00:00.997505 1 00:00:00.995630 1 Name: time, Length: 5460, dtype: int64 Like the Meteorological instrument, this profiling CTD also has a lot of different timing intervals in the dataset, due to the precision in how times are recorded. But they all seem to be centered around 1 second, which is a valid sampling rate for an instrument attached to a profiler. Just for fun, let's plot this dataset to see what it looks like. # Scatterplot of Temperature fig = plt.figure(figsize=(10,6)) sc1 = plt.scatter(df.index, df.seawater_pressure, c=df.seawater_temperature, cmap='RdYlBu_r', s=5) plt.xticks(rotation=30) ax1 = plt.gca() ax1.invert_yaxis() # Invert y axis ax1.set_xlim(data.time[0],data.time[-1]) # Set the time limits to match the dataset cbar = fig.colorbar(sc1, ax=ax1, orientation='vertical') # Add colorbar cbar.ax.set_ylabel('Temperature ($^\circ$C)') ax1.set_ylabel('Pressure (dbar)') ax1.set_title('Axial Base Shallow Profiler Mooring CTD'); fig.savefig('RS03AXPS_CTD.png')
https://datalab.marine.rutgers.edu/2020/05/identifying-dataset-sample-rates/
CC-MAIN-2022-40
refinedweb
1,234
60.72
Working with IonicDB Edit on Match 30, 2017: Unfortunately, the Ionic folks decided to not ship the final version of this service. IonicDB is no more. Today marks the launch of a new Ionic service, IonicDB. For those who fondly remember Parse (thanks again, Facebook), this will come as welcome news. IonicDB is a simple data storage system. It lets you store data in the cloud for your mobile apps and skip building a server just to handle simple data CRUD. It also ties nicely with the Ionic Auth system and has the ability to listen to changes to your data in real time. As always - the docs should be the first place you go, but I’ve been playing with this service for a little while now and have some demos that may help get you started. Everything I’m going to show below may be found in my GitHub repo of Cordova examples so you’ll be able to get the full source. A Simple Example To begin, ensure you’ve followed the directions for working with Ionic Cloud in general. This is the prereq for using any of the fancy Cloud-based services. This requires a login with Ionic so if it is the first time you’ve used Ionic Cloud you’ll need to set that up one time. After you’ve set up Ionic Cloud for your app, the DB instructions tell you this: Once you’ve created a database for your app in our dashboard you can start storing and accessing data in your database. So to be clear, you need to get out of code for now, and go to the Ionic Apps site (), find your app, and then enable Ionic DB: Click this nice obvious button and your database will be prepared for your app. This will take you into the dashboard view: There’s a lot of useful info here as well as a look into your stats (which should be pretty boring in a new app), but let me call out a few things in particular. Number one - collections are simply database tables. Ok, not tables, it’s all NoSQL and shiny, but basically, database tables. For those who didn’t grow up writing SQL for back end apps, then just think of these as buckets for your data. If your app works with cats and dogs, then you could have two collections. Really this will be up to you and your app’s needs. Now look at the toggles. They are all pretty self-explanatory I think. The third one, “Auto Create Collections”, is a setting Parse had as well. Basically, while you work on your app, you may be defining new collections as you build it out. (“Oh, the client wants to support cats, dogs, and mules? Ok - let’s add a new collection for mules.”) But most likely, when you’ve gone line, you do not want new collections created. So you’ll toggle this setting off. The first two refer to who can use the database and what particular rules apply - and again, this will be based on your app. So what does the code look like? As I said, I’m not going to repeat every part of the docs - the quick start gives you an idea of what you need to do. Basically you connect and then go to town. You’ve got full CRUD for working with data, but as I said earlier, you also have the ability to listen for new data live, and I really like how easy the service makes this. While the quick start shows you a code snippet, I’ve built a full (but simple) app that shows everything working together. Let me show you how it works, and then I’ll share the code. The one page app consists of a list of Notes, which comes from IonicDB, and a simple text field to add new ones: As you can imagine, typing a message and hitting the button adds a new one. Where things get interesting is when you work with multiple clients. Here’s a video showing this in action: Ok, so let’s look at the code. First, the view, even though it’s rather simple. <ion-header> <ion-navbar> <ion-title> Ionic DB Example </ion-title> </ion-navbar> </ion-header> <ion-content padding> <ion-item> <ion-label>Message</ion-label> <ion-input</ion-input> </ion-item> <button ion-button block (click)="sendMessage()">Send</button> <ion-list> <ion-item * <h2>{{chat.text}}</h2> <p>Posted {{chat.created | date}} at {{ chat.created | date:'shortTime' }}</p> </ion-item> </ion-list> </ion-content> Basically just a form field and button for adding data and a simple ion-list for displaying it. The component code is where the fun is: import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Database } from '@ionic/cloud-angular'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { public chats: Array<string>; public message:string = ''; constructor(public navCtrl: NavController, public db:Database) { this.db.connect(); this.db.collection('chats').order('created','descending').watch().subscribe( (chats) => { console.dir(chats); this.chats = chats; }, (error) => { console.error(error); }); } sendMessage() { this.db.collection('chats').store({text:this.message, created:Date.now()}); } } The first important bit is the import up top - that’s fairly self-explanatory. I’ve created an array of chats representing the data that will be displayed in the app. In the constructor, we connect, then open a collection called chats. I order the data by the created property, then watch and subscribe to the result. That’s it for getting data and knowing when new crap is added. Adding data is done via store, and being all fancy and NoSQL, I literally just pass an object representing my data and IonicDB stores it. As with most NoSQL-ish solutions, the ‘free form’ thing is awesome, but you probably want to have a good idea what your data looks like and try to be as consistent as possible. And that’s it! Nice and simple, right? Let’s take a look at the collections for this app in the dashboard. As you can see, Users is in there by default even if we aren’t doing anything with security. Now let’s look at chats: As you can see, you’ve got some meta data for the collection as a whole, and the ability to Add/Edit/Delete right from the tool. This is cool because while most data may be user generated, you may have data that is read only (and yes, the security model supports that). In that case, you would be able to use the dashboard to set up your data easily. Notice too you can do ad hoq queries here to search for data. An Example with Security So what about security? IonicDB has a pretty deep security model, and to be honest, I find it a bit confusing at time. For my second demo, I had the help of Nick Hyatt from the Ionic team. I think it’s going to take a few apps before I feel very comfortable with it, but I was able to build a complete demo of at least one example of it. Given the previous demo where folks made notes and everyone could see them - how would you modify the code so that notes where user specific and only visible to the users that created them? You begin by making use of the Auth system. (If you’ve never seen that, see my blog post: An example of the Ionic Auth service with Ionic 2). Then, edit your database settings in the dashboard to require authenticated users. That was the first toggle in dashboard seen above. Once you’ve done that, you then need to modify your code a bit. The first change you make is to app.module.ts, in your cloudSettings object: const cloudSettings: CloudSettings = { 'core': { 'app_id': '1f06a1e5' }, 'database': { 'authType': 'authenticated' } }; If you try to connect to the database without being logged in, you’ll get an error. But here’s a nit - Ionic’s Auth system caches logins. So you need to handle this in two places - the application startup, and your login/register routine. So here’s my app.component.ts: import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { HomePage } from '../pages/home/home'; import { LoginPage } from '../pages/login/login'; import { Auth, Database } from '@ionic/cloud-angular'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage; constructor(platform: Platform, public auth:Auth, public db:Database) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); Splashscreen.hide(); if(this.auth.isAuthenticated()) { this.db.connect(); this.rootPage = HomePage; } else { this.rootPage = LoginPage; } }); } } As you can see, if I detect a cached login, I connect to my database before sending the user to the appropriate page. By the same token, the login page has logic for both logging in as an existing user, and registering, and in both of those cases, I also need to connect to my database. I won’t share the entire file as it’s really a small mod from the Auth blog post I linked above (and again, I’ll be sharing links to the full source code), but here is just the part that handles login:(() => { loader.dismissAll(); //this is crucial this.db.connect();; } } You can see the connection in the success handler for logging in. So far so good. The next change is to where we work with data. In both are “get notes” and “add note” logic, we want to filter by the current user. Instead of sharing the entire page, here are those mods, first to “get notes” part: this.db.collection('chats').findAll({creator:this.user.id}).order('created','descending').watch().subscribe( (chats) => { Pretty simple, right? Basically filter by property creator and use my current login id as the value. Here is the new save routine: this.db.collection('chats').store({text:this.message, created:Date.now(), creator:this.user.id}); Now we add a third property, creator, to mark our content. So we’re not quite done yet. While we’ve done the right thing in the app, we also need to lock down the server as well. That requires permissions, so back in the dashboard, enable that second toggle as well. At this point, everything is blocked. So to be clear, if I try to use my app, I won’t be allowed to do anything with the data. I can connect, but I can’t CRUD a lick of content. I’ll begin by enabling the user to create content. In my dashboard, under permissions, I’ll add a new permission: I gave it a name of ‘create’, told it the collection, and then defined the permission rule. Basically - “when we run a store call, text and created can be anything, but the creator must be me.” Next I need to allow myself the ability to read my content: Whew! And that’s it. Remember, by enabling permissions, we’ve automatically closed down every other single operation, so we don’t have to worry about locking down deletes or anything else. As an aside, if you wanted to build a Twitter-like client where everyone’s notes were shared, you would simply modify that read permission like so: findAll({owner: any()) (And again, thank you, Nick!) For the full source code, here are the two app: Let me know if you have any questions (although be gentle, I’m still learning this myself), and let me know what you think!
https://www.raymondcamden.com/2017/01/19/working-with-ionicdb
CC-MAIN-2018-34
refinedweb
1,959
63.8
If you are starting with a fresh Android project or an existing app, follow these steps to add the Kinvey Android library to your app and set up the Kinvey Client. Prerequisites - Java Development Kit (JDK) 1.6 - Android SDK simply follow the installation instructions. This library currently supports Android 2.3 and higher. - An IDE, such as Eclipse or Android Studio, with ADT installed. Manual Project Set Up Eclipse - In Eclipse, create a new Android project: File → New → Project → Android Project. Name it appropriately (eg, "yourapp-android"). Choose Android build target. Specify a package name (eg, "com.yourapp"). Next to "Create Activity" enter "YourAppActivity". Click Finish. - Download the latest Kinvey library (zip) and extract the downloaded zip file. - copy all jars in the libs folder of the extracted zip to your project's libs folder on the file system, create the libs folder if it doesn't exist. - Right click on your project → Build Path → Configure Build Path and on the Order and Export tab ensure Android Private Libraries is checked. - In Eclipse, right click the project → Close Project → right click project (again) → Open Project. Android Studio - In Android Studio, create a new Android project: File → New Project. The Application Name will be displayed to users, and the Module Name is used internally with Android Studio. Specify a package name ("com.myApp"), and set the Minimum SDK level to API 9 or greater. Set the Target SDK to your preferred platform level, and finally Compile With the highest API level available. - Download the latest Kinvey library (zip) and extract the downloaded zip file. - copy all jars in the libs folder of the extracted zip to your project's libs folder on the file system, create the libs folder if it doesn't exist. - After adding the jars, right click on kinvey-android-lib-x.x.x.jarand select Add As Library. Ensure your module is selected, and click OK. Add an App Backend In the Kinvey console, click "New App" and enter the name of your app when prompted. You can find your key and secret on the app backend dashboard page, or in the footer on every page. Cut and paste the key and secret when performing the next steps. Initialize a Client The Client.Builder is used to build and initialize the Client before making any calls to the Kinvey API. The Client.Builder requires the App Key and App Secret obtained from the Kinvey console, as well as your Android Application context. Initializing a Client is usually done within your application's main Activity. import com.kinvey.android.Client; … final Client mKinveyClient = new Client.Builder(your_app_key, your_app_secret , this.getApplicationContext()).build(); final Client mKinveyClient = new Client.Builder(your_app_key, your_app_secret , this.getApplicationContext()).setBaseUrl("<your dedicated host URL>".build(); Using a properties file Hard wiring the appKey and appSecret programatically is a handy way for you to initialize the Kinvey library. However, this is not always the best choice. Often times you may want more control over the library config and would prefer to keep it in a separate properties file. Your kinvey.properties file in the assets folder of your project should contain the properties: # Required settings app.key=your_app_key app.secret=your_app_secret # Optional settings, only required for push gcm.enabled=true gcm.senderID=mySenderID In order to initialize Client with the properties file settings you need to call a different constructor method on the Client.Builder class, then call build(). final Client mKinveyClient = new Client.Builder(this.getApplicationContext()).build(); Verify Set Up You can use myClient.ping(…) to verify that the app has valid credentials. The following code example: - builds a new client - pings the backend with the app credentials import com.kinvey.android.Client; ... final Client mKinveyClient = new Client.Builder(appKey, appSecret, this.getApplicationContext()).build(); mKinveyClient.ping(new KinveyPingCallback() { public void onFailure(Throwable t) { Log.e(TAG, "Kinvey Ping Failed", t); } public void onSuccess(Boolean b) { Log.d(TAG, "Kinvey Ping Success"); } }); Every App has an Active User Your app will be used by a real-life human being; this person is represented by the Active User. This user object must explicitly be created, either with a username and password, OAuth sign-on (such as Facebook, Google+, Twitter, etc.), or by using a utility method to auto-generate a username and password (for apps that don't need the user to log-in)..
http://devcenter.kinvey.com/android/guides/getting-started
CC-MAIN-2015-14
refinedweb
727
59.3
I am trying to write Tkinter-like `GUI` library for iOS Hey everyone, ShadowSlayer here. I've decided to post this thread, to give myself a little motivation. I am trying to write Tkinter-like GUIlibrary (on top of Scene of course!) for Pythonista. Wish me luck! I will post all my updates here. P. S. Maybe I won't success in this project, but at least I am going to try :) - MartinPacker Go for it. I certainly can find a use for it. Sounds like a fun (and challenging) project, though you might want to wait for the 1.5 update. There will be a uimodule that might be more suitable for this than scene. @omz, maybe, but I'd better start with what I have right now. If I understand the logic (which I probably already did), I will be able to later rewrite the library, using the uimodule :) - MartinPacker If 1.5 is Real Soon Now I'd wait. I assume the ui module has some resemblance to other modules in the same area? Is there a way to force end the Scene? Like Scene().stop()? - filippocld223 yes. i think scene.end() I was unable to find a Scene.end()method... import inspect, scene print('\n'.join([member[0] for member in inspect.getmembers(scene.Scene())])) The other methods are documented in and Ole said he would add docs for Scene.stop()here: If you add a Scene.stop()method to your Scene, it will be called when the user clicks the X. The only ways that I have found to really end a Scene are to tap the X in the upper right corner of the window or to launch another Scene. Not sure how close this is to what you're planning to do, but BashedCrab made a simple GUI toolkit named Hydrogen a while ago. You should probably take a look at it, it may be possible to build upon that instead of having to write everything up from scratch. Guys, thanks for your tips :). I am done writing simple Button&StaticText and StaticLink widgets. I will upload the code tomorrow and post the link to it here. Ouch! I've got idea, how to implement Event system a little bit better. But I am getting very weird problems! Can someone help me? A bit hard to explain, you have to run file draggable_frame.py. iGUI.py<br> draggable_frame.py ImportError: No module named events I could not quite figure out how to help you but: - You might want to look at some advise that Ole provided on draggable images: - You can safely remove the .keys()part of lines like: if not id in self.children.keys(): # and return event_type in self.handlers.keys() # can be rewritten as: if not id in self.children: # and return event_type in self.handlers See key in dictat Hey all, I am back. Sorry for not writing anything for so long, I had damn lot of exams. I've finally fixed the problem, and now I have this draggable frame. Gonna add some more stuff and post the first version here soon.
https://forum.omz-software.com/topic/671/i-am-trying-to-write-tkinter-like-gui-library-for-ios
CC-MAIN-2017-43
refinedweb
524
76.01
TRe-- trJoin- ToPath, Tcl_FSConvertToPathType, Tcl_FSGetInternalRep, Tcl_FSGetTrans- latedPath, Tcl_FSGetTranslatedStringPath, Tcl_FSNewNativePath, Tcl_FSGetNativePath, Tcl_FSFileSystemInfo, Tcl_AllocStatBuf - proce- dures to interact with any filesystem #include <tcl.h>) Tcl_FSGetNativePath(pathPtr) Tcl_Obj* Tcl_FSFileSystemInfo(pathPtr) Tcl_StatBuf* Tcl_AllocStatBuf() Tcl_Filesystem *fsPtr (in) Points to a structure containing the addresses of procedures that can be called to perform the vari- ous filesystem operations. Tcl_Obj *pathPtr (in) The path represented by this object is used for the operation in ques- tion. If the object does not already have an internal path rep-- verted to path type. of the file which caused an error in the various copy/rename opera- tions. Tcl_Obj **objPtrRef(out) Filled with an object containing the result of the operation. Tcl_Obj *result (out) Pre-allocated object in which to store (by lappending) the list of files or directories which are suc- cessfully matched in Tcl_FSMatchInDirectory.fsUnloadFileProc_ **unloadProcPtr(out) Filled with the function to use to unload this piece of code. utimbuf *tval (in) The access and modification times in this structure are read and used to set those values for a given Tcl_Obj *basePtr (in) The base path on to which to join the given elements. May be NULL. int objc (in) The number of elements in objv. Tcl_Obj *CONST objv[] (in) The elements to join to the given base path. _________________________________________________________________- tive pro- vide representations and other path-related strings (e.g. the current working directory). One side-effect of this is that one must not pass in objects with a refCount of zero to any of these functions. If such calls were han- dled, call- ing the owning filesystem's 'delete file' function. Tcl_FSRemoveDirectory attempts to remove the directory given by pathPtr by calling the owning filesystem's 'remove directory' function. Tcl_FSRenameFile attempts to rename the file or directory given by src- Path vol-- tents as a Tcl script. It returns the same information as Tcl_EvalOb- j direc- tory for all files which match a given pattern. The appropriate func- tion for the filesystem to which pathPtr belongs will be called. The return value is a standard Tcl result indicating whether an error_SYMBOLIC_LINK and TCL_CRE- ATE information about the specified file. You do not need any access rights to the file to get this information but you need search rights to all directories named in the path leading to the file. The stat structure includes info regard- ing structure- Ptr belongs will be called. The called procedure. Tcl_FSAccess checks whether the process would be allowed to read, write Windows), rdev (same as device on Windows), size, last access time, last modification time, and creation time.Chan- nel leaves an error message in interp's result after any error.mented. This is needed for thread-safety purposes, to allow mul- tiple threads to access this and related functions, while ensuring the results are always valid. Tcl_FSChdir replaces the library version of chdir(). The path is nor- malized. non-NULL, we use it to return con- "~<user>" object is a valid path), then it is returned. Otherwise NULL will be returned, and an error message may be left in the interpreter. A "translated" path is one which contains filesys- sec- ond element may be empty if the filesystem does not provide a further categorization of files. A valid list object is returned, unless the path object is not recog- nized,. A filesystem provides a Tcl_Filesystem structure that contains pointers sim- ple data elements, all entries contain addresses of functions called by the generic filesystem layer to perform the complete range of filesys- tem related actions. File, The structureLength field is generally implemented as sizeof(Tcl_Filesystem), and is there to allow easier binary backwards compatibility if the size of the structure changes in a future Tcl release. The version field should be set to TCL_FILESYSTEM_VERSION_1. These fields contain addresses of functions which are used to associate a particular filesystem with a file path, and deal with the internal handling of path representations, for example copying and freeing such representations. The pathInFilesystemProc field contains the address of a function which is called to determine whether a given path object belongs to this filesystem or not. Tcl will only call the rest of the filesystem func- tions); This function makes a copy of a path's internal representation, the internal representation. This must be implemented if internal representations need freeing (i.e. if some memory is allocated when an internal representation is generated), but may otherwise be NULL. typedef void Tcl_FSFreeInternalRepProc( ClientData clientData); Function to convert internal representation to a normalized path. Only typedef ClientData Tcl_FSCreateInternalRepProc( Tcl_Obj *pathPtr); Function to normalize a path. Should be implemented for all filesys- tems which can have multiple string representations for the same path object. components should be converted from symbolic links. This one exception is required to agree with Tcl's semantics with 'file delete', 'file rename', 'file copy' operat- ing on symbolic links. This function may be called with 'nextCheck- point'); The fields in this section of the structure contain addresses of func- tions which are called to carry out the basic filesystem operations. A filesystem which expects to be used with the complete standard Tcl com- mand set must implement all of these. If some of them are not imple- mented, then certain Tcl commands may fail when operating on paths within that filesystem. However, in some instances this may be desir- able (for example, a read-only filesystem should not implement the last four functions, and a filesystem which does not support symbolic links need not implement the readlink function, etc. The Tcl core expects filesystems to behave in this way). directo- ries the file represented by pathPtr exists, the Tcl_FSStatProc returns 0 and the stat structure is filled with data. Otherwise, -1 is returned, and no stat info is given.. Function to process a Tcl_FSOpenFileChannel() call. Must be imple- mented creating the new channel also assigns it as a replacement for the stan- dard channel. Function to process a Tcl_FSMatchInDirectory() call. If not imple-- tem cor- rect, but on a TCL_OK result, the interpreter should not be modified, but rather results should be added to the result object given (which can be assumed to be a valid otherwise. In this case the result is not owned by the caller. See the documentation for Tcl_FSLink for the correct interpretation of the linkAction flags.. Function to process a Tcl_FSFileAttrsGet() call, used by 'file attributes'.. Function to process a Tcl_FSCreateDirectory() call. Should be imple- mented. Function to process a 'Tcl_FSRemoveDirectory()' call. Should be imple- mented an error does occur, the name of the file or directory which caused the error should be placed in errorPtr. Tcl_FSStatProc defined above, except that if it is applied to a sym- bolic link, it returns information about the link, not about the target file. Tcl_FSCopyDirectoryProc when needed to copy them (even if they are symbolic links to directories). Function to process a Tcl_FSRenameFile() call. If not implemented, Tcl will fall back on a copy and delete mechanism. Therefore it need only be implemented if the filesystem can perform that action more effi- ciently. typedef int Tcl_FSRenameFileProc( Tcl_Obj *srcPathPtr, Tcl_Obj *destPathPtr); The return value is a standard Tcl result indicating whether an error occurred in the renaming process. Function to process a Tcl_FSCopyDirectory() call. If not implemented, Tcl will fall back on a recursive create-dir,. Function to unload a previously successfully loaded file. If load was implemented, then this should also be implemented, if there is any cleanup action required. typedef void Tcl_FSUnloadFileProc( Tcl_LoadHandle loadHandle); direc- tory . Function to process a Tcl_FSChdir() call. If filesystems do not imple-.
http://www.syzdek.net/~syzdek/docs/man/.shtml/man3/Tcl_FSChdir.3.html
crawl-003
refinedweb
1,260
55.13
Have you ever wondered how spell checkers, in any word editor, suggest you a list of probable other words whenever you have any spelling mistake?? This is done using phonetic search. Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones (pronounced the same as another word but differs in meaning, and may differ in spelling) to be encoded to the same representation so that they can be matched despite minor differences in spelling e.g. bear - beer, Nelson - Neilson - Neelson etc. It is now a standard feature of popular database softwares such as DB2, PostgreSQL, MySQL, Ingres, MS SQL Server and Oracle and some major word editors. Soundex algorithm This algorithm was developed by Robert Russell in 1910 for the words in English. The main principle behind this algorithm is that consonants are grouped depending on the ordinal numbers and finally encoded into a value against which others are matched. It aims to find a code for every word by above process which is called soundex code. The Soundex code for a name consists of a letter followed by three numerical digits: the letter is the first letter of the name, and the digits encode the remaining consonants. The complete algorithm to find soundex code is as below: -. -. Soundex Implementation in Java One implementation of Soundex algorithm is as below: package com.howtodoinjava.examples; public class Soundex { public static String getGode(String s) { char[] x = s.toUpperCase().toCharArray(); char firstLetter = x[0]; //RULE [ 2 ] //Convert letters to numeric code for (int i = 0; i < x.length; i++) { switch (x[i]) { case 'B': case 'F': case 'P': case 'V': { x[i] = '1'; break; } case 'C': case 'G': case 'J': case 'K': case 'Q': case 'S': case 'X': case 'Z': { x[i] = '2'; break; } case 'D': case 'T': { x[i] = '3'; break; } case 'L': { x[i] = '4'; break; } case 'M': case 'N': { x[i] = '5'; break; } case 'R': { x[i] = '6'; break; } default: { x[i] = '0'; break; } } } //Remove duplicates //RULE [ 1 ] String output = "" + firstLetter; //RULE [ 3 ] for (int i = 1; i < x.length; i++) if (x[i] != x[i - 1] && x[i] != '0') output += x[i]; //RULE [ 4 ] //Pad with 0's or truncate output = output + "0000"; return output.substring(0, 4); } } Let’s see how it to use above algorithm. class Main { public static void main(String[] args) { String name1 = "beer"; String name2 = "bear"; String name3 = "bearer"; System.out.println(Soundex.getGode(name1)); System.out.println(Soundex.getGode(name2)); System.out.println(Soundex.getGode(name3)); } } Output: B600 B600 B660 It is clear from above output that words “bear” and “beer” have same code; so they are phonetic. Word “bearer” has different code because it’s not phonetic same. You can look at some implementations for soundex algorithm available well e.g. Apache commons Soundex Implementation. References Happy Learning !!
https://howtodoinjava.com/algorithm/implement-phonetic-search-using-soundex-algorithm/
CC-MAIN-2022-27
refinedweb
477
62.27
I have 2 python classes: Player, and Board. The board contains a dict with "A1" reference style for spaces. player.py's Player class: from board import Board class Player: def __init__(self): self.name = input("Name: ") self.board = Board(3, ["A", "B", "C"]) class Board: EMPTY = "0" spaces = {} def __init__(self, size, letters): for let in letters: for num in range(1, size + 1): self.spaces["{}{}".format(let, num)] = self.EMPTY def place_piece(self, spot): self.spaces[spot] = "X" def display_board(self): for let in letters: for num in range(1, size + 1): print("\n" + self.spaces["{}{}".format(let, num)] from player import * from board import * current_player = 1 players = [] player_1 = Player() player_2 = Player() players.append(player_1) players.append(player_2) while True: # Switches players current_player = abs(current_player - 1) # Prints the current player's name print(players[current_player].name) # Calls some method which should alter the current player's board players[current_player].board.place_piece(input("> ")) # Calls some method which should show the current player's board players[current_player].board.show_board() As it is written now the code posted shouldn't be working. The two methods in Board, place_piece and display_board, need to accept 'self' as a first argument. Assuming this is a typo here's what's happening. The class Board is created with a class member spaces. Each time you're referencing self.spaces in an object, it is not found in the object is instead looked up in the class. Meaning you're using the same dict for all object of the class Board. Instead, to create a regular member place the declaration in the init method as you do in the Player class: class Board: EMPTY = "0" # Remove spaces = {} def __init__(self, size, letters): self.spaces = {} ... Finally, since you're using Python 2x please let me encourage you to always use new style classes (i.e. write class Board(object)). See What is the difference between old style and new style classes in Python?
https://codedump.io/share/seEtWRNM27aA/1/python-referencing-object-inside-object-incorrectly
CC-MAIN-2018-13
refinedweb
326
59.3
ComponerComponer Componer is a workflow tool to help frontend developers to coding more easily. Support ES6. On the shoulders of gulp, bower, webpack, karma, jasmine and so on. Install and initializeInstall and initialize We have two commander componer and componout, componer is for projects which have .componerrc and componout is for componouts which have componer.json, However a componout could be from a project. # install componer globally npm install -g componer However, you have a way to use it without install it globally. git clone && cd componer npm install && npm run build && npm link With runing link, you can use componer commanders in local without installing. # initialize a project mkdir test-project && cd test-project && componer init After this, you will get a project which contains special directory structure. # initialize a componout which is not in a componer project mkdir test-componout && cd test-componout && componout init Answer the questions, and get a componout by special template. If you only want to create a componout, run: mkdir my-componout && cd my-componout cpon init cpon commander is a simple commander to run in a componout directory with a componer.json file in it. Usage of componer commanderUsage of componer commander componer -v componer -h componer init componer update componer add componoutname [-t templatename|typename -a yourgitname] componer build [componoutname] componer watch [componoutname] componer preview componoutname componer test [componoutname] [-D] [-b Chrome|Firefox|PhantomJS] componer remove/rm componoutname componer list/ls componer clone componoutname componer install [for componoutname] componer install packagename for componoutname componer link [componoutname] componer initcomponer init After your npm install -g componer, you should create a empty directory, and enter it to run componer init. Then you will see different files be initialized into this directory. This directory is called a componer project directory. When you run componer init, it will ask you two questions: your github name and the package name. The value you typed in will be found in package.json and .componerrc. So you can modify the file later. Your github name is important, because it will be used when you run componer add. If you do not give a --author parameter when you run componer add task, componer will use your github name to create the package github registry address. init commander will run 'npm install' at the last automaticly. componer resetcomponer reset When you use a new version of componer, your local project files a older one. If you want to use componer default program files, you can run update commander. However, files in gulp directory and gupfile.babel.js will be covered, so if you have ever changed these files, do not run update directly. 'npm install' will be run automaticly after files updated. componer add [-t|--template default] [-a|--author your-name]componer add [-t|--template default] [-a|--author your-name] Add a componout. A componout is a production created by componer. Componout name should must be given. When you run componer add task, you can pass -t and -a parameters. -t is short for --template, if you run componer add my-test -t npm, my-test componout will be a npm package. Default templates are directory names in gulp/templates. In fact, a template is a type of componout, so you will see I use type instead of template in the following content. If it runs successfully, you will find a new dirctory in componouts directory. If you want to add a new type of componout, just create a new dirctory in your gulp/templates directory. Template name is the directory name. In template file, you can use {{component-name}} and {{author-name}} as string template. defaults.template and project.author options in .componerrc in your project root path will be used as default values if you not give a -t or -a option. componer build [name]componer build [name] When you run build task, componer will compile your ES6 code to ES5 code and combine your code into one file by webpack. At the same time, scss files will be compiled to css files, minified by cssmin, and be put in dist directory too. However, componer.json is a special file which has information used for compiling for a componout. Use an array to arrange compile files: "build": [ /* compile and bundle javascript, judged by from file */ { /* entry file to build with */ "from": "src/script/bar-chart.js", /* output file after be built */ "to": "dist/js/bar-chart.js", "options": { /* create another .min.js file */ "minify": true, /* create sourcemap file */ "sourcemap": true, /**. **/ "vendors": [] }, /* settings for webpack-stream */ "settings": {} }, /* compile scss to css */ { "from": "src/style/bar-chart.scss", "to": "dist/css/bar-chart.css", "options": { "minify": true, "sourcemap": true }, "settings": { "sass": {}, // settings for node-sass "postcss": {}, // settings for postcss "nextcss": {}, // settings for nextcss "assets": {} // settings for gulp-css-copy-assets } } ], You can use only one object, if you have only one file to build: "build": { "from": "src/script/bar-chart.js", "to": "dist/js/bar-chart.js", "options": { "minify": true, "sourcemap": true, "vendors": false } }, If name is not given, all componouts will be built one by one. componer watch [name]componer watch [name] When you are coding, you can run a componer watch task to build your code automaticly after you change your code and save the changes. Only src directory is being watched. If name is not given, all componouts's src will be being watched. componer previewcomponer preview Open browser to preview your code. browser-sync is used. preview options in componer.json make sense. "preview": { /* html to use as home page */ "index": "preview/index.html", // required /* script to inject to home page, will be compiled by webpack */ "script": "preview/bar-chart.js", /* will be compiled by sass */ "style": "preview/bar-chart.scss", /* middlewares to be used, look into browser-sync config `middleware` */ "server": "preview/server.js", /* tmp dir to put preview tmp files */ "tmpdir": ".preview_tmp", // default: '.preview_tmp' /**. Why we need this? Because when you preview, browser will refresh automaticly after you change your watch files (in the following), bundle js being built, separate vendors avoid to build this vendors into re-build bundle file, which save your time. **/ "vendors": true, /* look into browser-sync config `files` */ "watch": [ "preview/index.html", "preview/bar-chart.js", "preview/bar-chart.scss", "src/**/*", ], /* look into browser-sync config `watchOptions` */ "watchOptions": {} }, - index file A html file, use <!--styles--> and <!--vendors--> <!--scripts--> for scripts files to be injected. - server file Export an object or an array or a function. Look into browser-sync middleware config. - scripts files script and style files will be compiled and be kept in memory, not true local files (though files compiled will be created after page shown). componer test [name] [-D|--debug] [-b|--browser PhantomJS|Chrome|Firefox|IE|Safari]componer test [name] [-D|--debug] [-b|--browser PhantomJS|Chrome|Firefox|IE|Safari] Componer use karma and jasmine as framework. You can pass -D (short for --debug) and -b (short for --browser). When use --debug mode, browser will be open, you can debug testing code in browser. You can use --browser to change to test in different browser. For example, you can use Firefox. Only "Chrome" or "Firefox" or "PhantomJS" can be used. "PhantomJS" is default. When you test a node module componout, it is different. You should modify componer.json test.browsers to be Terminal. If test.browsers = Terminal, jasmine-node will be used to test node scripts which can be run only in command line not in browsers. Do as so, -b will not work. If name is not given, all componouts will be tested. -D will not work, and debug mode will be ignored. Notice: if you want to use PhantomJS, you should install PhantomJS browser first on you compouter, it is a browser. componer removecomponer remove Remove the named componout, run unlink command if possible. componer listcomponer list List all componouts information. componer install [for name] [-F|--force]componer install [for name] [-F|--force] Install all dependencies for a componout based on its bower.json and pacakge.json. componer install for my-componout If you do not pass componout name, all componouts' dependencies will be installed. This is always run at the first time after you clone your project. componer install Packages will be put into node_modules/bower_components directory in your project root path. So all packages are shared amoung different componouts. bower always come first In componer, bower components always come before npm packages. For example, if you install a package which has both bower and npm packages, bower package will be recommanded to install firstly. If you require a package, and this package has both bower and npm packages in local directory, bower component will be used firstly. virtual cache If a package exists in local, no matter in bower_components or node_modules, it will not be installed again. If you want to force install a new version, you can pass -F|--force to install, e.g. componer prepare xxx -F. Then no matter what packages there are in local, all xxx dependencies will be install (may cover local pacakges version). version When you run prepare task, you should know that compner will not help you to resolve your dependencies version problems. Bebind versions will cover the previous ones and conflicts will be show and the end. For example, you run componer prepare to install all dependencies of your componouts. Different dependence packages may have different versions. Only the last same named package's version componer meets will be installed. However, virtual cache works, if you install all dependencies packages, if a dependence package exists in local, it will not be installed again. Use --force to install all dependencies if you want to reinstall all dependencies. download directory Componer keep only one same name package in local, for example, if there is a jquery installed in bower_components, no matter which version it has, jquery will never be installed again (until you use -F). Bower and npm packages are put in different directories. But, only one package will be installed, even if there are two pacakges have the same name and from bower.json and package.json. Remember bower always come first. componer install [@version] for|to [-D|--dev] [-F|--force]componer install [@version] for|to [-D|--dev] [-F|--force] Install a package for a componout. componer install jquery for my-componout New package will be put into node_modules/bower_components directory in your project root path. A new dependence will be added into your componout's package.json or bower.json. Bower components always come first. So if your componout has a bower.json, new packages will always be installed by bower. But if a package has only npm package, bower install will fail, when this happens, npm install will be run to install this package. -D is to save to devDependencies. If you do not pass -D, new pacakge will be save to dependencies. -F is to install new package ignore local virtual cache. version conflicts But force install may cause version conflicts. For example, one of your componouts dependents on jquery@1.12.0, but you try jquery --force, the latest version of jquery will be download, and old verison will be covered. So you should have to update your componouts to support higher version jquery manually. componer link [-F|--force]componer link [-F|--force] Link (Symbolic link) componout as package/component into node_modules/bower_components. In componer, components follow rules with bower components. So if you want to link your component as a bower component, you should create your componout as a bower component with bower.json. Firstly, type option in your componout's componer.json should be set to 'bower' or 'npm'. If type is bower, and there is a bower.json in your componout dirctory, it will be linked as bower component. The same logic, npm package needs type to be 'npm' and there is a package.json in your componout. After you run componer link a-name, you can use require('a-name') in other componouts to use this componout. There is not a unlink task. It means you should have to unlink your packages by manual. However, when you remove componouts, unlink will be automaticly run by componer. Notice: on windows, it is different. If you have no permission to do ln, and you pass -F, componer will use bower/npm link instead. For this, you have to know about bower link and npm link. Or componer will copy componout to packages directory, so you have to run link again after you update your code. componer clone [name] [-u|--url your-git-registry-address] [-I|--install] [-L|--link]componer clone [name] [-u|--url your-git-registry-address] [-I|--install] [-L|--link] Clone a componout from, by git. You can change registries in .componerrc with defaults options. If -u options is set, registry will be insteaded by this url. You can try: componer clone class-base After that, a componout named class-base will lay in your componouts directory. You will find this componout to be a git registry. -I is to run componer install task after this componout cloned to install its dependencies. -L is to run componer link task after it cloned to link it to package directories. If you do not pass a name to the cli, all of dependencies in .componerrc will be download into componouts directories. Notice, dependencies in .componerrc are different from ones in bower.json or pacakge.json, they are only use for clone, not for package dependencies. So after you clone from git, you should run componer install to install their dependencies. cpon commander Componer provide a cpon commander to run in a local componout directory. For example, you git clone a registry which has a componer.json from github, and do not want to create a componer project, want to re-build the componout, you can do like this: git clone && cd xxx # install dependencies cpon install # build cpon build cpon initcpon init create a new componout with componer templates, which has three type, npm, bower and app. Componer will ask you some questions, you could just follow the questions and give the answers. cpon install [-F|--force]cpon install [-F|--force] Install dependencies for current componout. All npm and bower dependencies will be installed in current directory. cpon buildcpon build Build current componout following the default rule of componer. If you use componer to create a componer project, you can change the files in gulp directory to build up your own workflow, but if you use cpon, it will use componer default workflow rules. cpon previewcpon preview Preview current componout by browsersync. cpon testcpon test Test current componout by karma and jasmine. GeneratorGenerator All componer command should be run in a componer directory. How about the directory of componer directory? --- your-project-directory `- componouts # all componouts will be put here |- gulp | `- tasks # all gulp tasks files, you can even modify by yourself | |- templates # componouts type templates | |- drivers # webpack, sass and their config files | |- utils # gulp helper files | `- loader.js # basic functions and config loader |- bower_components |- node_modules |- gulpfile.babel.js |- package.json |- .componerrc # componer cli config of this project |- .bowerrc `- .babelrc All files can be modified, but you should follow the rules. ComponoutComponout A componout should must contains a componer.json file, which provides build, preview, test information. We have three default type of componout: npm: use this type to create a npm package, which is created for node runtime modules, not for browser-end. bower: use this type to create a bower component, which is created for browser-end used, not for node runtime. app: use this type to create a website application, which is NOT used as a node runtime module or browser-end package. So in app template directory, bower.json and package.json only contains (dev)dependencies options. Normal directory structure: -- componout `- src | `- script | |- style | `- ... |- assets |- preview |- test | `- specs | |- data | |- reporters | `- ... |- dist |- componer.json |- README.md `- ... You can use componer to create node runtime packages, browser-end components and applications. The difference amoung this types is componer.json, packages of npm always run in node environment, so the test options in componer.json is different, and there is no preview options. Applications will contains all dependencies, so there is not externals options in componer.json. In the core idea of componer "组件是素材,不是作品。", I suggest developers to hold up component ideas. You build components, and provide to others to use directly, but in fact, you do NOT need to build, because others developers who use your component will use your components source code to build all by themselves. So you can see in default component template, main option in bower.json and package.json are point to src files, not built files. Keep in mind that components are used as resources of other productions, not as productions. A component should follow the idea of independence. When run build task, components' or packages' dependencies will not be packed by webpack. However, "bower_components" is automaticly considered as modules which can be require in source code, so just use bower component name to import the component. However, bower components provide style files, such as bootstrap providing source less/sass files in main option in bower.json. If you use bower component instead of npm package, webpack will include this styles in javascript code. dependencies options in bower.json or package.json will be external modules in built module componout. devDependencies in bower.json and package.json are no useful when building, but will be installed when you run componer install task. All dependencies should be install in "bower_components" and "node_modules" directories in your componer root directory, which in your componout directories will be ignore when building. So run componer install [name] after you change the dependencies in .json files of componout manually. The order of packages loaded by webpack In componer, if you use require('some-module') or import 'some-module' to include a external module, componer will use webpack to build all codes together. However, not all modules lay in node_modules directory, you can use bower_components packages and componouts as modules. The order to find module is bower_components > node_modules > componouts, so after you create a component in your componouts directory, you do NOT need to link it to modules dirctory. But if there are three same package in bower_components, node_modules and componouts, which in bower_components will be used as default. However, you can use componer link to link a componout to bower_components to improve its priority. (We use a plugin which makes bower components higher then node modules.) But if you want to use @import 'some-module'; in sass, you MUST link it to modules dirctory. Style files always can be used as bower packages. Just remember this. Share project - setup your project You could install bower to support bower components in your poject. And create a .bowerrc to set default config of bower. Babel config is default put in package.json. You could mv it to .babelrc. However, if you want to publish your project minimality, you could just change package.json. .jshintrc is used to check your code, if you want to ignore some warning, add this file and add your own rules. - minimality share project If you want to share your project minimality, you can only pack components, .componerrc and package.json, push them to git registry. - componouts |- componout1 |- componout2 `- ... - .componerrc - package.json Notice: do NOT push your test reporters, preview tmp dirs and dist dirs to your registry. After another developer cloned your code, he/she could only run: componer reset -I All componer relative files will be recover. gulp tasksgulp tasks Componer is a shell of node command, tasks are using gulp task framework, you can even modify the previous tasks for you special project. All tasks are in gulp/tasks directory. You can even add a new gulp tasks in this directory, and run the new task by run gulp new-task in your componer directory. Notice: you should follow process.args to use cli parameters. MIT License.
https://www.npmjs.com/package/componer
CC-MAIN-2020-10
refinedweb
3,334
58.18
Can someone tell me what is wrong with my program? (below) It builds without any errors, but any numbers that I input for cost and markup, the retail just comes out as "00411168" no matter what numbers I input. Help would be greatly appreciated!!! Code:#include <iostream> #include <iomanip> using namespace std; double retail (double, double); int main() { double cost; double markup; cout << "What is the item's wholesale cost? "; cin >> cost; cout << endl; cout << "What is the markup percentage? "; cin >> markup; cout << endl; retail (cost, markup); cout << "The retail price of the item is " << retail << fixed << setprecision(2) << endl; return (0); } double retail (double wholesaleCost, double markupPercentage) { return (wholesaleCost + (wholesaleCost * (markupPercentage/100))); }
http://cboard.cprogramming.com/cplusplus-programming/124991-programming-probelm-please-help.html
CC-MAIN-2015-27
refinedweb
113
61.46
This is your resource to discuss support topics with your peers, and learn from each other. 01-31-2011 03:12 PM? package { import flash.display.Sprite; import qnx.media.QNXStageWebView; // The following metadata specifies the size and properties of the canvas that // this application should occupy on the BlackBerry PlayBook screen. [SWF(width="1024", height="600", backgroundColor="#cccccc", frameRate="30")] public class Main extends Sprite { private var webView:QNXStageWebView; public function Main():void { webView = new QNXStageWebView(); webView.loadURL(""); } } } Solved! Go to Solution. 01-31-2011 04:03 PM Just compile against the whole BB SDK under /sdks folder of the FB. And if for some reason that you cannot, there are 2 QNX SWC files, so try the other one. 01-31-2011 04:26 PM I added all swc-files in ...\SDK\blackberry-tablet-sdk-0.9.1\frameworks\lib It doesn't work 01-31-2011 04:48 PM What is your development environment? FB4? Just add the SDK to the IDE and select it as the library for the project. You should be using SDK 0.9.2. When you say "it doesn't work", what does'nt work? Compile, runtime, display? 01-31-2011 04:49 PM There is a lot more in getting the webview to be shown and work. Have you searched the threads on the trial and tribulations of other developers? 01-31-2011 05:04 PM Hi, I use "FlashDeveop" and I think that's the problem. It's not that easy like in FlashBuilder 4. It doesn't work means that there is no change to the described behaviour. I think the message "Class qnx.media::QNXStageWebView could not be found" is normal because it's alsways a problem to run the QNX specific stuff outside the simulator. But the crash in the simulator is curious. 01-31-2011 05:06 PM I found an example here: seems it's soooo easy .... that drives my crazy Maybe I give it a try with FB4. I think there is a trial. 01-31-2011 06:19 PM - edited 01-31-2011 06:19 PM If you have the environment setup properly, it should compile fine (accept that the web view gets odd compile errors every other time). Runtime (outside of the simulator), you will probably get a PPS exception. There are several threads in the forum that covers the development and depolyoment of the QNX web view. Suggest that you review those to see if that helps. 01-31-2011 06:23 PM That is a nice tutorial. 01-31-2011 11:29 PM @Levion - ah yes, the WebView bogus errors! this is a known issue and there are 2 back to back errors that will show up inside Burrito, requiring you to save your project 3 times in order to deploy it. (and or see any true errors you have) This only occurs in projects that import the QNXStageWebView... Errors that occur in order. (just add then delete a space to re-save) 1.) An internal build error has occurred. Right-click for more information. 2.)1131: Classes must not be nested Once the errors clear, if you save again, the errors will re-appear and you'll have to save 3 more times. Needless to say, this is **MAJORLY** frustrating!!!! I'm not sure if the issue is with Burritto, or the SDK or what, but many of us would really love a fix! ;-)
https://supportforums.blackberry.com/t5/Adobe-AIR-Development/Class-not-found-when-using-QNXStageWebView/m-p/766381
CC-MAIN-2017-09
refinedweb
575
75.91
MLMARK This feature is not supported on the Wolfram Cloud. This feature is not supported on the Wolfram Cloud. is a MathLink type representing a mark in the expression stream. DetailsDetails - MLMARK is defined in the file mathlink.h, which should be included in the source code for any MathLink-compatible program. ExamplesExamplesopen allclose all Basic Examples (1)Basic Examples (1) #include "mathlink.h" /* look ahead in the expression stream on a link and reset */ void f(MLINK lp) { MLMARK mark; mark = MLCreateMark(lp); if(mark == (MLMARK)0) { /* unable to create mark in the stream on lp */ } /* now peek ahead and see what is coming */ switch(MLGetNext(lp)) { case MLTKINT: /* integer data */ case MLTKREAL: /* floating-point data */ } /* now restore to the original point */ mark = MLSeekToMark(lp, mark, 0); if(mark == (MLMARK)0) { /* unable to seek to the mark position in lp */ } MLDestroyMark(lp, mark); }
http://reference.wolfram.com/language/ref/c/MLMARK.html
CC-MAIN-2014-41
refinedweb
144
52.8
#include <hallo.h> * Matěj Hausenblas [Tue, Mar 18 2003, 11:19:27PM]: > I would like to know, if in general nowadays the DVD/CDRW drives on laptops > are supported by cdrecord and if getting them to work is the same as getting > a standard drive to work on a desktop PC. (I mean ide-scsi emulation, or even > better true scsi). Internal drivers are used the same way as the big versions. What I would like is to have a driver for the external Freecom/Toshiba drive. It is not USB or similar, it is a cardbus card which is registred correctly on the PCI bus without a driver for it. If someone has an idea how to make a such thing work, please tell me. Gruss/Regards, Eduard. -- Eine Regierung darf sich nie in Abhängigkeit eines einzigen Herstellers begeben, wenn sie unabhängig bleiben möchte. -- Presse-Team
http://lists.debian.org/debian-laptop/2003/03/msg00318.html
CC-MAIN-2013-48
refinedweb
147
76.66
This Visual Basic Tutorial is all about Sending an Email. In Visual Basic, sending e-mails are allowed in your application. The System.Net.Mail is the namespace that contains classes that is used for sending e-mails to a Simple Mail Transfer Protocol (SMTP) server for delivery. The SmtpClient class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). Take note that in sending e-mail you must specify the SMTP host server because the Host and Port properties will be different for various host server. In here, we will be using Gmail server. If the STMP server requires you for the authentication, you must need to give the Credentials Sender’s email address should be provided same as the recipients using the MailMessage.From and MailMessage.To properties. Specify also the content of message by using MailMessage.Body property. Example: - Open the Visual Basic, select “File” on the menu, hit new and create a new project. - The New Project dialog will appear. Select “windows” in the project types, hit the “windows form application” in the templates and hit “ok“. - Design the form this way. See it Below. - dd the following code in the code editor. Visual Basic Readers might read also:
https://itsourcecode.com/tutorials/visual-basic-tutorial/24-sending-an-email/
CC-MAIN-2019-47
refinedweb
208
58.89
This chapter begins our tour of the Python language. In an informal sense, in Python we do things with stuff.1 classes or external language tools such as C extension libraries. Although we’ll firm up this definition later, objects are essentially just pieces of memory, with values and sets of associated operations. As we’ll see, everything is an object in a Python script. Even simple numbers qualify, with values (e.g., 99), and supported operations (addition, subtraction, and so on). Because objects are also the most fundamental notion in Python programming, we’ll start this chapter with a survey of Python’s built-in object types. Later chapters provide a second pass that fills in details we’ll gloss over in this survey. Here, our goal is a brief tour to introduce the basics. Before we get to the code,. We’ll move on to study statements in the next part of the book, though we will find that they largely exist to manage the objects we’ll meet here. Moreover, by the time we reach classes in the OOP part of this book, we’ll discover that they allow us to define new object types of our own, by both using and emulating the object types we will explore here. Because of all this, built-in objects are a mandatory point of embarkation for all Python journeys. Traditional introductions to programming often stress its three pillars of sequence (“Do this, then that”), selection (“Do this if that is true”), and repetition (“Do this many times”). Python has tools in all three categories, along with some for definition—of functions and classes. These themes may help you organize your thinking early on, but they are a bit artificial and simplistic. Expressions such as comprehensions, for example, are both repetition and selection; some of these terms have other meanings in Python; and many later concepts won’t seem to fit this mold at all. In Python, the more strongly unifying principle is objects, and what we can do with them. To see why, read on.. Table 4-1 previews Python’s built-in object types and some of the syntax used to code their literals—that is, the expressions that generate these objects.2 Some of these types will probably seem familiar if you’ve used other languages; for instance, numbers and strings represent numeric and textual values, respectively, and file objects provide an interface for processing real files stored on your computer. To some readers, though, the object types in Table 4-1 may be more general and powerful than what you. Also shown in Table 4-1, program units such as functions, modules, and classes—which we’ll meet in later parts of this book; we’ll explore these in later parts too, though in less depth due to their specialized roles. Despite its functions in library modules—for example, in the re and socket modules for patterns and sockets—and have behavior all their own. We usually call the other object types in Table 4-1 core data types, though, because they are effectively built into the Python language—that is, there is specific expression syntax for generating most of them. For instance, when you run the following code with characters surrounded by quotes: >>> 'spam' you are, technically speaking, running a literal expression that. In formal terms, this means that Python is dynamically typed, a model that keeps track of types for you automatically instead of requiring declaration code, but it is also strongly typed, a constraint that means you can perform on an object only operations that are valid for. If you’ve done any programming or scripting in the past, some of the object types in Table 4-1 will probably seem familiar. Even if you haven’t, numbers are fairly straightforward. Python’s core objects set includes the usual suspects: integers that have no fractional part, floating-point numbers that do, and more exotic types—complex numbers with imaginary parts, decimals with fixed precision, rationals with numerator and denominator, and full-featured sets. Built-in numbers are enough to represent most numeric quantities—from your age to your bank balance—but more types are available as third-party add-ons. Although it offers some fancier options, Python’s basic number types are, well, basic. Numbers in Python support the normal mathematical operations. For instance, the plus sign ( +) performs addition, a star ( *) is used for multiplication, and two stars ( **) are used for exponentiation: >>> 123 + 222 # Integer addition345 >>> 1.5 * 4 # Floating-point multiplication6.0 >>> 2 ** 100 # 2 to the power 100, again1267650600228229401496703205376 Notice the last result here: Python 3.X’s integer type automatically provides extra precision for large numbers like this when needed (in 2.X,)) # How many digits in a really BIG number?301030 This nested-call form works from inside out—first converting the ** result’s number to a string of digits with the built-in str function, and then getting the length of the resulting string with len. The end result is the number of digits. str and len work on many object types; more on both as we move along. On Pythons prior to 2.7 and 3.1, once you start experimenting with floating-point numbers, you’re likely to stumble across something that may look a bit odd at first glance: >>> 3.1415 * 2 # repr: as code (Pythons < 2.7 and 3.1)6.2830000000000004 >>> print(3.1415 * 2) # str: user-friendly6.283 The first result isn’t a bug; it’s a display issue. It turns out that there are two ways to print every object in Python—with full precision (as in the first result shown here), and in a user-friendly form (as in the second). Formally, the first form is known as an object’s as-code repr, and the second is its user-friendly str. In older Pythons, the floating-point repr sometimes displays more precision than you might expect. The difference can also matter when we step up to using classes. For now, if something looks odd, try showing it with a Better yet, upgrade to Python 2.7 and the latest 3.X, where floating-point numbers display themselves more intelligently, usually with fewer extraneous digits—since this book is based on Pythons 2.7 and 3.3, this is the display form I’ll be showing throughout this book for floating-point numbers: >>> 3.1415 * 2 # repr: as code (Pythons >= 2.7 and 3.1)6.283 Besides expressions, there are a handful of useful numeric modules that ship with Python—modules are just packages of additional tools that we import to use: >>> import math>>> math.pi3.141592653589793 >>> math.sqrt(85)9.219544457292887 The math module contains more advanced numeric tools as functions, while the random module performs random-number generation and random selections (here, from a Python list coded in square brackets—an ordered collection of other objects to be introduced later in this chapter): >>> import random>>> random.random()0.7082048489415967 >>> random.choice([1, 2, 3, 4])1 Python also includes more exotic numeric objects—such as complex, fixed-precision, and rational numbers, as well as sets and Booleans—and the third-party open source extension domain has even more (e.g., matrixes and vectors, and extended precision numbers). We’ll defer discussion of these types until later in this chapter and book. So far, we’ve been using Python much like a simple calculator; to do better justice to its built-in types, let’s move on to explore strings. Strings are used to record both textual information (your name, for instance) as well as arbitrary collections of bytes (such as an image file’s contents). They are our first example of what in Python we call a sequence—a positionally ordered collection of other objects. Sequences maintain a left-to-right order among the items they contain: their items are stored and fetched by their relative positions. Strictly speaking, strings are sequences of one-character strings; other, more general sequence types include lists and tuples, covered later. As sequences, strings support operations that assume a positional ordering among items. For example, if we have a four-character string coded inside quotes (usually of the single variety), we can verify its length with the built-in len function and fetch its components with indexing expressions: >>> S = 'Spam' # Make a 4-character string, and assign it to a name>>> len(S) # Length4 >>>.] # The last item from the end in S'm' >>> S[-2] # The second-to-last item from the end'a' Formally, a negative index is simply added to the string’s length, we wish. second of the preceding operations, for instance, gives us all the characters in string S from offsets 1 through 2 (that is, 1 through in the second-to-last command'Spam' >>>. Also notice in the prior examples that we were not changing the original string with any of the operations we ran on it. Every string operation is defined to produce a new string as its result, because strings are immutable in Python—they cannot be changed in place after they are created. In other words, you can never overwrite the values of immutable objects. either immutable (unchangeable) or not. In terms of the core types, numbers, strings, and tuples are immutable; lists, dictionaries, and sets are not—they can be changed in place freely, as can most new objects you’ll code with classes. This distinction turns out to be crucial in Python work, in ways that we can’t yet fully explore. Among other things, immutability can be used to guarantee that an object remains constant throughout your program; mutable objects’ values can be changed at any time and place (and whether you expect it or not). Strictly speaking, you can change text-based data in place if you either expand it into a list of individual characters and join it back together with nothing between, or use the newer bytearray type available in Pythons 2.6, 3.0, and later: >>>>> L = list(S) # Expand to a list: [...]>>> L['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y'] >>> L[1] = 'c' # Change it in place>>> ''.join(L) # Join with empty delimiter'scrubbery' >>> B = bytearray(b'spam') # A bytes/list hybrid (ahead)>>> B.extend(b'eggs') # 'b' needed in 3.X, not 2.X>>> B # B[i] = ord(x) works here toobytearray(b'spameggs') >>> B.decode() # Translate to normal string'spameggs' The bytearray supports in-place changes for text, but only for text whose characters are all at most 8-bits wide (e.g., ASCII). All other strings are still immutable— byte array is a distinct hybrid of immutable bytes strings (whose b'...' syntax is required in 3.X and optional in 2.X) and mutable lists (coded and displayed in []), and we have to learn more about both these and Unicode text to fully grasp this code. Every string operation we’ve studied so far is really a sequence operation—that is, these operations will work on other sequences in Python as well, including lists and tuples. In addition to generic sequence operations, though, strings also have operations all their own, available as methods—functions that are attached to and act upon a specific object, which are triggered with a call expression. For example, the string find method is the basic substring search operation (it returns the offset of the passed-in substring, or −1 if it is not present), and the string replace method performs global searches and replacements; both act on the subject that they are attached to and called from: >>>>> S.find('pa') # Find the offset of a substring in S1 >>> S'Spam' >>> S.replace('pa', 'XYZ') # Replace occurrences of a string in S with another'SXYZm' >>> S'Spam' Again, despite the names of these string methods, we are not changing the original strings here, but creating new strings as the results—because strings are immutable, this is the only way this can work..rstrip() # Remove whitespace characters on the right side'aaa,bbb,ccccc,dd' >>> line.rstrip().split(',') # Combine two operations['aaa', 'bbb', 'ccccc', 'dd'] Notice the last command here—it strips before it splits because Python runs from left to right, making a temporary result along the way. Strings also support an advanced substitution operation known as formatting, available as both an expression (the original) and a string method call (new as of 2.6 and 3.0); the second of these allows you to omit relative argument value numbers as of 2.7 and 3.1: >>> '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting expression (all)'spam, eggs, and SPAM!' >>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting method (2.6+, 3.0+)'spam, eggs, and SPAM!' >>> '{}, eggs, and {}'.format('spam', 'SPAM!') # Numbers optional (2.7+, 3.1+)'spam, eggs, and SPAM!' Formatting is rich with features, which we’ll postpone discussing until later in this book, and which tend to matter most when you must generate numeric reports: >>> '{:,.2f}'.format(296999.2567) # Separators, decimal digits'296,999.26' >>> '%.2f | %+05d' % (3.14159, −42) # Digits, padding, signs'3.14 | −0042' One note here: although sequence operations are generic, methods are not—although some types share some method names, string method operations generally. The methods introduced in the prior section are a representative, but small, sample of what is available for string objects. In general, this book is not exhaustive in its look at object methods. For more details, you can always call the built-in dir function. This function lists variables assigned in the caller’s scope when called with no argument; more usefully, it returns a list of all the attributes available for any object passed to it. Because methods are function attributes, they will show up in this list. Assuming S is still the string, here are its attributes on Python 3.3 (Python 2.X varies slightly): >>> dir(S)['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', '] You probably won’t care about the names with double underscores in this list until later in the book, when we study operator overloading in classes—they represent the implementation of the string object and are available to support customization. The __add__ method of strings, for example, is what really performs concatenation; Python maps the first of the following to the second internally, though you shouldn’t usually use the second form yourself (it’s less intuitive, and might even run slower): >>> S + 'NI!''spamNI!' >>> S.__add__('NI!')'spamNI!' a handful of interfaces to a system of code that ships with Python known as PyDoc—a tool for extracting documentation from objects. Later in the book, you’ll see that PyDoc can also render its reports in HTML format for display on a web browser. You can also ask for help on an entire string (e.g., help(S)), but you may get more or less help than you want to see—information about every string method in older Pythons, and probably no help at all in newer versions because strings are treated specially. It’s generally better to ask about a specific method. Both dir and help also accept as arguments either a real object (like our string S), or the name of a data type (like str, list, and dict). The latter form returns the same list for dir but shows full type details for help, and allows you to ask about a specific method via type name (e.g., help on str.replace). For more details, you can also consult Python’s standard library reference manual or commercially published reference books, but dir and help are the first level of documentation in Python. So far, we’ve looked at the string object’s sequence operations and type-specific methods. Python also provides a variety of ways for us to code strings, which we’ll explore in greater depth later. For instance, special characters can be represented as backslash escape sequences, which Python displays in \xNN hexadecimal escape notation, unless they represent printable characters: >>> S = 'A\nB\tC' # \n is end-of-line, \t is tab>>> len(S) # Each stands for just one character5 >>> ord('\n') # \n is one character coded as decimal value 1010 >>> S = 'A\0B\0C' # \0, a binary zero byte, does not terminate string>>> len(S)5 >>> S # Non-printables are displayed as \xNN hex escapes'A\x00B\x00C' Python allows strings to be enclosed in single or double quote characters—they mean the same thing but allow the other type of quote to be embedded without an escape (most programmers prefer single quotes). It also allows multiline string literals enclosed in triple quotes (single or double)—when this form is used, all the lines are concatenated together, and end-of-line characters are added where line breaks appear. This is a minor syntactic convenience, but it’s useful for embedding things like multiline HTML, XML, or JSON code in a Python script, and stubbing out lines of code temporarily—just add three quotes above and below: >>>\n' Python also supports a raw string literal that turns off the backslash escape mechanism. Such literals start with the letter r and are useful for strings like directory paths on Windows (e.g., r'C:\text\new'). Python’s strings also come with full Unicode support required for processing text in internationalized character sets. Characters in the Japanese and Russian alphabets, for example, are outside the ASCII set. Such non-ASCII text can show up in web pages, emails, GUIs, JSON, XML, or elsewhere. When it does, handling it well requires Unicode support. Python has such support built in, but the form of its Unicode support varies per Python line, and is one of their most prominent differences. In Python 3.X, the normal str string handles Unicode text (including ASCII, which is just a simple kind of Unicode); a distinct bytes string type represents raw byte values (including media and encoded text); and 2.X Unicode literals are supported in 3.3 and later for 2.X compatibility (they are treated the same as normal 3.X str strings): >>> 'sp\xc4m' # 3.X: normal str strings are Unicode text'spÄm' >>> b'a\x01c' # bytes strings are byte-based datab'a\x01c' >>> u'sp\u00c4m' # The 2.X Unicode literal works in 3.3+: just str'spÄm' In Python 2.X, the normal str string handles both 8-bit character strings (including ASCII text) and raw byte values; a distinct unicode string type represents Unicode text; and 3.X bytes literals are supported in 2.6 and later for 3.X compatibility (they are treated the same as normal 2.X str strings): >>> print u'sp\xc4m' # 2.X: Unicode strings are a distinct typespÄm >>> 'a\x01c' # Normal str strings contain byte-based text/data'a\x01c' >>> b'a\x01c' # The 3.X bytes literal works in 2.6+: just str'a\x01c' Formally, in both 2.X and 3.X, non-Unicode strings are sequences of 8-bit bytes that print with ASCII characters when possible, and Unicode strings are sequences of Unicode code points—identifying numbers for characters, which do not necessarily map to single bytes when encoded to files or stored in memory. In fact, the notion of bytes doesn’t apply to Unicode: some encodings include character code points too large for a byte, and even simple 7-bit ASCII text is not stored one byte per character under some encodings and memory storage schemes: >>> 'spam' # Characters may be 1, 2, or 4 bytes in memory'spam' >>> 'spam'.encode('utf8') # Encoded to 4 bytes in UTF-8 in filesb'spam' >>> 'spam'.encode('utf16') # But encoded to 10 bytes in UTF-16b'\xff\xfes\x00p\x00a\x00m\x00' Both 3.X and 2.X also support the bytearray string type we met earlier, which is essentially a bytes string (a str in 2.X) that supports most of the list object’s in-place mutable change operations. Both 3.X and 2.X also support coding non-ASCII characters with \x hexadecimal and short \u and long \U Unicode escapes, as well as file-wide encodings declared in program source files. Here’s our non-ASCII character coded three ways in 3.X (add a leading “u” and say “print” to see the same in 2.X): >>> 'sp\xc4\u00c4\U000000c4m''spÄÄÄm' What these values mean and how they are used differs between text strings, which are the normal string in 3.X and Unicode in 2.X, and byte strings, which are bytes in 3.X and the normal string in 2.X. All these escapes can be used to embed actual Unicode code-point ordinal-value integers in text strings. By contrast, byte strings use only \x hexadecimal escapes to embed the encoded form of text, not its decoded code point values—encoded bytes are the same as code points, only for some encodings and characters: >>> '\u00A3', '\u00A3'.encode('latin1'), b'\xA3'.decode('latin1')('£', b'\xa3', '£') As a notable difference, Python 2.X allows its normal and Unicode strings to be mixed in expressions as long as the normal string is all ASCII; in contrast, Python 3.X has a tighter model that never allows its normal and byte strings to mix without explicit conversion: u'x' + b'y' # Works in 2.X (where b is optional and ignored)u'x' + 'y' # Works in 2.X: u'xy'u'x' + b'y' # Fails in 3.3 (where u is optional and ignored)u'x' + 'y' # Works in 3.3: 'xy''x' + b'y'.decode() # Works in 3.X if decode bytes to str: 'xy''x'.encode() + b'y' # Works in 3.X if encode str to bytes: b'xy' Apart from these string types, Unicode processing mostly reduces to transferring text data to and from files—text is encoded to bytes when stored in a file, and decoded into characters (a.k.a. code points) when read back into memory. Once it is loaded, we usually process text as strings in decoded form only. Because of this model, though, files are also content-specific in 3.X: text files implement named encodings and accept and return str strings, but binary files instead deal in bytes strings for raw binary data. In Python 2.X, normal files’ content is str bytes, and a special codecs module handles Unicode and represents content with the unicode type. We’ll meet Unicode again in the files coverage later in this chapter, but save the rest of the Unicode story for later in this book. It crops up briefly in a Chapter 25 example in conjunction with currency symbols, but for the most part is postponed until this book’s advanced topics part. Unicode is crucial in some domains, but many programmers can get by with just a passing acquaintance. If your data is all ASCII text, the string and file stories are largely the same in 2.X and 3.X. And if you’re new to programming, you can safely defer most Unicode details until you’ve mastered string basics. One point worth noting before we move on is that none of the string object’s own a substring is found, portions of the substring matched by parts of the pattern enclosed in parentheses are available as groups. The following pattern, for example, picks out three groups separated by slashes or colons, and is similar to splitting by an alternatives pattern: >>> match = re.match('[/:](.*)[/:](.*)[/:](.*)', '/usr/home:lumberjack')>>> match.groups()('usr', 'home', 'lumberjack') >>> re.split('[/:]', '/usr/home/lumberjack')['', 'usr', 'home', 'lumberjack'] Pattern matching is an advanced text-processing tool by itself, but there is also support in Python for even more advanced text and language processing, including XML and HTML parsing and natural language analysis. We’ll see additional brief examples of patterns and XML parsing at the end of Chapter 37, but I’ve already said enough about strings for this tutorial, so let’s move on to the next type.. Accordingly, they provide a very flexible tool for representing arbitrary collections—lists of files in a folder, employees in a company, emails in your inbox, and so on. Because they are sequences, lists support all the sequence operations we discussed for strings; the only difference is that the results are usually lists instead of strings. For instance, given a three-item list: >>> L = [123, 'spam', 1.23] # A list of three different-type objects>>> len(L) # Number of items in the list3 we can index, slice, and so on, just as for strings: >>> L[0] # Indexing by position123 >>> L[:-1] # Slicing a list returns a new list[123, 'spam'] >>> L + [4, 5, 6] # Concat/repeat make new lists too[123, 'spam', 1.23, 4, 5, 6] >>> L * 2[123, 'spam', 1.23, 123, 'spam', 1.23] >>> L # We're not changing the original list[123, 'spam', 1.23] Python’s lists may be reminiscent1 an item at an arbitrary position ( insert), remove a given item by value ( remove), add multiple items at the end ( extend), intentional, (you’ll get “...” continuation-line prompts on lines 2 and 3 of the following in some interfaces, but not in IDLE): >>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists [4, 5, 6], # Code can span lines if bracketed 6 The first operation here fetches the entire second row, and the second grabs the third item within that row (it runs left to right, like the earlier string strip and split). Stringing together index operations takes us deeper and deeper into our nested-object structure.3 they can be used to iterate over any iterable object—a term we’ll flesh out later in this preview. Here, for instance, we'] These expressions can also be used to collect multiple values, as long as we wrap those values in a nested collection. The following illustrates using range—a built-in that generates successive integers, and requires a surrounding list to display all its values in 3.X only (2.X makes a physical list all at once): >>> list(range(4)) # 0..3 (list() required in 3.X) [0, 1, 2, 3] >>> list(range(−6, 7, 2)) # −6 to +6 by 2 (need list() in 3.X) [−6, −4, −2, 0, 2, 4, 6] >>> [[x ** 2, x ** 3] for x in range(4)] # Multiple values, "if" filters[[0, 0], [1, 1], [4, 8], [9, 27]] >>> [[x, x / 2, x * 2] for x in range(−6, 7, 2) if x > 0][[2, 1, 4], [4, 2, 8], [6, 3, 12]] As you can probably tell, list comprehensions, and relatives like the map and filter built-in functions, are too involved to cover more formally in this preview chapter. The main point of this brief introduction is to illustrate that Python includes both simple and advanced tools in its arsenal. List comprehensions are an optional feature, but they tend to be very useful in practice and often provide a substantial processing speed advantage. They also work on any type that is a sequence in Python, as well as some types that are not. You’ll hear much more about them later in this book. As a preview, though, you’ll find that in recent Pythons, comprehension syntax has been generalized for other roles: it’s not just for making lists today. For example, enclosing a comprehension in parentheses can also be used to create generators that produce results on demand. To illustrate, the sum built-in sums items in a sequence—in this example, summing all items in our matrix’s rows on request: >>> G = (sum(row) for row in M) # Create a generator of row sums>>> next(G) # iter(G) not required here6 >>> next(G) # Run the iteration protocol next()15 >>> next(G)24 The map built-in can do similar work, by generating the results of running items through a function, one at a time and on request. Like range, wrapping it in list forces it to return all its values in Python 3.X; this isn’t needed in 2.X where map makes a list of results all at once instead, and is not needed in other contexts that iterate automatically, unless multiple scans or list-like behavior is also required: >>> list(map(sum, M)) # Map sum over items in M[6, 15, 24] In Python 2.7 and 3.X, comprehension syntax can also be used to create sets and dictionaries: >>> {sum(row) for row in M} # Create a set of row sums{24, 6, 15} >>> {i : sum(M[i]) for i in range(3)} # Creates key/value table of row sums{0: 6, 1: 15, 2: 24} In fact, lists, sets, dictionaries, and generators can all be built with comprehensions in 3.X and 2.7: >>> [ord(x) for x in 'spaam'] # List of character ordinals[115, 112, 97, 97, 109] >>> {ord(x) for x in 'spaam'} # Sets remove duplicates{112, 97, 115, 109} >>> {x: ord(x) for x in 'spaam'} # Dictionary keys are unique{'p': 112, 'a': 97, 's': 115, 'm': 109} >>> (ord(x) for x in 'spaam') # Generator of values<generator object <genexpr> at 0x000000000254DAB0> To understand objects like generators, sets, and dictionaries, though, we must move ahead.: like lists, they may be changed in place and can grow and shrink on demand. Also like lists, they are a flexible tool for representing collections, but their more mnemonic keys are better suited when a collection’s items are named or labeled—fields of a database record, for example.,” perhaps the details of a hypothetical menu item?): >>>{'color': 'pink', 'food': 'Spam', 'quantity': 5} Although the curly-braces literal form does see use, it is perhaps more common to see dictionaries built up in different ways (it’s rare to know all your program’s data before your program runs). The following code, for example, starts with an empty dictionary and fills it out one key at a time. Unlike out-of-bounds assignments in lists, which are forbidden, assignments to new dictionary keys create those keys: >>>. As we’ll learn later, we can also make dictionaries by passing to the dict type name either keyword arguments (a special name = value syntax in function calls), or the result of zipping together sequences of keys and values obtained at runtime (e.g., from files). Both the following make the same dictionary as the prior example and its equivalent {} literal form, though the first tends to make for less typing: >>> bob1 = dict(name='Bob', job='dev', age=40) # Keywords>>> bob1{'age': 40, 'name': 'Bob', 'job': 'dev'} >>> bob2 = dict(zip(['name', 'job', 'age'], ['Bob', 'dev', 40])) # Zipping>>> bob2{'job': 'dev', 'name': 'Bob', 'age': 40} Notice how the left-to-right order of dictionary keys is scrambled. Mappings are not positionally ordered, so unless you’re lucky, they’ll come back in a different order than you typed them. The exact order may vary per Python, but you shouldn’t depend on it, and shouldn’t expect yours to match that in this book.'}, 'jobs': ['dev', 'mgr'], 'age': 40.5} Here, we again have a three-key dictionary at the top (keys “name,” “jobs,” and “age”), but the values have become more complex: a nested dictionary for the name to support multiple parts, and a nested list for the jobs to support multiple roles and future expansion. We can access the components of this structure much as we did for our list-based matrix earlier, but this time most indexes are dictionary keys, not list offsets: >>> rec['name'] # 'name' is a nested dictionary{'last': 'Smith', 'first': 'Bob'} >>> rec['name']['last'] # Index the nested dictionary'Smith' >>> rec['jobs'] # 'jobs' is a nested list['dev', 'mgr'] >>> rec['jobs'][-1] # Index the nested list'mgr' >>> rec['jobs'].append('janitor') # Expand Bob's job description in place>>> rec{'age': 40.5, 'jobs': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}} Notice how the last operation here expands the nested jobs list—because the jobs standard Python (a.k.a. CPython), the space is reclaimed immediately, as soon as the last reference to an object is removed. We’ll study how this works later in Chapter 6; for now, it’s enough to know that you can use objects freely, without worrying about creating their space or cleaning up as you go. Also watch for a record structure similar to the one we just coded in Chapter 8, Chapter 9, and Chapter 27, where we’ll use it to compare and contrast lists, dictionaries, tuples, named tuples, and classes—an array of data structure options with tradeoffs we’ll cover in full later.4 As mappings, dictionaries support accessing items by key only, with the sorts of operations we’ve just seen. In addition, though, they also support type-specific operations with method calls that are useful in a variety of common use cases. For example, although we can assign to a new key to expand a dictionary, fetching a nonexistent key is still a mistake: >>> D = {'a': 1, 'b': 2, 'c': 3}>>> D{'a': 1, 'c': 3, 'b': 2} >>> D['e'] = 99 # Assigning new keys grows dictionaries>>> D{'a': 1, 'c': 3, 'b': 2, 'e': 99} >>> D['f'] # Referencing a nonexistent key errors? One solution is to test ahead of time. The dictionary in membership expression allows us to query the existence of a key and branch on the result with a Python if statement. In the following, be sure to press Enter twice to run the if interactively after typing its code (as explained in Chapter 3, an empty line means “go” at the interactive prompt), and just as for the earlier multiline dictionaries and lists, the prompt changes to “...” on some interfaces for lines two and beyond: >>> 'f' in DFalse >>> if not 'f' in D: # Python's sole selection statement print('missing')missing This book has more to say about the if statement in later chapters, statement tool in Python; along with both its ternary if/ else expression cousin (which we’ll meet in a moment) and the if comprehension filter lookalike we saw earlier, it’s the way we code the logic of choices and decisions in our scripts. If you’ve used some other programming languages in the past, you might be wondering how Python knows when the if statement ends. I’ll explain Python’s syntax rules in depth in later chapters, but in short, if you have more than one action to run in a statement block, you simply indent all their statements the same way—this both promotes readable code and reduces the number of characters you have to type: >>> if not 'f' in D: print('missing') print('no, really...') # Statement blocks are indentedmissing no, really... Besides the in test, there are a variety of ways to avoid accessing nonexistent keys in the dictionaries we create: the get method, a conditional index with a default; the Python 2.X has_key method, an in work-alike that is no longer available in 3.X; the try statement, a tool we’ll first meet in Chapter 10 that catches and recovers from exceptions altogether; and the if/ else ternary (three-part) expression, which is essentially an if statement squeezed onto a single line. Here are a few examples: >>> value = D.get('x', 0) # Index but with a default>>> value0 >>> value = D['x'] if 'x' in D else 0 # if/else expression form>>> value0 We’ll save the details on such alternatives until a later chapter. For now, let’s turn to another dictionary method’s role in a common use case. As mentioned earlier, because dictionaries are not sequences, they don’t maintain any dependable left-to-right order. If we make a dictionary and print it back, its keys may come back in a different order than that in which we typed them, and may vary per Python version and other variables: >>> (as for if, be sure to press the Enter key twice after coding the following for loop, and omit the outer parenthesis in the >>> Ks = list(D.keys()) # Unordered keys list>>> Ks # A list in 2.X, "view" in 3.X: use list()['a', 'c', 'b'] >>> Ks.sort() # Sorted keys list>>> Ks['a', 'b', 'c'] >>> for key in Ks: # Iterate though sorted keys print(key, '=>', D[key]) # <== press Enter twice here (3.X print)a => 1 b => 2 c => 3 This is a three-step process, although, as we’ll see in later chapters, in recent versions of Python it can be done in one step with the newer sorted built-in function. The sorted call returns the result and sorts a variety of object types, in this case sorting dictionary keys automatically: >>> D{'a': 1, 'c': 3, 'b': 2} >>> for key in sorted(D): print(key, '=>', D[key])a => 1 b => 2 c => 3 Besides showcasing dictionaries, this use case serves colleague the while loop, are the main ways we code repetitive tasks as statements in our scripts. Really, though, the for loop, like its relative the list comprehension introduced earlier, is a sequence operation. It works on any object that is a sequence and, like the list comprehension, even on some things that are not. Here, for example, it is stepping across the characters in a string, printing the uppercase version of each as it goes: >>> for c in 'spam': print(c.upper())S P A M Python’s while loop is a more general sort of looping tool; it’s not limited to stepping across sequences, but generally requires more code to do so: >>> x = 4>>> while x > 0: print('spam!' * x) x -= 1spam!spam!spam!spam! spam!spam!spam! spam!spam! spam! We’ll discuss looping statements, syntax, and tools in depth later in the book. First, though, I need to confess that this section has not been as forthcoming as it might have been. Really, the for loop, and all its cohorts that step through objects from left to right, are not just sequence operations, they are iterable operations—as the next section describes. If the last section’s for loop looks like the list comprehension expression introduced earlier, it should: both are really general iteration tools. In fact, both will work on any iterable object that follows the iteration protocol—pervasive ideas in Python that underlie all its iteration tools. In a nutshell, an object is iterable if it is either a physically stored sequence in memory, or an object that generates one item at a time in the context of an iteration operation—a sort of “virtual” sequence. More formally, both types of objects are considered iterable because they support the iteration protocol—they respond to the iter call with an object that advances in response to next calls and raises an exception when finished producing values. The generator comprehension expression we saw earlier is such an object: its values aren’t stored in memory all at once, but are produced as requested, usually by iteration tools. Python file objects similarly iterate line by line when used by an iteration tool: file content isn’t in a list, it’s fetched on demand. Both are iterable objects in Python—a category that expands in 3.X to include core tools like range and map. By deferring results as needed, these tools can both save memory and minimize delays. I’ll have more to say about the iteration protocol later in this book. For now, keep in mind that every Python tool that scans an object from left to right uses the iteration protocol. This is why the sorted call used in the prior section works on the dictionary directly—we don’t have to call the keys method to get a sequence because dictionaries are iterable objects, with a next that returns successive keys. It may also help you to see comprehension does squares.append(x ** 2) # Both run the iteration protocol internally>>> squares[1, 4, 9, 16, 25] Both tools leverage the iteration protocol internally and produce the same result. The list comprehension, though, and related functional programming tools like map and filter, will often run faster than a for loop today on some types of code (perhaps even twice as fast)—a property that could matter in your programs for large data sets. Having said that, though, I should point out that performance measures are tricky business in Python because it optimizes so much, and they may for timing the speed of alternatives, and the profile module for isolating bottlenecks. You’ll find more on these later in this book (see especially Chapter 21’s benchmarking case study) and in the Python manuals. For the sake of this preview, let’s move ahead to the next core data type. The tuple object (pronounced “toople” or “tuhple,” depending on whom you ask) is roughly like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like strings. Functionally, they’re used to represent fixed collections of items: the components of a specific calendar date, for instance. Syntactically, they are normally coded in parentheses instead of square brackets, and they support arbitrary types, arbitrary nesting, and the usual sequence operations: >>> T = (1, 2, 3, 4) # A 4-item tuple>>> len(T) # Length4 >> T + (5, 6) # Concatenation(1, 2, 3, 4, 5, 6) >>> T[0] # Indexing, slicing, and more1 Tuples also have type-specific callable methods as of Python 2.6 and 3.0, but not nearly as many as lists: >>> T.index(4) # Tuple methods: 4 appears at offset 33 >>> T.count(4) # 4 appears once1 The primary distinction for tuples is that they cannot be changed once created. That is, they are immutable sequences (one-item tuples like the one here require a trailing comma): >>> T[0] = 2 # Tuples are immutable ...error text omitted...TypeError: 'tuple' object does not support item assignment >>> T = (2,) + T[1:] # Make a new tuple for a new value>>> T(2, 2, 3, 4)): >>> T = 'spam', 3.0, [11, 22, 33]>>> T[1]3.0 >>> T[2][1]22 >>> T.append(4)AttributeError: 'tuple' object has no attribute 'append'’ll write here. We’ll talk more about tuples later in the book, including an extension that builds upon them called named tuples. For now, though, let’s jump ahead to our last major core type: the file. File objects are Python code’s main interface to external files on your computer. They can be used to read and write text memos, audio clips, Excel documents, saved email messages, and whatever else you happen to have stored on your machine. Files are a core type, but they’re something of an oddball—there is no specific literal syntax for creating them. Rather, to create a file object, you call the built-in open function, passing in an external filename and an optional processing mode as strings. For example, to create a text output file, you would pass in its name and the 'w' processing mode string to write data: >>> f = open('data.txt', 'w') # Make a new file in output mode ('w' is write)>>> f.write('Hello\n') # Write strings of characters to it 6>>> f.write('world\n') # Return number of items written in Python 3.X text input—this is the default if you omit the mode in the call. Then read the file’s content into a string, and display it. A file’s contents are always a string in your script, regardless of the type of data the file contains: >>> f = open('data.txt') # 'r' (read) is the default processing mode>>> text = f.read() # Read entire file into a string>>> text'Hello\nworld\n' >>> print(text) # print interprets control charactersHello world >>> text.split() # File content is always a string['Hello', 'world'] Other file object methods support additional features we don’t have time to cover here. For instance, file objects provide more ways of reading and writing ( read accepts an optional maximum byte/character size, readline reads one line at a time, and so on), as well as other tools ( seek moves to a new file position). As we’ll see later, though, the best way to read a file today is to not read it at all—files provide an iterator that automatically reads line by line in for loops and other contexts: >>> for line in open('data.txt'): print(line) We’ll meet the full set of file methods later in this book, but if you want a quick preview now, run a dir call on any open file and a help on any of the method names that come back: >>> dir(f)[ ...many names omitted...'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines'] >>> help(f.seek) ...try it and see... The prior section’s examples illustrate file basics that suffice for many roles. Technically, though, they rely on either the platform’s Unicode encoding default in Python 3.X, or the 8-bit byte nature of files in Python 2.X. Text files always encode strings in 3.X, and blindly write string content in 2.X. This is irrelevant for the simple ASCII data used previously, which maps to and from file bytes unchanged. But for richer types of data, file interfaces can vary depending on both content and the Python line you use. As hinted when we met strings earlier, Python 3.X draws a sharp distinction between text and binary data in files: text files represent content as normal str strings and perform Unicode encoding and decoding automatically when writing and reading data, while binary files represent content as a special bytes string and allow you to access file content unaltered. Python 2.X supports the same dichotomy, but doesn’t impose it as rigidly, and its tools differ. For example, binary files are useful for processing media, accessing data created by C programs, and so on. To illustrate, Python’s struct module can both create and unpack packed binary data—raw bytes that record values that are not Python objects—to be written to a file in binary mode. We’ll study this technique in detail later in the book, but the concept is simple: the following creates a binary file in Python 3.X (binary files work the same in 2.X, but the “b” string literal prefix isn’t required and won’t be displayed): >>> import struct>>> packed = struct.pack('>i4sh', 7, b'spam', 8) # Create packed binary data>>> packed # 10 bytes, not objects or textb'\x00\x00\x00\x07spam\x00\x08' >>> >>> file = open('data.bin', 'wb') # Open binary output file>>> file.write(packed) # Write packed binary data10 >>> file.close() Reading binary data back is essentially symmetric; not all programs need to tread so deeply into the low-level realm of bytes, but binary files make this easy in Python: >>> data = open('data.bin', 'rb').read() # Open/read binary data file>>> data # 10 bytes, unalteredb'\x00\x00\x00\x07spam\x00\x08' >>> data[4:8] # Slice bytes in the middleb'spam' >>> list(data) # A sequence of 8-bit bytes[0, 0, 0, 7, 115, 112, 97, 109, 0, 8] >>> struct.unpack('>i4sh', data) # Unpack into objects again(7, b'spam', 8) Text files are used to process all sorts of text-based data, from memos to email content to JSON and XML documents. In today’s broader interconnected world, though, we can’t really talk about text without also asking “what kind?”—you must also know the text’s Unicode encoding type if either it differs from your platform’s default, or you can’t rely on that default for data portability reasons. Luckily, this is easier than it may sound. To access files containing non-ASCII Unicode text of the sort introduced earlier in this chapter, we simply pass in an encoding name if the text in the file doesn’t match the default encoding for our platform. In this mode, Python text files automatically encode on writes and decode on reads per the encoding scheme name you provide. In Python 3.X: >>> S = 'sp\xc4m' # Non-ASCII Unicode text>>> S'spÄm' >>> S[2] # Sequence of characters'Ä' >>> file = open('unidata.txt', 'w', encoding='utf-8') # Write/encode UTF-8 text>>> file.write(S) # 4 characters written4 >>> file.close()>>> text = open('unidata.txt', encoding='utf-8').read() # Read/decode UTF-8 text>>> text'spÄm' >>> len(text) # 4 chars (code points)4 This automatic encoding and decoding is what you normally want. Because files handle this on transfers, you may process text in memory as a simple string of characters without concern for its Unicode-encoded origins. If needed, though, you can also see what’s truly stored in your file by stepping into binary mode: >>> raw = open('unidata.txt', 'rb').read() # Read raw encoded bytes>>> rawb'sp\xc3\x84m' >>> len(raw) # Really 5 bytes in UTF-85 You can also encode and decode manually if you get Unicode data from a source other than a file—parsed from an email message or fetched over a network connection, for example: >>> text.encode('utf-8') # Manual encode to bytesb'sp\xc3\x84m' >>> raw.decode('utf-8') # Manual decode to str'spÄm' This is also useful to see how text files would automatically encode the same string differently under different encoding names, and provides a way to translate data to different encodings—it’s different bytes in files, but decodes to the same string in memory if you provide the proper encoding name: >>> text.encode('latin-1') # Bytes differ in othersb'sp\xc4m' >>> text.encode('utf-16')b'\xff\xfes\x00p\x00\xc4\x00m\x00' >>> len(text.encode('latin-1')), len(text.encode('utf-16'))(4, 10) >>> b'\xff\xfes\x00p\x00\xc4\x00m\x00'.decode('utf-16') # But same string decoded'spÄm' This all works more or less the same in Python 2.X, but Unicode strings are coded and display with a leading “u,” byte strings don’t require or show a leading “b,” and Unicode text files must be opened with codecs.open, which accepts an encoding name just like 3.X’s open, and uses the special unicode string to represent content in memory. Binary file mode may seem optional in 2.X since normal files are just byte-based data, but it’s required to avoid changing line ends if present (more on this later in the book): >>> import codecs>>> codecs.open('unidata.txt', encoding='utf8').read() # 2.X: read/decode textu'sp\xc4m' >>> open('unidata.txt', 'rb').read() # 2.X: read raw bytes'sp\xc3\x84m' >>> open('unidata.txt').read() # 2.X: raw/undecoded too'sp\xc3\x84m' Although you won’t generally need to care about this distinction if you deal only with ASCII text, Python’s strings and files are an asset if you deal with either binary data (which includes most types of media) or text in internationalized character sets (which includes most content on the Web and Internet at large today). Python also supports non-ASCII file names (not just content), but it’s largely automatic; tools such as walkers and listers offer more control when needed, though we’ll defer further details until Chapter 37. The open function is the workhorse for most file processing you will do in Python. For more advanced tasks, though, Python comes with additional file-like tools: pipes, FIFOs, sockets, keyed-access files, persistent object shelves,. Beyond the core types we’ve seen so far, there are others that may or may not qualify for membership in the category, depending on how broadly it is defined. Sets, for example, are a recent addition to the language that are neither mappings nor sequences; rather, they are unordered collections of unique and immutable objects. You create sets by calling the built-in set function or using new set literals and expressions in 3.X and 2.7, and they support the usual mathematical set operations (the choice of new {...} syntax for set literals makes sense, since sets are much like the keys of a valueless dictionary): >>> X = set('spam') # Make a set out of a sequence in 2.X and 3.X>>> Y = {'h', 'a', 'm'} # Make a set with set literals in 3.X and 2.7>>> X, Y # A tuple of two sets without parentheses({'m', 'a', 'p', 's'}, {'m', 'a', 'h'}) >>> X & Y # Intersection{'m', 'a'} >>> X | Y # Union{'m', 'h', 'a', 'p', 's'} >>> X - Y # Difference{'p', 's'} >>> X > Y # SupersetFalse >>> {n ** 2 for n in [1, 2, 3, 4]} # Set comprehensions in 3.X and 2.7{16, 1, 4, 9} Even less mathematically inclined programmers often find sets useful for common tasks such as filtering out duplicates, isolating differences, and performing order-neutral equality tests without sorting—in lists, strings, and all other iterable objects: >>> list(set([1, 2, 1, 3, 1])) # Filtering out duplicates (possibly reordered)[1, 2, 3] >>> set('spam') - set('ham') # Finding differences in collections{'p', 's'} >>> set('spam') == set('asmp') # Order-neutral equality ('spam'=='asmp' False)True Sets also support in membership tests, though all other collection types in Python do too: >>> 'p' in set('spam'), 'p' in 'spam', 'ham' in ['eggs', 'spam', 'ham'](True, True, True) In addition, Python recently grew a few new numeric types: decimal numbers, which are fixed-precision floating-point numbers, and fraction numbers, which are rational numbers with both a numerator and a denominator. Both can be used to work around the limitations and inherent inaccuracies of floating-point math: >>> 1 / 3 # Floating-point (add a .0 in Python 2.X)0.3333333333333333 >>> (2/3) + (1/2)1.1666666666666665 >>> import decimal # Decimals: fixed precision>>> d = decimal.Decimal('3.141')>>> d + 1Decimal('4.141') >>> decimal.getcontext().prec = 2>>> decimal.Decimal('1.00') / decimal.Decimal('3.00')Decimal('0.33') >>> from fractions import Fraction # Fractions: numerator+denominator>>> f = Fraction(2, 3)>>> f + 1Fraction(5, 3) >>> f + Fraction(1, 2)Fraction(7, 6) Python also comes with Booleans (with predefined True and False objects that are essentially just the integers 1 and 0 with custom display logic), and it has long supported a special placeholder object called None commonly used to initialize names and objects: >>> 1 > 2, 1 < 2 # Booleans(False, True) >>> bool('spam') # Object's Boolean valueTrue >>> X = None # None placeholder>>> print(X)None >>> L = [None] * 100 # Initialize a list of 100 Nones>>> L[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, ...a list of 100 Nones...] I’ll have more to say about all of Python’s object types later, but one merits special treatment here. The type object, returned by the type built-in function, is an object that gives the type of another object; its result differs slightly in 3.X, because types have merged with classes completely (something we’ll explore in the context of “new-style” classes in Part VI). Assuming L is still the list of the prior section: # In Python 2.X:>>> type(L) # Types: type of L is list type object<type 'list'> >>> type(type(L)) # Even types are objects<type 'type'> # In Python 3.X:>>> type(L) # 3.X: types are classes, and vice versa<class 'list'> >>> type(type(L)) # See Chapter 32 for more on class types<class 'type'> Besides allowing you to explore your objects interactively, the type object in its most practical application allows code to check the types of the objects it processes. am required by law to tell you that doing so is almost always the wrong thing to do in a Python program (and often a sign of an ex-C programmer first starting to use Python!). The reason why won’t become completely clear until later in the book, when we start writing larger code units such as functions, but it’s a (perhaps the) core Python concept.. That is, we care what an object does, not what it is.’s methods automatically receive the instance being processed by a given method call (in the self argument): >>> bob = Worker('Bob Smith', 50000) # Make two instances>>> sue = Worker('Sue Jones', 60000) # Each has name and pay attrs>>> consider this just a preview; for full disclosure on user-defined types coded with classes, you’ll have to read on. Because classes build upon other tools in Python, they are one of the major goals of this book’s journey. types in Python either are objects related to program execution (like functions, modules, classes, and compiled code), which we will study later, or are implemented by imported module functions, not language syntax. The latter of these. And that’s a wrap for our initial, such as immutability, sequences, and polymorphism. Along the way, we’ve seen that Python’s core object types are more flexible and powerful than what is available in lower-level languages such as C. For instance, Python’s. We’ve also seen that strings and files work hand in hand to support a rich variety of binary and text data. I’ve skipped most of the details here in order to provide a quick tour, so you shouldn’t expect all of this chapter to have made sense yet. In the next few chapters we’ll start to dig deeper, taking a second pass over Python’s core object types that will fill in details omitted here, and give you a deeper understanding. We’ll start off the next chapter with an in-depth look at Python numbers. First, though, here is another quiz to review.? Numbers, strings, lists, dictionaries, tuples, files, and sets are generally considered to be the core object (data) types. Types, None, and Booleans are sometimes classified this way as well. There are multiple number types (integer, floating point, complex, fraction, and decimal) and multiple string types (simple strings and Unicode strings in Python 2.X, and text strings and byte strings in Python 3.X). They are known as “core” types because they are part of the Python language itself and are always available; to create other objects, you generally must call functions in imported modules. Most of the core types have specific syntax for generating the objects: 'spam', for example, is an expression that makes a string and determines the set of operations that can be applied to it. Because of this, core types are hardwired into Python’s syntax. In contrast, you must call the built-in open function to create a file object (even though this is usually considered a core type too). An “immutable” object is an object that cannot be changed after it is created. Numbers, strings, and tuples in Python fall into this category. While you cannot change an immutable object in place, you can always make a new one by running an expression. Bytearrays in recent Pythons offer mutability for text, but they are not normal strings, and only apply directly to text if it’s a simple 8-bit kind (e.g., ASCII). A “sequence” is a positionally ordered collection of objects. Strings, lists, and tuples are all sequences in Python. They share common sequence operations, such as indexing, concatenation, and slicing, but also have type-specific method calls. A related term, “iterable,” means either a physical sequence, or a virtual one that produces its items on request.. 1 Pardon my formality. I’m a computer scientist. 2 in the section “Immutability”). 3 This matrix structure works for small-scale tasks, but for more serious number crunching you will probably want to use one of the numeric extensions to Python, such as the open source NumPy and SciPy systems., JPL, and many others use this tool for scientific and financial tasks. Search the Web for more details. 4 Two application notes here. First, as a preview, the rec record we just created really could be an actual database record, when we employ Python’s object persistence system—an easy way to store native Python objects in simple files or access-by-key databases, which translates objects to and from serial byte streams automatically. We won’t go into details here, but watch for coverage of Python’s pickle and shelve persistence modules in Chapter 9, Chapter 28, Chapter 31, and Chapter 37, where we’ll explore them in the context of files, an OOP use case, classes, and 3.X changes, respectively. Second, if you are familiar with JSON (JavaScript Object Notation)—an emerging data-interchange format used for databases and network transfers—this example may also look curiously similar, though Python’s support for variables, arbitrary expressions, and changes can make its data structures more general. Python’s json library module supports creating and parsing JSON text, but the translation to Python objects is often trivial. Watch for a JSON example that uses this record in Chapter 9 when we study files. For a larger use case, see MongoDB, which stores data using a language-neutral binary-encoded serialization of JSON-like documents, and its PyMongo interface. No credit card required
https://www.oreilly.com/library/view/learning-python-5th/9781449355722/ch04.html
CC-MAIN-2018-51
refinedweb
10,224
59.94
public class Date extends Object implements Cloneable, Comparable<Date> Daterepresents a specific instant in time, with millisecond precision. This class has been subset for Java ME based on the JDK 1.7 Date class. Many methods and variables have been pruned, and other methods simplified, in an effort to reduce the size of this class. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields.: Calendar Object clone() clonein class Object Cloneable long getTime() setTime(long) public int hashCode() getTime()method. That is, the hash code is the value of the expression: (int)(this.getTime()^. getTime() public String toString() Dateobject to a Stringof the form: where:where:dow mon dd hh:mm:ss zzz yyyy toStringin class Object Copyright (c) 2014, Oracle and/or its affiliates. All Rights Reserved. Use of this specification is subject to license terms.
http://docs.oracle.com/javame/config/cldc/opt-pkgs/api/cldc/api/java/util/Date.html
CC-MAIN-2014-15
refinedweb
146
67.55
Forum:Should VFS be abolished? From Uncyclopedia, the content-free encyclopedia I noticed on the VFS page this month that there's a sentiment that the system is more trouble than it's worth. It's led to numerous drama fests in the past (including the banning of PuppyOnTheRadio), and becoming an admin becomes an obsession for many. It leads to lobbying and votewhoring by people looking to secure an adminship. I'm normally for democratization, but in the case, perhaps we should have a meritocratic system similar to a typical discussion board. So, let's vote (irony): should VFS be abolished and replaced by something else entirely? If so, what? Saberwolf116 (talk) 19:59, July 3, 2012 (UTC) Vote! For. It seems to cause a lot more trouble than it's worth. Saberwolf116 (talk) 19:59, July 3, 2012 (UTC) Against. →A (Ruins) 20:23, 3 July 2012 Against. although reform would be nice. I've never thought it fair that admins had a greater say in VFS. And my campaigning to be admin a few years ago was a joke. --Hotadmin4u69 [TALK] 21:12 Jul 3 2012 Against. And I get two votes because I'm an admin (that was a joke, I actually think that aspect should be abolished). -- Sir Xam Ralco the Mediocre 21:19, July 3, 2012 (UTC) Against. Mattsnow 21:21, July 3, 2012 (UTC) - Against. There's no real debate about a consensus based system or the idea of having a VFS... just one that keeps the nepotism and lobbying to a minimum.--Sycamore (Talk) 22:05, July 3, 2012 (UTC) Against. While I agree VFS is a um... bad system to see the least, the idea of a RfA system would never work on Uncyclopedia because unlike wikipedia which receives close to 50 edits per minute you could have too many administrators. So unless it could be modified into some way that could make it work here I guess we'll have to make do with VFS. (Although totally impractical if we could somehow make a secret ballet, say by using some third party where all votes are submitted to that could gain absolutely nothing from altering the votes would be the ultimate solution to all vote whoring forever and ever amen) ~Sir Frosty (Talk to me!) 23:21, July 3, 2012 (UTC) - I've never really noticed a problem with "lobbying" unless you count, like, stating your reasons for voting for someone as lobbying. Which is a pretty big stretch. Anyway, no need to make things more complicated than they're worth. A little improvement at maybe reducing drama somehow would be nice, but that's definitely more our fault, not the system's. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 23:47, July 3, 2012 (UTC) - I don't think anybody wants to "abolish" VFS. The general sentiment is that the VFS system needs improvement. Perhaps we should be proposing improvements instead of voting about whether or not to scrap the whole system. -- Brigadier General Sir Zombiebaron 00:15, July 4, 2012 (UTC) Nah. —Sir Socky (talk) (stalk) GUN SotM UotM PMotM UotY PotM WotM 18:16, 4 July 2012 - Comment I don't think there is anything wrong with the process. I think that there has been issues with people, myself included. However we change process, we still have people involved, so I don't see how this will impact on that. Having said that, I'm happy to go with a democratic vote as to what system we have, but would suggest simplification is key. -- • Puppy's talk page • 02:47 07 Jul 02:47, July 7, 2012 (UTC) Against. I personally think there is nothing wrong with the current system and you have all convinced yourselves that drama will happen, when it only happens when you will it to happen. --MasterWangs CUNT and proud of it! 08:24, July 15, 2012 (UTC) Suggestions for replacement of VFS WP:RFA - it's simpler and if we chuck all their silly rules, it might even work here. ~ 01:34, 4 July 2012 Replace VFS with RFA (sans the silly rules)? For. Why not. Saberwolf116 (talk) 02:04, July 4, 2012 (UTC) - No. Not overhauling anything this drastically until a new standard is actually fully drafted out. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 02:38, July 4, 2012 (UTC) For.--fcukman LOOS3R! 02:50, July 4, 2012 (UTC) For. |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 10:24, July 4, 2012 (UTC) Per TKF ~Sir Frosty (Talk to me!) 02:54, July 4, 2012 (UTC) Against. Mattsnow 03:15, July 4, 2012 (UTC) Against. →A (Ruins) 15:29, 4 July 2012 Against. -- • Puppy's talk page • 12:40 11 Jul 00:40, July 11, 2012 (UTC) Could you all stop arbitrarily voting on everything? And, like, figure out what, specifically, needs fixing and then try to come up with things that might fix that instead? I suggest carefully discussing the matter in detail. ~ 07:29, 4 July 2012 Vote to stop voting on everything? - For. ~Sir Frosty (Talk to me!) 07:38, July 4, 2012 (UTC) - For. →A (Ruins) 15:29, 4 July 2012 - Forever and ever amen -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 16:29, July 4, 2012 (UTC) For. —Sir Socky (talk) (stalk) GUN SotM UotM PMotM UotY PotM WotM 18:17, 4 July 2012 - UltaMegaFor+20 -OptyC Sucks! CUN00:19, 11 Jul Against. -- • Puppy's talk page • 12:42 11 Jul 00:42, July 11, 2012 (UTC) Improvements (add any ideas) - Admins get 1 vote like everyone else. -- Sir Xam Ralco the Mediocre 00:17, July 4, 2012 (UTC) - I agree, if someone could explain to me why they are given x2 I'd stop being confused. ~Sir Frosty (Talk to me!) 00:26, July 4, 2012 (UTC) - Limit the amount a user can comment as they make their vote. Like limit them to two sentences worth of comment, if its any longer its ether really negative and probably not helpful or someone seriously has a boner for the candidate. ~Sir Frosty (Talk to me!) 00:26, July 4, 2012 (UTC) - How is that an improvement? Limiting the length of comments limits the ability of folks to explain themselves, which is particularly problematic with a system that actively discourages voters from examining candidates' contributions and the like - on the rare occasion someone does take the time to look, anything they find can be particularly pertinent to all involved in the discussion. ~ 01:32, 4 July 2012 - The long comments tend to lead to arguments and such which decreases efficiency and has also (although it may not be the intention of whoever wrote it) give the user it refers to the impression they are being bullied and picked on, which was the case with POTR and the comment you left you left last time. A 14 line critique of what they are doing wrong can instead of offering simple advice on how to improve themselves and make them a suitable candidate instead can leave the user feeling unwanted and unappreciated which leads to retaliation and poor decision making, admittedly your intensions may have been all well and good but a long list of reasons why it was a bad idea didn't help matters. But limited comment length is just my personal opinion as long winded comments don't help matters at all in my experience. ~Sir Frosty (Talk to me!) 02:06, July 4, 2012 (UTC) - I also think there's nothing wrong with explaining a vote, but when a person uses a vote as a platform for pettiness and bullying beyond the necessary boundaries, then again, that's on them and not the system. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 02:35, July 4, 2012 (UTC) - I don't think that was the intention but I'm fairly sure thats the way POTR took it as. As quoted from the forum he stated "I have now gotten to the point where I feel that I cannot contribute effectively here while she still remains as an admin, as her abuse of position and harassment and bullying of members based upon whim and favouritism is destroying the wiki." The VFS drama certainly was part of that. ~Sir Frosty (Talk to me!) 02:57, July 4, 2012 (UTC) - UR MOM IS SOOOO GHEY!!!!!! --fcukman LOOS3R! 03:13, July 4, 2012 (UTC) - The intention was to point out why he shouldn't be opped. I think it succeeded, although things did got a little out of hand. ~ 07:31, 4 July 2012 - The getting out of hand part is why I don't like long comments, because not everyone can just ignore it/take it on board. ~Sir Frosty (Talk to me!) 07:42, July 4, 2012 (UTC) - Yet the reason why POTR is no longer with us and why you are still here, despite Romartus's comment, is because you were able to take the criticisms (no matter how irrelevant) in stride, while he took them way too personally. Perhaps Lyrithya was being too harsh too, but again this is not the system's fault. If people are going to soapbox about other people, they will certainly find outlets other than VFS if that avenue has been deprived, too. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 15:10, July 4, 2012 (UTC) I had some ideas I had the idea of a simpler method here. While most seem to like having a lot of user involvement, it's not really led to outcomes that are agreeable. This isn't like a final draft - but it might offer some direction.--Sycamore (Talk) 10:03, July 5, 2012 (UTC) - I don't like the idea of user nominations being so discreet. Couldn't we instead allow users to "apply for adminship" like in RfA, and then allow the subsequent screening to take place? --Scofield & 1337 11:48, July 5, 2012 (UTC) - I like the idea of a secret nomination, but I would prefer a system where more than two admins do the voting. Maybe an instant runoff ballot on a private Google doc accessible, but anonymous to, all admins decides the top 3 candidates. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 14:35, July 9, 2012 (UTC) - This idea is something I knocked together just to maybe change direction a bit - ZB's idea that I've voted for below seem to strike a balance of everyones take, while I have an idea for VFS based on personal preference. I appreciate the concerns of Scofield and I like TKF's idea. My main reason to keep things so 'discreet' is that despite the bulk of good contributers, we simply cannot depend on some people here to be sensible and as one admin stated to me a while back, most of the powers that be and community at large are often 'too scared' of standing up to certain drama creating types (who have very surprisingly resurfaced with "Their Opinions").--Sycamore (Talk) 18:11, July 11, 2012 (UTC) - That's an odd opinion. The only thing that I'm aware of where users have chosen not to voice their perspective is when they have been told that doing so will earn them a ban. Having a look at almost every forum we have ever had, users who have opinions or perspectives have felt free to express them. -- • Puppy's talk page • 10:26 11 Jul 22:26, July 11, 2012 (UTC) - Well there are opinions and there's some very neurotic characters who'll mansplain to the entire community about 'their needs'. I think the community should be involved and have the opportunity to express their views, though the impression that individuals can aggressively lobby, whore or cajole the community onto their demands is unacceptable. 'Have your say, but like fuck off a bit' should be the new motto.--Sycamore (Talk) 08:52, July 12, 2012 (UTC) Drama We've had a nice three or four month period relatively drama free. It's been nice...hasn't it? Quiet. A nice PLS. A gentle roll-over of featured articles. Time floating by. Nice jokes bouncing around talk pages. Pleasant love filling up the whole wiki. It's lovely isn't it? That's why I've decided to name myself the new anti-wiki-terrorism agent. My new powers are to kidnap anyone who engages in wiki-terrorism, bring them to an abandoned parking lot, waterboard them until they admit to what they did, then dump them on the moon, naked, with a chocolate bar and a litre of petrol. I don't have any clue that wiki-terrorism is. It is so ill defined I could make anything seem like wiki-terrorism. For instance...Mattsnow forgot to capitalise a word. That is blatant wiki-terrorism...but I'll let him off this time because his fragile mind couldn't cope with my interrogation techniques. I love you all...and so I don't want to have to use the patriot act against any of you. But I will if it means preserving the freedom of freedom. --ShabiDOO 03:01, July 4, 2012 (UTC) - I just named myself as Osama Bin Laden and Hitler. My single goal in life is to spread hatred and destruction :3 →A (Ruins) 15:33, 4 July 2012 New system, Mr-ex777 selects new ops based on how "ghey" their mom is - You know I'm right ~Sir Frosty (Talk to me!) 03:41, July 4, 2012 (UTC) - For. I have never been in more support of anything in my entire life. -RAHB 03:43, July 4, 2012 (UTC) HELL FUCKING YES →A (Ruins) 15:34, 4 July 2012 - Antifor I'd lose. My mom isn't "ghey" : ( Cat the Colourful (Feed me!) Zzz 18:00, 4 July, 2012 (UTC) For. —Sir Socky (talk) (stalk) GUN SotM UotM PMotM UotY PotM WotM 18:18, 4 July 2012 - My mother is more gheyer than all of your mothers time a nillion! --ShabiDOO 22:38, July 4, 2012 (UTC) Just do what I suggested last year For. --Hotadmin4u69 [TALK] 02:52 Jul 5 2012 Switch who can vote for round 3 & 4 - My proposal is simple, currently users get the vote in round 3 and then the sysops take that result to vote in round 4 and eventually picks the new sysops. I propose we make round 3 (still with nominees selected by anybody) the sysop only round, anyone who is able to get x number of votes may proceed to round 4 where everyone gets 1 or 2 votes (depending on how many we want for that month). Now some of you ask, whats the point? We still have an admin only round and a user round. Will think of it this way. Currently its probably the most universally liked people that get past round 3 and into round 4 where its the best candidates that make it through. Essentially we get the most competent of the most popular elected, which isn't necessarily the best result. Reversing it will only allow the users that have the confidence of our administrators past round 3 and into round 4, where with a much shorter list of candidates users may vote more rationally and not just for their favorite user. ~Sir Frosty (Talk to me!) 10:49, July 5, 2012 (UTC) - To be frank the problem is not favoritism, it's characters such as yourself constantly bringing up the issue or whining about how the community has turned against because you were not the 'Sysop candidate you felt you were'. The issue it not so much the voting of sysops, it's devising a VFS where we don't have this behavior or detrimental activities. These are just horrible to be around, see reputations such as Puppy's destroyed and take us collectively away from comedy. --Sycamore (Talk) 11:16, July 5, 2012 (UTC) - BAHAHAHAHAHAHAHA I was pissed because being an ED admin seems a valid reason to vote someone done and the community has in part turned against me because of ED and proved by all the bullshit I received on irc and over email. Also I wanted new sysops simply because doing nothing but reverting vandals that are allowed to get to 50+ edits because nobody is awake to ban them and it fucking sucked and I'd had enough. But ok, I just won't except noms in VFS for a very long time now, tired of all the bullshit related to ED, also tired of being labeled as "a whiny little bitch who just wanted things to run more smoothly." ~Sir Frosty (Talk to me!) 23:02, July 5, 2012 (UTC) - Actually I suspect your attitude in general might raise issues and misgivings about your involvements elsewhere (and their reputations/issues) . More often than not, keeping calm and building some kind of consensus is better than trying to bludgeon your points across... This is a maturity thing, and as I suspect, a life experience thing. That's not something that comes with extra vigilance towards vandals. Again the impetus is on you, not on the community to resolve this need for admin status:)--Sycamore (Talk) 23:56, July 5, 2012 (UTC) For. →A (Ruins) 15:07, 5 July 2012 New hierarchical structure I saw the so-called fanboys at Bulbapedia (one of my all-time favorite wikis), and they seem to be organizing their admins into three tiers of adminship. Here's basically how it works. Right above the administrators, but lower in rank than the bureaucrats, are the Senior Administrators, who "can add and remove users from the abuse usergroup, view the checkuser log, delete pages with large histories, and more." These guys are just a bit more experienced than your average admin. (Further information: Bulbapedia:Senior Administrators.) Just below adminship is the Junior Administrator rank. (I've documented a proposal for this rank here.) Junior administrators can rollback, edit protected pages, view deleted pages, and show and hide individual edits to a page. I've added the extra privilege that they can archive old VFD and QVFD nominations. (Further information: Bulbapedia:Junior Administrators.) Let's discuss. -- Sir CuteLatiasOnTheRadio [CUN • PBJ'12 • PLS(0)] 16:22, July 5, 2012 (UTC) - Sounds interesting. I'm in! Cat the Colourful (Feed me!) Zzz 16:25, 5 July, 2012 (UTC) - Hm... what's it like to be j-- oomph! :3 -- Sir CuteLatiasOnTheRadio [CUN • PBJ'12 • PLS(0)] 16:26, July 5, 2012 (UTC) - I mean, ideally, about 5 of our sysops would become senior admins and about 7 of our regular users who contribute a lot would become junior admins. -- Sir CuteLatiasOnTheRadio [CUN • PBJ'12 • PLS(0)] 16:30, July 5, 2012 (UTC) - I'm not kissing anyone's ass but if Zombiebaron, Lyrithya, ChiefjusticeDS, Romartus and someone else would be senior admins. And Shabidoo would be a great junior admin. Cat the Colourful (Feed me!) Zzz 16:37, 5 July, 2012 (UTC) - This proposition is technically impossible. We do not have local CheckUser, separate admin usergroups, an abuse usergroup, or the ability to hide individual edits. And I doubt that Wikia is going to turn any of these features of for use (especially local CheckUser). -- Brigadier General Sir Zombiebaron 17:02, July 5, 2012 (UTC) - Or we could do what RationalWiki does and make anyone an op if they contribute regularly. --Hotadmin4u69 [TALK] 18:40 Jul 5 2012 For. →A (Ruins) 19:28, 5 July 2012 Nah. They might not have good judgement. -- Sir CuteLatiasOnTheRadio [CUN • PBJ'12 • PLS(0)] 18:34, July 6, 2012 (UTC) - Qzekrom Well, they wouldn't be automatically op'd....we could see their contribs and decide if they deserve it. →A (Ruins) 18:40, 6 July 2012 - Not feasible, plain and simple, for the reasons Zombiebaron stated. The difference in the toolbox is extremely marginal, plus it's just another way to make bureaucracy and rank seem more important on this comedy site where no one's supposed to give a sliver of a fuck about such retarded, menial things. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 01:30, July 7, 2012 (UTC) Shabidoo should never be nominated as any kind of admin While I appreciate the idea (though I'm not entirely sure if you guys are joking or not), I don't want to be an admin. There's no point as I wouldn't use the tools. However, you can vote for and feature my articles more often. And love me. I wish you guys would love me more. --ShabiDOO 23:11, July 5, 2012 (UTC) Zombiebaron's idea Ok, so here's my idea. This is the VFS model that was used at the time that I was made an admin. - The admins privately decide that more admins are required to keep the site running smoothly. This is because we the admins are the ones who are on the forefront of adminning the site. We collectively know how many pages get deleted and how many bans are given every day. We know when the site is running smoothly and when it is not. - The admins hold a two week nomination process, on a sysop-protected forum page, in MiniLuv. Anyone can nominate anyone. Both for and against votes are encouraged. - All registered users get to vote on the top scoring nominees from the previous round for the following 2 weeks, on a semi-protected Village Dump page. No against votes. No comments. - Top scoring users become admins. The number of admins is determined based on the voting totals and general community consensus. I think two votes for everyone in both of the voting rounds makes sense. -- Brigadier General Sir Zombiebaron 02:10, July 7, 2012 (UTC) - So, in this case, instead of everyone nominating anyone, only admins can nominate? Then, instead of Admins-only getting to vote in the final round, everyone does? It just switches when Users can vote from the first two rounds to the final round? Why was this switched away from in the first place? The Woodburninator Minimal Effort ™02:15, July 7, 2012 (UTC) - I have no idea why it was switched in the first place. The other important change is the first step. -- Brigadier General Sir Zombiebaron 02:18, July 7, 2012 (UTC) - A compromise for this I think. ~Sir Frosty (Talk to me!) 02:34, July 7, 2012 (UTC) - The switch occurred far, far earlier. I think MadMax and Strange but Untrue were the first admins to be elected by the system we currently have, and me and Mordillo rode the wave in shortly after. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 07:51, July 7, 2012 (UTC) - While Zombie may have some kind of sort of point about the admins being on the "forefront" of how many pages are whatever and how many users are whatever, there isn't any explanation as to why it should be "private". Since when were things done out of sight? Without transparency and a clear dialogue and communication available? Its disturbing that things have come to this, where the admins will get some kind of "carte blanche" to do as they please and not even have to account for it. --ShabiDOO 17:32, July 7, 2012 (UTC) - The admins already do many important things in private. Mostly arguing. But we do also have civil policy discussion and what-not. There are some things that we simply cannot discuss on the wiki. One recent example of this that I can think of is when I banned PotR. Several admins approached me privately on IRC to discuss that event. The fact that the admins will be deciding when we need new admins doesn't mean that we will no longer be listening to the views of the community. I mean, if somebody were to hold a vote where a vast majority of the registered users were calling for new admins, and the admins just ignored it, that would be stupid. --Brigadier General Sir Zombiebaron 17:46, July 7, 2012 (UTC) - Thats even more disturbing that there are important conversations going on that we don't even know about. I hope they don't involve policy or major decisions.--ShabiDOO 20:24, July 7, 2012 (UTC) - Privacy also works pragmatically against interloping absentee admins returning to the community with little idea of what it's been like for the past few months having an immediate say in policy/important votes. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 21:07, July 7, 2012 (UTC) - What kind of decisions are you guys making behind the scenes?--ShabiDOO 22:19, July 7, 2012 (UTC) - Beats me. I didn't even know we had a "scene." -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 22:20, July 7, 2012 (UTC) - And why precisely should "deciding if the wiki needs new admins" be held behind closed doors? Why can you not have that discussion with each other, at the VERY LEAST on the wiki, blocked so only admins can edit it? We should be able to see the positions of each admin, their reasons for and against and what the debate entails. Users should not be kept out of the dark about this. Theres no reason to. --ShabiDOO 12:51, July 8, 2012 (UTC) - It does not mean the admins won't entertain the whims of the community, it just means we can discuss it without fear of inciting drama, personal insult or implausibly high expectations of what will happen next. --Black Flamingo 13:13, July 8, 2012 (UTC) - But thats just putting bad faith on the community. Just because there was one particularily exagerated VFS drama, doesn't mean users should loose the right to know why a decision has been made. Just because there is the possibility of a problem doesnt mean you should hold your sessions behind closed doors. VFD has the potential to induce drama...does that mean the admins should now deal with VFD...and even more so behind closed doors? Besides, the big drama fest came from the "selection" of the admins and not wether to have admins. This solution just disenfranchises the community even more. Instead of having one step of the vote involving admins only making the decision, now, one of the steps is admins making the decision AND doing so with absolute secrecy. --ShabiDOO 18:35, July 8, 2012 (UTC) - For -RAHB 02:32, July 7, 2012 (UTC) - Spiritual for If change is required, then this is a good proposal. -- • Puppy's talk page • 02:51 07 Jul 02:51, July 7, 2012 (UTC) - I like it, aside from an issue already discussed with Zombiebaron. This makes me kind of want to come back and do stuff on uncyc again. Kind of.--OliOmniOmbudsman 03:48, July 7, 2012 (UTC) - The "issue" was whether or not against votes would be allowed during the second round of voting. I have changed the proposal to clearly state that against votes will not be allowed during the second round. -- Brigadier General Sir Zombiebaron 03:53, July 7, 2012 (UTC) - Does that principle also extend to the first round? (Just for clarification.) -- • Puppy's talk page • 06:48 07 Jul 06:48, July 7, 2012 (UTC) - Apparently not. I would also add in something protecting against "non-against comments" or comments in general, too, since some people love doing those so much, too. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 06:53, July 7, 2012 (UTC) - Seconded. ~ BB ~ (T) ~ Sat, Jul 7 '12 7:14 (UTC) - I'd allow for the provision of comments on the talk page. Votes for where votes go, comments elsewhere. (And I realise the irony of me saying this when I'm not actually voting here.) -- • Puppy's talk page • 08:51 07 Jul 08:51, July 7, 2012 (UTC) - Ok I haved added "No comments" to the proposal. -- Brigadier General Sir Zombiebaron 16:20, July 7, 2012 (UTC) For. Saberwolf116 (talk) 04:14, July 7, 2012 (UTC) - Also let's do this. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 06:54, July 7, 2012 (UTC) For. And if it doesn't work... We can argue some more. ~Sir Frosty (Talk to me!) 07:02, July 7, 2012 (UTC) - No we can't! --Black Flamingo 23:35, July 8, 2012 (UTC) - Shut up! The Woodburninator Minimal Effort ™ 23:40, July 8, 2012 (UTC) For. Especially the "No comments" part. ~ BB ~ (T) ~ Sat, Jul 7 '12 7:14 (UTC) - NO Admins should not be quietly tiptoeing around making decisions for users in a non open and non-trasparent way. Im surprised this is even being suggested, and that users would consider letting admins make decisions on our behalf behind closed doors. --ShabiDOO 14:05, July 7, 2012 (UTC) WTF? I'm not sure about this. Per Shabidoo, official Uncyclopedia processes need to be transparent. Here's my proposal: anyone should be able to request that an admin nominate them during the admin-only nominations (or else open up nominations to all autoconfirmed users). On an ideal wiki, it would take an expert to distinguish a regular user from an admin or a junior admin and so forth, but it's different here because we're kind of an odd community that actually has vanity pages about admins being dirty turds. --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 22:40, July 7, 2012 (UTC) - For. --Black Flamingo 11:09, July 8, 2012 (UTC) Upvote. – Sir Skullthumper, MD (criticize • writings • SU&W) 18:11 Jul 08, 2012 Against. A major step backwards. My biggest issue is that it still leaves VFSes up to admins. Why should the decision for new admins be left to the group of individuals whose absence necessitates VFSes in the first place? Shouldn't those who need admins and are irked when they're not around to help decide when it's time for some more of them? --Hotadmin4u69 [TALK] 18:24 Jul 8 2012 - Yeah. This seems to strike the balance.--Sycamore (Talk) 20:05, July 8, 2012 (UTC) - Against, especially that commenting bit. Regular users can have as useful of things to say as admins, even if they usually don't bother; there is always potential for misuse with any system, but that most votes here have a comment attached is also evidence of the potential for good, and well-worded supportive comments can still make a world of difference for a user faced with a general lack of other support. I also just don't like the only op if it's needed model; just because more admins aren't specifically needed doesn't mean that, provided capable candidates, it would hurt to lessen the workload for the current admins to help prevent burnout and give then more time to do other things, like write articles. Because people still do that here, from what I understand. Write, I mean. Don't they? -Lyrithya 12:01, July 12, 2012 (UTC) The Burninator's Idea (Joe The Burninator/Kyurem+Woodburninator) Wait, I think we can have a very democratic application here. How about we get the general public and the admins to vote if we need to have any more admins every two months? Then if the voting is passed upon agreeing that we need more admins, you can nominate someone or yourself to become an admin. The top five candidates who received most votes will afterwards proceed to the third part: discussion with the sysops on why they want to become an admin. After the interview, the sysops proceed to vote, with bureaucrats' votes worth three (Zombiebaron et al.), and only sysops can vote. So the process will be like this: - First week: General public decides if we need more admins. Needs for and against votes. This will take place every two months instead of monthly. - Second week: If we have enough votes for wanting more sysops, then we proceed to an election. You can nominate yourself or another person. Expect two-week voting process. For votes are only allowed, as the public will use a numbered system. The process will be explained: - To prevent rigging, the proportional voting system must be used. - The general public and sysops number their preferences for admin candidates, 1 being in most favor of being an admin, and the last number (7, 8, 9, 10, etc.) being in least favor. For example, if there are seven candidates, people number them from 1 to 7. Qzekrom will create the voting process. - The ones with the most votes are selected. The top five candidates with the most votes proceed to the next round. The rest are eliminated. - Fourth week: The top five candidates (the ones with the most for votes) are interviewed by sysops and bureaucrats. Expect a two-week process. - Sixth week: Sysops proceed to vote in a Hunger Games-style elimination round. Bureaucrats' vote is worth three votes. Again, two-week process. - Eighth week: The new sysops are announced Any questions? |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 08:54, July 7, 2012 (UTC) - Too long, too complicated and Zombiebaron's idea is simpler and works better. ~Sir Frosty (Talk to me!) 09:00, July 7, 2012 (UTC) - Agree with Frosty. Fails on the K.I.S.S. principle. (Keep it simple, fuckwad) -- • Puppy's talk page • 10:59 07 Jul 10:59, July 7, 2012 (UTC) - Addendum: The point of that that I agree with and could be used if we keep a system similar to the current is the 2 month rule. It takes users around 3 months (from what I've seen) to get to grips with the admin role. Two months is enough time though to see if they are coming to terms with it. It also reduces the "Yes/No" arguments to only 6 a year. 3 months would probably be a better term, as I don't recall seeing a VFS go to voting within 3 months of the previous. (I could be wrong on that though.) -- • Puppy's talk page • 11:04 07 Jul 11:04, July 7, 2012 (UTC) - Typically since we changed the rules to include users in round 1 its been around every 6 months. ~Sir Frosty (Talk to me!) 11:18, July 7, 2012 (UTC) - Is there a reason my name is associated with this? Or am I just being vain again? I do that sometimes! ME! ME! ME! The Woodburninator Minimal Effort ™ 21:27, July 7, 2012 (UTC) - It's because Joe likes to call himself "Joe the Burninator". —Sir Socky (talk) (stalk) GUN SotM UotM PMotM UotY PotM WotM 21:53, 7 July 2012 - JoeNumbers has a better ring to it. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 22:09, July 7, 2012 (UTC) - I like Joey Numbers. Sounds like a racketeer in the Mafia. Is that cool with you, Joey Numbers? The Woodburninator Minimal Effort ™ 22:14, July 7, 2012 (UTC) - No, call me Kyurem. And how the hell did you get unbanned, POTR? |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 05:48, July 8, 2012 (UTC) - I've been unbanned? Wow! -- • Puppy's talk page • 12:49 11 Jul 00:49, July 11, 2012 (UTC) - Sure thing, Joey Numbers. The Woodburninator Minimal Effort ™ 06:12, July 8, 2012 (UTC) - Joey Numbers: Don't Lose My Number or I'll Do a Number on Your Face! |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 08:27, July 9, 2012 (UTC) Voting process You asked me for it, here you go. Feel free to revise. I think rather than ranking all admin candidates, voters pick their top three choices to prevent ties, and so that no one gets offended finding that Joey Numbers ranked them sixth rather than fifth. (And it saves brainpower for writing articles.) (Though admins can pick more than three.) During the voting process, candidates are free to do campaigning as long as they aren't misleading. Then, the votes get tallied. Each vote gets put in as follows: - 1nd place: 50 points - 2st place: 38 points - 3th place: 25 points - 4rd place: 13 points The top five candidates are then nominated for the second round, and the next two become poopsmiths. --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 22:56, July 7, 2012 (UTC) - The process is still overlong (two whole weeks for interview when a single day will suffice) and unnecessarily complicated. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 23:01, July 7, 2012 (UTC) - Then we should fill up the rest of the time with conventions and debates between candidates (made on public Dump forums where a bureaucrat is assigned to moderate the forum). --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 23:12, July 7, 2012 (UTC) - And hey, do we really need two weeks for the elimination round? --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 23:17, July 7, 2012 (UTC) - There are a lot of words on this forum. Should I be paying attention? -- RomArtus*Imperator ® (Orate) 23:21, July 7, 2012 (UTC) - Not really. If anything noteworthy comes from this collection of words, it'll be reflected on {{VFSrules}}. So as far as paying attention is concerned, just putting that template on your watchlist will suffice. —Sir Socky (talk) (stalk) GUN SotM UotM PMotM UotY PotM WotM 00:07, 8 July 2012 - I think we need two new admins every two months. This should keep the numbers small. Also, I think we need a maximum of five candidates, and top three choices to prevent ties. |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 05:33, July 8, 2012 (UTC) - This is similar to the instant-runoff voting system that Spang proposed last year. I am all for it and the revised rules that The Burninator has proposed. --Hotadmin4u69 [TALK] 18:27 Jul 8 2012 - Instant runoff voting is better than that voting system we currently have. An if we have a two-week long voting process, we could give time for those unable to vote on one week, to vote the second week. And I'll change the numbering system (Qzekrom, I modified it because four is better than three) |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 08:01, July 9, 2012 (UTC) Quick note on the instant runoff suggestion and the two month rule The two month rule is a rule in which two new admins are picked every two months, while the rest will choose becoming a poopsmith or a rollback as a consolation prize. In the fourth and fifth weeks, there will be debates and conversations between candidates. All of the current goings-on regarding the debate and conversations for the VFS will be promoted on the UnSignpost and the VFS section of UnNews. The final three weeks will be a trial run on how the new admins are going. As a final note regarding campaigning for VFS, advertising campaigns will be placed on the board (where the PLS announcements and so on are placed), and must be approved by the Advertising Ombudsman (a bureaucrat). |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 08:27, July 9, 2012 (UTC) - Your proposal there has several flaws in it: - We do not need 2 new ops every 2 months, currently we have been getting 1 - 2 every 6 months and some see this as too many. You do the math 2 every 2 months = 12 a year and with our current user-base size that is far too much. - Poopsmith is a ridiculous "consolation prize" we have 3 active ones and 3 is plenty we archive 3 voting pages on the whole site and administrators also do this task as well, granting an otherwise meaningless title is a) a poor prize b) Pointless, we have enough and don't need anymore (I say this as a poopsmith as I can typically archive the 3 pages in a the space of a few minutes, without any help) - If you want rollback, be like a normal person and just ask Zombiebaron or Thekillerfroggy giving it as a second prize is a dumb idea because typically (under your proposal) anyone who comes second is going to already be a rollbacker (I base this off the fact we haven't had a non-rollbacker promoted to admin since 2008.) - Five weeks? As TKF pointed out everything you proposed can easily be done in half that time - Potential opping candidates before last VFS already did banter, argue and carry on. It's called IRC we argue and debate a lot there and guess where it typically will take us? No where - You are proposing a system that involves debates and voting almost like a presidential election, and yet we can't even manage a simple vote what on earth makes you think this will work? - UnNews is a namespace for humor and making fun of IRL events and being funny, it is not for carrying on about VFS which nobody in the real world cares about - ~Sir Frosty (Talk to me!) 08:40, July 9, 2012 (UTC) NEW PROPOSAL I'm so fucking tired of forum debates. VFS sucks. It will always suck. Nothing you do will ever improve it to the point where less than half of the user base can find some problem with it. We have mob rule here, and mob rule produces three things: tyrants, angry people, and angry dead people. If this were a country, I might give a shit. But it isn't a country, it's a comedy website. So I have a NEW FUCKING PROPOSAL (read closely, chimps, because it's about to get complicated): NO OPS EVER AGAIN, WITH THREE EXCEPTIONS: - If you give Zombiebaron sexual favors, instant oppage. Boom. - If you give Thekillerfroggy sexual favors, instant oppage. Boom. - If you post again in this forum, you die. Oh, wait, did I say there were three exceptions? Consider this one "oppage in Hell". Who's with me!?!? Boom. I hereby apologize for starting the last three forums I have been responsible for, and I request that y'all just fuck off to your respective corners, and start spewing comedy like comedy was shit and you fuckers just drank ten gallons of Log-Out™. ~ BB ~ (T) ~ Mon, Jul 9 '12 14:12 (UTC) - If this had been the rules from the beginning, I would have been opped years ago! The Woodburninator Minimal Effort ™ 14:41, July 9, 2012 (UTC) - Strong For. More sexual favors from Woody please. -- TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK 14:44, July 9, 2012 (UTC) - What if I give Zombie and TKF sexual favours at the same time. What then? --ShabiDOO 17:19, July 9, 2012 (UTC) Hell, no! What happens when all the current sysops have retired? --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 01:58, July 10, 2012 (UTC) Strong boner ~Sir Frosty (Talk to me!) 02:32, July 10, 2012 (UTC) Euroiphones New proposal: Whatever the voting rules are, let's create a new rank in the (Most Excellent) Order of Uncyclopedia and award that to VFS runner-ups, poopsmiths and rollbackers. We still don't have any use for Her Majesty's Flying Rat's Ass Medal, do we? --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 02:16, July 10, 2012 (UTC) - Thats hardly a proposal, this forum is for fixing the problem not adding pointless consolations to it. ~Sir Frosty (Talk to me!) 02:30, July 10, 2012 (UTC) Alternate suggestion Week one. The entire community equally and openly decides if a new admin is needed. Week two. The entire community nominates nominees. Week three and four. The entire community equally and openly selects the admin. Its simple, clear, equitable, transparant, participatory and uncomplicated. I personally like it. --ShabiDOO 02:59, July 10, 2012 (UTC) Ooh... that feels good... Forgive me, I was just thinking about the new system... Support. --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 03:13, July 10, 2012 (UTC) Kinda. ~ BB ~ (T) ~ Tue, Jul 10 '12 4:19 (UTC) Strong for And no word limits. Scofield & 1337 10:04, July 11, 2012 (UTC) For. Ticks the right boxes in my mind. -- • Puppy's talk page • 12:30 11 Jul 12:30, July 11, 2012 (UTC) For. --Hotadmin4u69 [TALK] 13:13 Jul 11 2012 - This Shabidoo guy is a communist fag. --ShabiDOO 19:08, July 11, 2012 (UTC) - If you included "all first- and second-week comments are limited to 20 words or less" and "votes are limited to 'For' or 'Against'", I'd vote "yes". ~ BB ~ (T) ~ Tue, Jul 10 '12 3:10 (UTC) - Less complicated would be: "don't be a dick during this process". --ShabiDOO 03:18, July 10, 2012 (UTC) - Yes, but certain pompous blowhards who shall remain nameless here would just say "I am not being a dick. I am simply offering up a 10,000-character comment (which I have, incidentally, chosen to label a 'non-vote') because that's how we do things on Wikipedia." So I think "no vote comments" and "keep all other comments short" needs to be carved in stone. ~ BB ~ (T) ~ Tue, Jul 10 '12 3:30 (UTC) - In an open, equal and transparent process, you cant tell users what to say, how to say it and when to say it. No matter what you do, nasty users will find a way to be dirty. Brush away unconstructive criticism to the side and move on. Just dont be dicks during the process and keep things equitable, fair and uncomplicated and a good admin will be selected. --ShabiDOO 03:51, July 10, 2012 (UTC) - You can't tell them what to say, but limiting how much they can say will certainly make them choose their words more carefully, and make it less headache-inducing to read. ~ BB ~ (T) ~ Tue, Jul 10 '12 4:19 (UTC) - We should have a televised debate for all of the candidates and we should get the cookie monster to be the moderator. His first question would be: 'peanut butter cookies vs. oatmeal bars'.--ShabiDOO 04:24, July 10, 2012 (UTC) - Which is better: "No. I do not think he would make a good admin. Perhaps in the future, though," or a paragraph which wastes 500 words to say EXACTLY the same thing? ~ BB ~ (T) ~ Tue, Jul 10 '12 4:44 (UTC) - I myself am very guilty of writing very long blocks of text. Its actually embarassing to read them. My three largest blocks of text were all written to the same user...who reacted in different ways to the different texts, 1. told me they didnt even bother to read it. 2. banned me. 3. tried to work things out. I still laugh my ass off when I read the longest one...and I laugh even harder when I read Aleisters commentary on it. It was very funny. --ShabiDOO 05:19, July 10, 2012 (UTC) - To avoid controversy, let's not allow explicit non-votes. If you're not going to vote for someone, just don't fucking vote! --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 21:29, July 10, 2012 (UTC) - I'm sorry that Lyrithya was nasty and dirty to Frosty and Puppy, but thats no reason to shut up users who have constructive comments. Zombiebarons proposal will make the process secretive and limiting to avoid "controversey" ... which is a very exagerated response to one bad VFS experience. Simple is better. --ShabiDOO 00:36, July 11, 2012 (UTC) - Let's keep it simple and see if Puppy has any ideas for how to change it. --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 00:40, July 11, 2012 (UTC) - In a Wikipedian manner, let's reserve the voting area for votes, and allow the comments in a separate section underneath, or preferably, on a talk page. That means that when someone wants to non-vote, they can do that, and write war and frigging peace if they like, but at least a vote is counted as a vote, and commentary is counted as commentary. In much the ame way this particular vote here has been framed. Clear, simple, concise, and equitable. -- • Puppy's talk page • 12:26 11 Jul 12:26, July 11, 2012 (UTC) The collegiate system At the present we have members of the community broken into various time zones. I propose we tabulate how many members we have in a particular time zone, and give that timezone a number of "collegiate" votes accordingly. Then the voting is done broken down into timezones. The majority of votes in a particular timezone means that all of those collegiate votes are put toward that candidate. That seems the only logical method to me. Oh, and terms cannot last longer than 2 years, and an admin cannot have more than 2 consecutive terms. And the admin candidates can be chosen by parties representing the retention of existing articles, or "conservatives", and the other party can represent the growth of new articles, or "liberals". And an individual cannot become an admin via merit alone, but by the country of their birth. That way we become the most powerful wiki on the web. GOD BLESS UNCYCLOPEDIA! -- • Puppy's talk page • 12:59 11 Jul 00:59, July 11, 2012 (UTC) - This is a misrepresentation of conservatives and liberals! Conservatives want to conserve the supreme position of featured articles while leaving every other article to starve to deletion for all they care. Liberals seek to divert the focus away from the featured articles, towards the often ignored majority of non-featured articles. —Sir Socky (talk) (stalk) GUN SotM UotM PMotM UotY PotM WotM 16:52, 11 July 2012 - It's impractical to de-op admins just because their terms expired. And what if someone doesn't want to reveal their time zone? --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 22:17, July 11, 2012 (UTC) - We can get time zone information from the Order of Uncyclopedia. --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 22:23, July 11, 2012 (UTC) - I think all of the current and active admins are good ones (though we all have our moments) and I cant see any reason to de-op or rotate or give terms for any of them as they'll probably always be useful and good admins (though we all have our moments). --ShabiDOO 23:14, July 11, 2012 (UTC) This forum ...is too long and confusing. In fact, it's longer than my penis even though it's erected now. Can someone please tell me what the hell is currently being discussed here? --QZEKЯOM Proud sponsor of Team Zombiebaron Tw$*ty Tw%#ve G*me$ FTW! Let's go for the g^@d! 22:52, July 11, 2012 (UTC) - When a man and a woman love each other very much... -- • Puppy's talk page • 01:19 12 Jul 01:19, July 12, 2012 (UTC) I say that we just go the Bulbapedian way. Where's my boner tag? I want an extensive erection like Cilan had! |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 06:33, July 12, 2012 (UTC) - Also, Boner. |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 06:42, July 12, 2012 (UTC) on a side note Sandwiches are fucking awesome. ~Sir Frosty (Talk to me!) 09:18, July 12, 2012 (UTC) - You're too young to be engaging in group sex. -- • Puppy's talk page • 09:24 12 Jul 09:24, July 12, 2012 (UTC) MasterWangs' great idea with a 100% chance of success!!! All of you stop bitching and write comedy -- Do you know why this system doesn't work? Because you all have it set it out in your head and have convinced yourselves that something will go wrong. In my humble opinion it's more an attitude problem more than an actual problem with the system. If you all could try and be more positive about it you might find it works. So my advice is as follows: - Leave the current system - Adopt a more positive mind set about it - Watch the results when it starts running more smoothly - Go back to writing comedy I personally think it's a mind thing, does anyone agree? --MasterWangs CUNT and proud of it! 08:20, July 15, 2012 (UTC) - From the mouth of madness. I MEAN, "babes". ~ BB ~ (T) ~ Sun, Jul 15 '12 8:33 (UTC) Fuck the system If we can't get admin rights, then we'll be doing it the hard way. We just need a new system. |Si Plebius Dato' (Sir) Joe ang Pinoy CUN|IC Kill | 11:18, July 16, 2012 (UTC) - And uh, that means what exactly? ~Sir Frosty (Talk to me!) 11:19, July 16, 2012 (UTC) --fcukman LOOS3R! 11:26, July 16, 2012 (UTC)
http://uncyclopedia.wikia.com/wiki/Forum:Should_VFS_be_abolished%3F?t=20120716112643
CC-MAIN-2014-23
refinedweb
8,890
63.39
0 Hello, if you have seen any of my other posts you will know I am working on a script to make a "vocabulary test". I currently having it functioning nearly perfectly, except I get an error if I enter the wrong word. Code: def vocabtest(): for r in words.values(): count = 0 while count < 3: print("What word does the following definition correspond with?") print(r) answer = raw_input("> ") if words[answer] == r: #Error print("Correct!") count = 100000 elif words[answer] != r: if count < 2: count = count + 1 print("That is incorrect. Try again.") elif count == 2: count = count + 1 print("That is incorrect. The answer was",str(words[r]) + ".") fail[r] = words[r] If I enter the wrong word, I get a Key Error at line 8. Would anybody be able to help? Thanks in advance.
https://www.daniweb.com/programming/software-development/threads/171187/dictionary-looping-name-error
CC-MAIN-2018-30
refinedweb
137
77.94
Opened 5 years ago Closed 3 years ago #18456 closed Bug (fixed) HttpRequest.get_full_path does not escape # sign in the url Description Suppose request was made with the url '/some%23thing?param=1', then get_full_path() would return '/some#thing?param=1' which I believe is incorrect as 'thing?param=1' is now in anchor part. Change History (10) comment:1 Changed 5 years ago by comment:2 Changed 5 years ago by I have always found request.get_full_path() to be less than useful when dealing with tricky corner cases. It doesn't escape anything itself, but if you escape its output, it also escapes the ' ?' used to assemble the path and the query string: >>> from django.http import HttpRequest >>> from django.utils.http import urlquote >>> request = HttpRequest() >>> request.>> request.META['QUERY_STRING'] = 'q=a' >>> request.get_full_path() '/?q=a' >>> urlquote(request.get_full_path()) u'/%3Fq%3Da' In cases involving both query strings and unicode characters in urls, I have found that it is best simply to avoid request.get_full_path() altogether. Instead, in my own projects I have defined a method called request.get_escaped_full_path() as follows: def get_escaped_full_path(self): return '%s%s' % (iri_to_uri(urlquote(self.path)), self.META.get('QUERY_STRING', '') and ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) or '') This turns out to be much more predictable (and useful). comment:3 follow-up:. comment:4 follow-up:. I think there is a bigger issue to consider here, and I hope you will reconsider having marked this ticket as wontfix. As I mentioned in comment:2, get_full_path() as currently implemented is useless on sites that contain paths that need escaping along with query strings. The question comes down to: should one urlencode the result of get_full_path(), or not? The documentation endorses neither way, and actually, neither answer is fully correct. Consider the case where one is attempting to use get_full_path() as a way to construct a URL to place in an HTML anchor tag, or a URL that can be used as a 302 redirect. If the path has a query string, then calling urlquote(request.get_fullpath()) will mistakenly urlencode the '?' character. If one chooses not to escape the result and just use get_full_path() directly (which is, e.g., what the django admin does), then the link will be broken if the URL contains characters that need to be escaped. As such, for any conceivable use case of HttpRequest.get_full_path(), the only behavior that makes consistent sense is to urlencode the path. This is true whether one is using it to e.g. construct an anchor tag with, or in a 301/302 redirect. In fact, in neither of these use cases (nor in any can I think of) does it even matter whether one is able to reconstruct the precise url that was sent by the browser. comment:5 Changed 4 years ago by It's difficult to say something about "every conceivable use case of get_full_path()". For instance, it could be used for logging; and one wants to log "/foo:bar/", not "%2Ffoo%3Abar%2F" :) Reopening to see if it would make sense to escape specifically significant characters in the path of an URL (?, #, ;, maybe others). comment:6 Changed 4 years ago by According to. I would escape all ";", "=" and "?" characters. The fragment isn't even contemplated because it's not strictly part of the URI:. Personally, I consider the possible logging clarity problems less important than the problems arising from HttpRequest.get_full_path() bad behavior. If needed, logging could use some other function to print out the URI. comment:7 Changed 4 years ago by It seems that Django doesn't (in principle) log the successful requests anywhere (the PATH_INFO WSGI environ is what gets logged both in development and production). The only place where get_full_path() is intended for human consumption is django.middleware.common.BrokenLinkEmailsMiddleware.process_response where it gets mailed. I would say that, in this case, it might be even interesting to have the "correct" yet difficult to understand path printed. comment:8 Changed 4 years ago by comment:9 Changed 3 years ago by Here is the revised pull request: Changes: - Fixed merge conflict - Rewrote the tests in tests/utils_tests/test_encoding.py - Added a test to tests/requests/tests.py - Updated the versionadded directive in docs/ref/utils.txt - Added a release note request.get_full_path()returns the path with the query string (if there is one). The result doesn't have any particular encoding or escaping applied. The docs would mention it otherwise :) This is a bit pathological when the path includes a "?". In this case, the "?" must have been escaped in the original representation of the URL (written in the HTML or typed in the address bar). Otherwise it would have been interpreted as the beginning of the query string. However, since request.get_full_path()is just path + '?' + query string, you can't tell the difference between a "?" in the path and the "?" that marks the beginning of the query string in its output. "#" is less of a problem. Browsers don't includes fragments (that's the official name for "anchor") in requests, so if you have a # in the output of request.get_full_path(), it was in the path or the query string. It can't be the anchor. To sum up with an example, if the escaped URL is /%3Ffoo%23bar?baz#quux, then request.get_full_path()is /?foo#bar?baz. So your question boils down to: should pathbe URL-encoded when building request.get_full_path()? To be honest I'm not sure. Note that django.utils.encoding.iri_to_uri()won't do the job because it keeps # and ? unchanged. Related ticket: #11522
https://code.djangoproject.com/ticket/18456
CC-MAIN-2017-26
refinedweb
929
59.09
Python/pandas: Column value in list (ValueError: The truth value of a Series is ambiguous.) I've been using Python's pandas library while exploring some CSV files and although for the most part I've found it intuitive to use, I had trouble filtering a data frame based on checking whether a column value was in a list. A subset of one of the CSV files I've been working with looks like this: $ cat foo.csv "Foo" 1 2 3 4 5 6 7 8 9 10 import pandas as pd df = pd.read_csv('foo.csv', index_col=False, header=0) >>> df Foo 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 If we want to find the rows which have a value of 1 we'd write the following: >>> df[df["Foo"] == 1] Foo 0 1 Finding the rows with a value less than 7 is as you'd expect too: >>> df[df["Foo"] < 7] Foo 0 1 1 2 2 3 3 4 4 5 5 6 Next I wanted to filter out the rows containing odd numbers which I initially tried to do like this: odds = [i for i in range(1,10) if i % 2 <> 0] >>> odds [1, 3, 5, 7, 9] >>> df[df["Foo"] in odds] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/markneedham/projects/neo4j-himym/himym/lib/python2.7/site-packages/pandas/core/generic.py", line 698, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Unfortunately that doesn't work and I couldn't get any of the suggestions from the error message to work either. Luckily pandas has a special isin function for this use case which we can call like this: >>> df[df["Foo"].isin(odds)] Foo 0 1 2 3 4 5 6 7 8 9 Much better! About the author Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database.
http://markhneedham.com/blog/2015/02/16/pythonpandas-column-value-in-list-valueerror-the-truth-value-of-a-series-is-ambiguous/
CC-MAIN-2018-17
refinedweb
353
62.72
I've tried a number of ways, and I don't seem to be able to use tscollect effectively while maintaining a _time component. Here is my tscollect: ... | bucket _time span=1d | stats [many different things] by transactionid, _time | fields - transactionid | tscollect keepresults=t namespace=mynamespace Here is my tstats: | tstats values(onestat) as onestat sum(anotherstat) as anotherstat from mynamespace groupby _time [span=1d] This just returned all of the results in one timeslot. I've also tried to mimic one of the examples from the docs: | tstats prestats=t values(onestat) as onestat sum(anotherstat) as anotherstat from mynamespace by _time [span=1d] | timechart count The latter only confirms that the tstats only returns one result. The local disk also confirms that there's only a single time entry: [root@splunksearch1 mynamespace]# ls -lh total 18M -rw------- 1 root root 18M Aug 3 21:36 1407049200-1407049200-18430497569978505115.tsidx -rw------- 1 root root 86 Aug 3 21:36 splunk-autogen-params.dat Can anyone offer any recommendations for how I can get tscollect to store the event time? It turns out my root cause was a lookup table I had in line had a leftover _time field not removed, which was overwriting the _time of the event. In essence, the above works perfectly, so long as you're not sabotaging yourself. It turns out my root cause was a lookup table I had in line had a leftover _time field not removed, which was overwriting the _time of the event. In essence, the above works perfectly, so long as you're not sabotaging yourself. You are using tscollect and tstats incorrectly. They are not meant to be used as collect/ summaryindex and stats, which is what it appears you are trying to do. The summary indexing backfill scripts will not work with them either (for different reasons). You could use: ... | fields <fields you are interested in> transactionid _time | tscollect namespace=mynamespace But then you will be responsible for backfill and missed data yourself. (As mentioned the summary backfill will not work with tscollect as it does with collect.) So really you should create a data model that contains all the fields you might be interested in working with and accelerate that data model instead. You can use then use tstats against the accelerated data model. But the way you're using it, you're sort of defeating one of the main points of tscollect/ tstats and that is to keep data in full fidelity, and to be able to therefore run any stats over it without specifying it ahead of time. You can do this I guess. But then I'd recommend that you at least just do as little aggregation on the fields as possible so that you can still do aggregations afterwards. tscollect can collect from stats. It just wasn't designed for it, and backfilling is usually a disaster especially if you have more than one indexer. If you must, your problem has nothing to do with tscollect, but because you're using stats and omitting _time on the "by" clause, so there's no _time being passed to tscollect in the first place. Just because you're running a specific range a day at a time, you must still include _time. (This is one of those things that the backfill scripts and addinfo scripts do for you with collect that tscollect does not handle.) It looks like what you're saying is that tscollect cannot receive the output of a stats command. Is that correct? The challenge with this data source (and why I originally failed using data models) is that a handful of the fields are in the starting event, and a handful in the ending event. Without using a stats (or transaction, etc.), I was having to store the transactionid and two events, so the default count the data model put in was inaccurate. tscollect was an attempt to work around that limitation. What is the right way to leverage acceleration here? (Search DM of Events DM?)
https://community.splunk.com/t5/Splunk-Search/Maintaining-time-with-tscollect-and-tstats/td-p/168801
CC-MAIN-2020-45
refinedweb
675
69.82
Hi all, I am now learning python, know a bit of VBA and C# so have some basic understanding of programming concepts. I read_csv (from pandas) a csv file, then used iloc to split the columns, so that I could then concatenate the data - no idea if this is the best way to do it, but it is the way I worked out from reading. I then thought, it would be nice to limit the data output to a range, and read some more. The code is below, and it works fine - I have put the data output below so you can see whether that is an issue. These are statistics from the UK gov website. The issue I am having is that changing the variable, so that it isn’t everything, pushed out an exception error. So if I change the value of the function to: .between(10, 30) I get this error: line 3080, in get_loc return self._engine.get_loc(casted_key)25, in pandas._libs.hashtable.Int64HashTable.get_item File “pandas_libs\hashtable_class_helper.pxi”, line 1632, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 0 Which is the cause of this exception: line 19, in print(firstRow[i], " - ", secondRow[i]) Removing this offending code block outputs the range limited data, just not in the format that I wanted it in. I wanted to try and understand why this error was occurring, why limiting the data set would throw the iloc part off and cause an exception? Thanks! Code and output: import pandas as pd import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() df = pd.read_csv(file_path) output = df[df["Number of homicides"].between(0, 40)] count = len(output.index) firstRow = output.iloc[:, 0] secondRow = output.iloc[:, 1] i = 0 while i < count: print(firstRow[i], " - ", secondRow[i]) i += 1 print(count) Output Data: Southwark - 40 Brent - 38 Greenwich - 38 Newham - 38 Croydon - 36 Haringey - 30 Redbridge - 29 Tower Hamlets - 29 Ealing - 27 Wandsworth - 27 Lambeth - 26 Enfield - 25 Waltham Forest - 25 Islington - 24 Westminster - 24 Barnet - 22 Camden - 22 Hackney - 22 Lewisham - 21 Barking and Dagenham - 17 Hammersmith and Fulham - 16 Hillingdon - 15 Hounslow - 15 Kensington and Chelsea - 12 Havering - 11 Kingston upon Thames - 9 Merton - 9 Bexley - 8 Harrow - 8 Bromley - 7 Richmond upon Thames - 7 Sutton - 3 32
https://discuss.python.org/t/panda-between-iloc-creating-odd-output-would-like-to-understand-why/9228
CC-MAIN-2021-31
refinedweb
387
71.44
Sentiment analysis on Trump's tweets using Python 🐍 Rodolfo Ferro Sep 12, 2017 Updated on Sep 13, 2017 DESCRIPTION: In this article we will: - Extract twitter data using tweepy and learn how to handle it using pandas. - Do some basic statistics and visualizations with numpy, matplotlib and seaborn. - Do sentiment analysis of extracted (Trump's) tweets using textblob. Phew! It's been a while since I wrote something kinda nice. I hope you find this a bit useful and/or interesting. This is based on a workshop I taught in Mexico City. I'll explain the whole post along with code, in the most simple way possible. Anyway, all the code can be found in the repo I used for this workshop. What will we need? First of all, we need to have Python installed. I'm almost sure that all the code will run in Python 2.7, but I'll use Python 3.6. I highly recommend to install Anaconda, which is a very useful Python distribution to manage packages that includes a lot of useful tools, such as Jupyter Notebooks. I'll explain the code supposing that we will be using a Jupyter Notebook, but the code will run if you are programming a simple script from your text editor. You'll just need to adapt it (it's not hard). The requirements that we'll need to install are: - NumPy: This is the fundamental package for scientific computing with Python. Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. - Pandas: This is an open source library providing high-performance, easy-to-use data structures and data analysis tools. - Tweepy: This is an easy-to-use Python library for accessing the Twitter API. - Matplotlib: This is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. - Seaborn: This is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics. - Textblob: This is a Python library for processing textual data. It provides a simple API for diving into common natural language processing (NLP) tasks. All of them are "pip installable". At the end of this article you'll be able to find more references about this Python libraries. Now that we have all the requirements, let's get started! 1. Extracting twitter data (tweepy + pandas) 1.1. Importing our libraries This will be the most difficult part of all the post... 😥 Just kidding, obviously it won't. It'll be just as easy as copying and pasting the following code in your notebook: # General: import tweepy # To consume Twitter's API import pandas as pd # To handle data import numpy as np # For number computing # For plotting and visualization: from IPython.display import display import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline Excellent! We can now just run this cell of code and go to the next subsection. 1.2. Creating a Twitter App In order to extract tweets for a posterior analysis, we need to access to our Twitter account and create an app. The website to do this is. (If you don't know how to do this, you can follow this tutorial video to create an account and an application.) From this app that we're creating we will save the following information in a script called credentials.py: - Consumer Key (API Key) - Consumer Secret (API Secret) - Access Token - Access Token Secret An example of this script is the following: # Twitter App access keys for @user # Consume: CONSUMER_KEY = '' CONSUMER_SECRET = '' # Access: ACCESS_TOKEN = '' ACCESS_SECRET = '' The reason of creating this extra file is that we want to export only the value of this variables, but being unseen in our main code (our notebook). We are now able to consume Twitter's API. In order to do this, we will create a function to allow us our keys authentication. We will add this function in another cell of code and we will run it: # We import our access keys: from credentials import * # This will allow us to use the keys as variables # API's setup: def twitter_setup(): """ Utility function to setup the Twitter's API with our access keys provided. """ # Authentication and access using keys: auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) # Return API with authentication: api = tweepy.API(auth) return api So far, so easy right? We're good to extract tweets in the next section. 1.3. Tweets extraction Now that we've created a function to setup the Twitter API, we can use this function to create an "extractor" object. After this, we will use Tweepy's function extractor.user_timeline(screen_name, count) to extract from screen_name's user the quantity of count tweets. As it is mentioned in the title, I've chosen @realDonaldTrump as the user to extract data for a posterior analysis. Yeah, we wanna keep it interesting, LOL. The way to extract Twitter's data is as follows: # We create an extractor object: extractor = twitter_setup() # We create a tweet list as follows: tweets = extractor.user_timeline(screen_name="realDonaldTrump", count=200) print("Number of tweets extracted: {}.\n".format(len(tweets))) # We print the most recent 5 tweets: print("5 recent tweets:\n") for tweet in tweets[:5]: print(tweet.text) print() With this we will have an output similar to this one, and we are able to compare the output with the Twitter account (to check if we're being consistent): Number of tweets extracted: 200. 5 recent tweets: On behalf of @FLOTUS Melania & myself, THANK YOU for today's update & GREAT WORK! #SouthernBaptist @SendRelief,… I will be going to Texas and Louisiana tomorrow with First Lady. Great progress being made! Spending weekend working at White House. Stock Market up 5 months in a row! 'President Donald J. Trump Proclaims September 3, 2017, as a National Day of Prayer' #HurricaneHarvey #PrayForTexas… Texas is healing fast thanks to all of the great men & women who have been working so hard. But still so much to do. Will be back tomorrow! We now have an extractor and extracted data, which is listed in the tweets variable. I must mention at this point that each element in that list is a tweet object from Tweepy, and we will learn how to handle this data in the next subsection. 1.4. Creating a (pandas) DataFrame We now have initial information to construct a pandas DataFrame, in order to manipulate the info in a very easy way. IPython's display function plots an output in a friendly way, and the headmethod of a dataframe allows us to visualize the first 5 elements of the dataframe (or the first number of elements that are passed as an argument). So, using Python's list comprehension: # We create a pandas dataframe as follows: data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets']) # We display the first 10 elements of the dataframe: display(data.head(10)) This will create an output similar to this: So we now have a nice table with ordered data. An interesting thing is the number if internal methods that the tweetstructure has in Tweepy: # Internal methods of a single tweet object: print(dir(tweets[0])) This outputs the following list of elements: ['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_api', '_json', 'author', 'contributors', 'coordinates', 'created_at', 'destroy', 'entities', 'favorite', 'favorite_count', 'favorited', 'geo', 'id', 'id_str', 'in_reply_to_screen_name', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'in_reply_to_user_id', 'in_reply_to_user_id_str', 'is_quote_status', 'lang', 'parse', 'parse_list', 'place', 'possibly_sensitive', 'retweet', 'retweet_count', 'retweeted', 'retweets', 'source', 'source_url', 'text', 'truncated', 'user'] The interesting part from here is the quantity of metadata contained in a single tweet. If we want to obtain data such as the creation date, or the source of creation, we can access the info with this attributes. An example is the following: # We print info from the first tweet: print(tweets[0].id) print(tweets[0].created_at) print(tweets[0].source) print(tweets[0].favorite_count) print(tweets[0].retweet_count) print(tweets[0].geo) print(tweets[0].coordinates) print(tweets[0].entities) Obtaining an output like this: 903778130850131970 2017-09-02 00:34:32 Twitter for iPhone 24572 5585 None None {'hashtags': [{'text': 'SouthernBaptist', 'indices': [90, 106]}], 'symbols': [], 'user_mentions': [{'screen_name': 'FLOTUS', 'name': 'Melania Trump', 'id': 818876014390603776, 'id_str': '818876014390603776', 'indices': [13, 20]}, {'screen_name': 'sendrelief', 'name': 'Send Relief', 'id': 3228928584, 'id_str': '3228928584', 'indices': [107, 118]}], 'urls': [{'url': '', 'expanded_url': '', 'display_url': 'twitter.com/i/web/status/9…', 'indices': [121, 144]}]} We're now able to order the relevant data and add it to our dataframe. 1.5. Adding relevant info to our dataframe As we can see, we can obtain a lot of data from a single tweet. But not all this data is always useful for specific stuff. In our case we well just add some data to our dataframe. For this we will use Pythons list comprehension and a new column will be added to the dataframe by just simply adding the name of the content between square brackets and assign the content. The code goes as...: # We add relevant data: data['len'] = np.array([len(tweet.text) for tweet in tweets]) data['ID'] = np.array([tweet.id for tweet in tweets]) data['Date'] = np.array([tweet.created_at for tweet in tweets]) data['Source'] = np.array([tweet.source for tweet in tweets]) data['Likes'] = np.array([tweet.favorite_count for tweet in tweets]) data['RTs'] = np.array([tweet.retweet_count for tweet in tweets]) And to display again the dataframe to see the changes we just...: # Display of first 10 elements from dataframe: display(data.head(10)) Now that we have extracted and have the data in a easy-to-handle ordered way, we're ready to do a bit more of manipulation to visualize some plots and gather some statistical data. The first part of the post is done. 2. Visualization and basic statistics 2.1. Averages and popularity We first want to calculate some basic statistical data, such as the mean of the length of characters of all tweets, the tweet with more likes and retweets, etc. From now, I'll just add some input code and the output right below the code. To obtain the mean, using numpy: # We extract the mean of lenghts: mean = np.mean(data['len']) print("The lenght's average in tweets: {}".format(mean)) The lenght's average in tweets: 125.925 To extract more data, we will use some pandas' functionalities: # We extract the tweet with more FAVs and more RTs: fav_max = np.max(data['Likes']) rt_max = np.max(data['RTs']) fav = data[data.Likes == fav_max].index[0] rt = data[data.RTs == rt_max].index[0] # Max FAVs: print("The tweet with more likes is: \n{}".format(data['Tweets'][fav])) print("Number of likes: {}".format(fav_max)) print("{} characters.\n".format(data['len'][fav])) # Max RTs: print("The tweet with more retweets is: \n{}".format(data['Tweets'][rt])) print("Number of retweets: {}".format(rt_max)) print("{} characters.\n".format(data['len'][rt])) The tweet with more likes is: The United States condemns the terror attack in Barcelona, Spain, and will do whatever is necessary to help. Be tough & strong, we love you! Number of likes: 222205 144 characters. The tweet with more retweets is: The United States condemns the terror attack in Barcelona, Spain, and will do whatever is necessary to help. Be tough & strong, we love you! Number of retweets: 66099 144 characters. This is common, but it won't necessarily happen: the tweet with more likes is the tweet with more retweets. What we're doing is that we find the maximum number of likes from the 'Likes' column and the maximum number of retweets from the 'RTs' using numpy's max function. With this we just look for the index in each of both columns that satisfy to be the maximum. Since more than one could have the same number of likes/retweets (the maximum) we just need to take the first one found, and that's why we use .index[0] to assign the index to the variables favand rt. To print the tweet that satisfies, we access the data in the same way we would access a matrix or any indexed object. We're now ready to plot some stuff. :) 2.2. Time series Pandas has its own object for time series. Since we have a whole vector with creation dates, we can construct time series respect tweets lengths, likes and retweets. The way we do it is: # We create time series for data: tlen = pd.Series(data=data['len'].values, index=data['Date']) tfav = pd.Series(data=data['Likes'].values, index=data['Date']) tret = pd.Series(data=data['RTs'].values, index=data['Date']) And if we want to plot the time series, pandas already has its own method in the object. We can plot a time series as follows: # Lenghts along time: tlen.plot(figsize=(16,4), color='r'); This creates the following output: And to plot the likes versus the retweets in the same chart: # Likes vs retweets visualization: tfav.plot(figsize=(16,4), label="Likes", legend=True) tret.plot(figsize=(16,4), label="Retweets", legend=True); This will create the following output: 2.3. Pie charts of sources We're almost done with this second section of the post. Now we will plot the sources in a pie chart, since we realized that not every tweet is tweeted from the same source (😱🤔). We first clean all the sources: # We obtain all possible sources: sources = [] for source in data['Source']: if source not in sources: sources.append(source) # We print sources list: print("Creation of content sources:") for source in sources: print("* {}".format(source)) With the following output, we realize that basically this twitter account has two sources: Creation of content sources: * Twitter for iPhone * Media Studio We now count the number of each source and create a pie chart. You'll notice that this code cell is not the most optimized one... Please have in mind that it was 4 in the morning when I was designing this workshop. 😅 # We create a numpy vector mapped to labels: percent = np.zeros(len(sources)) for source in data['Source']: for index in range(len(sources)): if source == sources[index]: percent[index] += 1 pass percent /= 100 # Pie chart: pie_chart = pd.Series(percent, index=sources, name='Sources') pie_chart.plot.pie(fontsize=11, autopct='%.2f', figsize=(6, 6)); With this we obtain an output like this one: And we can see the percentage of tweets per source. We can now proceed to do sentiment analysis. 3. Sentiment analysis 3.1. Importing textblob As we mentioned at the beginning of this post, textblob will allow us to do sentiment analysis in a very simple way. We will also use the re library from Python, which is used to work with regular expressions. For this, I'll provide you two utility functions to: a) clean text (which means that any symbol distinct to an alphanumeric value will be remapped into a new one that satisfies this condition), and b) create a classifier to analyze the polarity of each tweet after cleaning the text in it. I won't explain the specific way in which the function that cleans works, since it would be extended and it might be better understood in the official redocumentation. The code that I'm providing is: from textblob import TextBlob import re def clean_tweet(tweet): ''' Utility function to clean the text in a tweet by removing links and special characters using regex. ''' return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) def analize_sentiment(tweet): ''' Utility function to classify the polarity of a tweet using textblob. ''' analysis = TextBlob(clean_tweet(tweet)) if analysis.sentiment.polarity > 0: return 1 elif analysis.sentiment.polarity == 0: return 0 else: return -1 The way it works is that textblob already provides a trained analyzer (cool, right?). Textblob can work with different machine learning models used in natural language processing. If you want to train your own classifier (or at least check how it works) feel free to check the following link. It might result relevant since we're working with a pre-trained model (for which we don't not the data that was used). Anyway, getting back to the code we will just add an extra column to our data. This column will contain the sentiment analysis and we can plot the dataframe to see the update: # We create a column with the result of the analysis: data['SA'] = np.array([ analize_sentiment(tweet) for tweet in data['Tweets'] ]) # We display the updated dataframe with the new column: display(data.head(10)) Obtaining the new output: As we can see, the last column contains the sentiment analysis ( SA). We now just need to check the results. 3.2. Analyzing the results To have a simple way to verify the results, we will count the number of neutral, positive and negative tweets and extract the percentages. # We construct lists with classified tweets: pos_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] > 0] neu_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] == 0] neg_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] < 0] Now that we have the lists, we just print the percentages: # We print percentages: print("Percentage of positive tweets: {}%".format(len(pos_tweets)*100/len(data['Tweets']))) print("Percentage of neutral tweets: {}%".format(len(neu_tweets)*100/len(data['Tweets']))) print("Percentage de negative tweets: {}%".format(len(neg_tweets)*100/len(data['Tweets']))) Obtaining the following result: Percentage of positive tweets: 51.0% Percentage of neutral tweets: 27.0% Percentage de negative tweets: 22.0% We have to consider that we're working only with the 200 most recent tweets from D. Trump (last updated: September 2nd.). For more accurate results we can consider more tweets. An interesting thing (an invitation to the readers) is to analyze the polarity of the tweets from different sources, it might be deterministic that by only considering the tweets from one source the polarity would result more positive/negative. Anyway, I hope this resulted interesting. As we saw, we can extract, manipulate, visualize and analyze data in a very simple way with Python. I hope that this leaves some uncertainty in the reader, for further exploration using this tools. It might be possible to find little mistakes in the translation of the material (I designed the workshop in Spanish, originally 😅). Please feel free to comment or suggest all that comes up to your mind. That would complement some ideas that I already have in mind for further work. 😀 I'll now leave some references for documentation and tutorials on the used libraries. Hope to hear from you! References: - Official documentation - Tweepy. - Official documentation - NumPy. - Official tutorial - NumPy. - Official tutorial - Pandas. - Official documentation - Pandas. - Official documentation - Matplotlib. - Official tutorial - Pyplot. - Official website - Seaborn. - Official documentation - TextBlob. - Tutorial: Building a Text Classification System - TextBlob. Awesome tutorial!! Thank you so much! 😀👍. :) Excellent, Superb man you are! Executed your code., got the results as it is. Thanks! I'm glad you enjoyed it. :) @Rodolfo @ben This is really great, can we do healthcare analysis for USA. As it took time for CBO for recent Healthcare (not making anything political) but they took seven days for calculate CBO score which is ridiculous.. Excelente trabajo Rodolfo para NLP. Saludos un abrazo Muchísimas gracias. Como mencionaba en el post, en mi Github puede encontrarse el notebook con el contenido en español (por cualquier cosa). ¡Saludos! nice Thank you!. :)
https://dev.to/rodolfoferro/sentiment-analysis-on-trumpss-tweets-using-python-?utm_content=buffer6877a&utm_medium=social&utm_source=linkedin.com&utm_campaign=buffer
CC-MAIN-2018-09
refinedweb
3,278
65.22
Hi all, I am new to Zope but worked for 2 years in a dev-env called Uniface so Im fairly up to speed on Zope quickly. But I am having a problem writing data through a REQUEST.set that is larger than its apparent limit. (sorry can remember the exact error i get from Zope) What I am trying to do is collect in a field a large list of emails that are gathered in a dtml-in statement with a REQUEST.set('all', all + email) nested in the loop. While appending the namespace to store the data in PGSQL, i always get the size error which i assume is coming from the publisher saying that a the request can only have a byte size of 1800 bytes or so. Im not so hot with straight SQL because Uniface had its own methods, so Im not sure if I can append data directly to a stored field or if I need to continue trying to use the REQUEST.set. After the hundreth occurence in the IN, the namespace I use to store the appended data, so I cannot fully make a list of 2000 occurences. Any ideas? Sorry, no code to show what Im doing but it should be pretty easy to understand for all you veterans out there... TIA, -- Paz Oratrix Development BV GRiNS SMIL Editor - _______________________________________________ Zope maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - ) - Re: [Zope] REQUEST.set size Paul Zwarts - Re: [Zope] REQUEST.set size Paul Zwarts - Re: [Zope] REQUEST.set size Evan Simpson - Re: [Zope] REQUEST.set size Manuel Amador (Rudd-O)
https://www.mail-archive.com/zope@zope.org/msg08997.html
CC-MAIN-2018-51
refinedweb
271
70.84
Name: [171] Florian Mayer Member: 93 months Authored: 7 videos Description: I'm a student from Vienna, the federal capital of Austria. Please visit `My Blog <>`_ ... Decorators: The Basics [ID:877] (1/3) in series: Advanced Python video tutorial by Florian Mayer, added 09/08 Name: [171] Florian Mayer Member: 93 going to show you the basics of decorators. A decorator is used to alter the docstring of a function. def change_doc(docstring): def decorator(func): func.__doc__ = docstring return func return decorator #@change_doc("My super-new docstring") def foo(bar): """ My old docstring """ return bar foo = change_doc("My super-new docstring")(foo) if __name__ == '__main__': print foo.__doc__ Got any questions? Get answers in the ShowMeDo Learners Google Group. Video statistics: - Video's rank shown in the most popular listing - Video plays: 1892 << groovy Perspicuous. If I were unfamiliar with decorators, I would appreciate brief illustrations of specific situations where you have used them. (Changing __doc__ strings, while simple enough to serve as clear examples, doesn't convey how important decorators can be). Nice VIdeo,rly.. U speak slowy and clearly. I Understood everything of the Decorators :D... You have to know im German :P I was having difficulty understanding the concept and implementation of decorators, but your video along with some experimenting helped to clear this up. Thank you, Steve I was having difficulty understanding the concept and implementation of decorators, but your video along with some experimenting helped to clear this up. Thank you, Steve thanks -- just learning decorators. Technical note -- I was hanging on last image when this comment page popped up and I lost my train of thought and the image. Very clear example, good video. Thanks! You've made decorators' purpose much clearer, thanks! Seems logical to have a meta-level for munging code while running. Rather like adapting to life! good job. thanks Very nice intro into Decorators. Cheers! Hi Florian, When you showed your results, they were only flashed on the screen for a quick moment before you went back to your original screen. It would have been nice if you could have left that screen up a bit longer. Also it was difficult to know what we were looking at without more explanation. Some sort of screen pointer would be helpful so we would know where to direct our eyes and what portion of an overwhelmingly complex screen image is important for us to pay attention to. It would also be nice to have a bit of introduction at the beginning of what you are planning to show us and what you want to accomplish in showing that to us. Then at the end a short summation of what you had just showed us and what we should take away with us. I also like less abstract examples. Show this in the context of a simple programming idiom we can relate to. (example: functions that compute the board feet in a log. A decorator that adapts that function for different kinds of woods and/or different kinds of prices) Give us some idea where and when we would find a decorator useful. Give us a reason for wanting to use a decorator. Thanks, Good Luck, Bruce Great... thanks a lot. Helps me to understand decorators :-) I got a bunch of "Advanced Python" videos on my harddisk. But I am too lazy to post-process them, for some months now. Once I do that I'll upload videos about lambda, higher-order functions, list comprehensions, generator expressions and so forth. Stay tuned! More videos on advanced python, please Nice to have advanced python, there aren't so many! I have never understood decorators until watching this video. It is starting to make some sense now. Thanks for putting this together. mind-boggling ! the wing-ide looks really cool, i was not aware that it works under linux. Oh really? I'm very delighted to hear that. Be sure to comment on the second video too. Thanks! was anxiously waiting for this video! The ShowMeDo Robot says - this video is now published, thanks for adding to ShowMeDo.
http://showmedo.com/videotutorials/video?name=3370000
CC-MAIN-2014-42
refinedweb
685
65.73
TIFF imread() fail std::bad_alloc in Ubuntu 14.04 Hi, I installed a fresh Ubuntu 14.04 and use cmake and gcc 4.8 with -std=c++11 flag to build OpenCV from source. Where I select "With TIFF" and "Build TIFF" in CMake-GUI. The simple code : #include "opencv2/opencv.hpp" int main(void) { Mat rst = cv::imread("test.tiff",0); cv::namedWindow("testCV"); imshow("testCV",rst); cv::waitKey(0); return 0; } compiled by: g++ -o testcv -I/usr/local/include testcv.cpp -lopencv_core -lopencv_highgui -std=c++11 When it runs failed with info: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) I tried compiling OpenCV 2.4.9 (Release) and 3.0.0-dev (in GitHub) source. But both of them has the same failure.I tried PNG and JPEG, they work well. What is the problem? Is this OS related problem? I used the same code in my Ubuntu 12.04, and it has no problem at all.
https://answers.opencv.org/question/38937/tiff-imread-fail-stdbad_alloc-in-ubuntu-1404/?answer=38998
CC-MAIN-2019-43
refinedweb
168
80.48
:\/\/mozilla.org\/" }) }} The data from this macro is available in template code as an object in the $0 argument (e.g., $0.Alpha, $0.Beta, $0.Foo). This also allows you to express complex data structures in macro parameters that are hard or impossible to do with a simple list of parameters. Note that this parameter style is very picky — it must adhere to JSON syntax exactly, which has some requirements about escaping characters that are easy to miss (e.g., all forward slashes are escaped). When in doubt, try running your JSON through a validator. Como escrever "{{" no texto Since the character sequence " {{" is used to indicate the start of a macro, this can be troublesome if you actually just want to use " {{" and " }}" in a page. It will probably produce DocumentParsingError messages. In this case, you can escape the first brace with a backslash, like so: \{). KumaScript templates are processed by an embedded JavaScript template engine with a few simple rules: - Within a template, the parameters passed in from the macro are available as the variables $0, $1, $2, and so on. The entire list of parameters is also available in a template as the variable arguments. - Most text is treated as output and included in the output stream. - JavaScript variables and expressions can be inserted into the output stream with these blocks: <%= expr %>— the value of a JavaScript expression is escaped for HTML before being included in output (e.g., characters like <and >are turned into <and >). <%- expr %>— the value of a JavaScript expression is included in output without any escaping. (Use this if you want to dynamically build markup or use the results of another template that may include markup.) - It is an error to include semicolons inside these blocks. - Anything inside a <% %>block is interpreted as JavaScript. This can include loops, conditionals, etc. - Nothing inside a <% %>block can ever contribute to the output stream. But, you can transition from JS mode to output mode using <% %>—for example: <% The env.tags and env.review_tags variables return arrays of tags. You can work with these in many ways, of course, but here are a couple of suggestions. Looking to see if a specific tag is set You can look to see if a specific tag exists on a page like this: if (env.tags.indexOf("tag") != −1) { // The page has the tag "tag" } Iterating over all the tags on a page You can also iterate over all the tags on a page, like this: env.tag.forEach(function(tag) { // do whatever you need to do, such as: if (tag.indexOf("a") == 0) { // this tag starts with "a" - woohoo! } }); APIs This manually-maintained documentation is likely to fall out of date with the code. With that in mind, you can always check out the latest state of built-in APIs in the KumaScript source. But here is a selection of useful methods exposed to templates: md5(string) - Returns an MD5 hex digest of the given string. template("name", ["arg0", "arg1", ..., "argN"]) - Executes and returns the result of the named template with the given list of parameters. - Example: <%- template("warning", ["foo", "bar", "baz"]) %>. - Example using the domxrefmacro: <%- template("domxref", ["Event.bubbles", "bubbles"]) %>. - This is a JavaScript function. So, if one of the parameters is an arg variable like $2, do not put it in quotes. Like this: <%- template("warning", [$1, $2, "baz"]) %>. If you need to call another template from within a block of code, do not use <%... %>. Example: myvar = "<li>" + template("LXRSearch", ["ident", "i", $1]) + "</li>"; require(name) - Loads another template as a module; any output is ignored. Anything assigned to module.exportsin the template is returned. - Used in templates like so: <% var my_module = require('MyModule'); %>. cacheFn(key, timeout, function_to_cache) - Using the given key and cache entry lifetime, cache the results of the given function. Honors the value of env.cache_controlto invalidate cache on no-cache, which can be sent by a logged-in user hitting shift-refresh. request - Access to mikeal/request, a library for making HTTP requests. Using this module in KumaScript templates is not yet very friendly, so you may want to wrap usage in module APIs that simplify things. log.debug(string) - Outputs a debug message into the script log on the page (i.e. the big red box that usually displays errors). Módulos de API integrados There's only one API built in at the moment, in the kuma namespace. You can see the most up to date list of methods under kuma from the KumaScript source code, but here are a few: kuma.inspect(object) - Renders any JS object as a string, handy for use with log.debug(). See also: node.js util.inspect(). kuma.htmlEscape(string) - Escapes the characters &, <, >, "to &, <, >, ", respectively. kuma.url - See also: node.js urlmodule. kuma.fetchFeed(url) - Fetch an RSS feed and parse it into a JS object. A useful tip when debugging. You can use the log.debug() method to output text to the scripting messages area at the top of the page that's running your template. Note that you need to be really sure to remove these when you're done debugging, as they're visible to all users! To use it, just do something like this: <%- log.debug("Some text goes here"); %> You can, of course, create more complex output using script code if it's helpful. Colocação em cache KumaScript templates are heavily cached to improve performance. For the most part, this works great to serve up content that doesn't change very often. But, as a logged-in user, you have two options to force a page to be regenerated, in case you notice issues with scripting: - Hit Refresh in your browser. This causes KumaScript to invalidate its cache for the content on the current page by issuing a request with a Cache-Control: max-age=0header. - Hit Shift-Refresh in your browser. This causes KumaScript to invalidate cache for the current page, as well as for any templates or content used by the current page by issuing a request with a Cache-Control: no-cacheheader.. Cookbook This section will list examples of common patterns for templates used on MDN, including samples of legacy DekiScript templates and their new KumaScript equivalents. Force templates used on a page to be reloaded It bears repeating: To force templates used on a page to be reloaded after editing, hit Shift-Reload. Just using Reload by itself will cause the page contents to be regenerated, but using cached templates and included content. A Shift-Reload is necessary to invalidate caches beyond just the content of the page itself. Recovering from "Unknown Error" Sometimes, you'll see a scripting message like this when you load a page: Kumascript service failed unexpectedly: <class 'httplib.BadStatusLine'> This is probably a temporary failure of the KumaScript service. If you Refresh the page, the error may disappear. If that doesn't work, try a Shift-Refresh. If, after a few tries, the error persists - file an IT bug for Mozilla Developer Network to ask for an investigation. Broken wiki.languages() macros On some pages, you'll see a scripting error like this: Syntax error at line 436, column 461: Expected valid JSON object as the parameter of the preceding macro but... If you edit the page, you'll probably see a macro like this at the bottom of the page: {{ wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) }} To fix the problem, just delete the macro. Or, replace the curly braces on either side with HTML comments <!-- --> to preserve the information, like so: <!-- wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) --> Because Kuma supports localization differently, these macros aren't actually needed any more. But, they've been left intact in case we need to revisit the relationships between localized pages. Unfortunately, it seems like migration has failed to convert some of them properly. Finding the Current Page's Language In KumaScript, the locale of the current document is exposed as an environment variable: var lang = env.locale; The env.locale variable should be reliable and defined for every document. Reading the contents of a page attachment You can read the contents of an attached file by using the mdn.getFileContent() function, like this: <% var contents = mdn.getFileContent(fileUrl); ... do stuff with the contents ... %> or <%-mdn.getFileContent(fileObject)%> In other words, you may specify either the URL of the file to read or as a file object. The file objects for a page can be accessed through the array env.files. So, for example, to embed the contents of the first file attached to the article, you can do this: <%-mdn.getFileContent(env.files[0])%>o Templates are not translated like wiki pages, rather any single template might be used for any number of locales. So the main way to output content tailored to the current document locale is to pivot on the value of env.locale. There are many ways to do this, but a few patterns are common in the conversion of legacy DekiScript templates: If/else blocks in KumaScript The KumaScript equivalent of this can be achieved with simple if/else blocks, like so: <% if ("fr" == env.locale) { %> <%- template("CSSRef") %> « <a title="Référence_CSS/Extensions_Mozilla" href="/fr/docs/Référence_CSS/Extensions_Mozilla">Référence" href="/en-US/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a> <% } %> Depending on what text editor is your favorite, you may be able to copy & paste from the browser-based editor and attack this pattern with a series of search/replace regexes to get you most of the way there. My favorite editor is MacVim, and a series of regexes like this does the bulk of the work with just a little manual clean up following: %s#<span#^M<span#g %s#<span lang="\(.*\)" .*>#<% } else if ("\1" == env.locale) { %>#g %s#<span class="script">template.Cssxref(#<%- template("Cssxref", [# %s#)</span> </span>#]) %> Your mileage may vary, and patterns change slightly from template to template. That's why the migration script was unable to just handle this automatically, after all. String variables and switch.
https://developer.mozilla.org/pt-PT/docs/MDN/Tools/KumaScript
CC-MAIN-2021-04
refinedweb
1,675
65.22
We are excited to release new functionality to enable a 1-click import from Google Code onto the Allura platform on SourceForge. You can import tickets, wikis, source, releases, and more with a few simple steps. Pearson, Lewis wrote: > from java.lang import Runtime > barf = Runtime.exec("dir") > > The above gives me the following error. > TypeError: exec(): expected 2-4 args; got 1 > > Should be able to accept one arg. This wouldn't work in Java either. :-) You need: Runtime.getRuntime().exec( "dir" ) Usually, when you get that "expected ... args", it means you're calling an instance method w/o passing an instance (that is, you're calling it as if it were a static method). kb PS. Of course, for this particular case, you want: import os os.listdir() from java.lang import Runtime barf = Runtime.exec("dir") The above gives me the following error. TypeError: exec(): expected 2-4 args; got 1 Should be able to accept one arg. Any ideas Lew Pearson Chief Architect, New Development NetBoss Business Unit Harris Corporation, NSD (321-724-3234) lpearson@...
http://sourceforge.net/p/jython/mailman/message/7287113/
CC-MAIN-2014-10
refinedweb
179
69.68
App Search with Thinking Sphinx 3.0 Thinking Sphinx is now a very standard library for interfacing with Sphinx and has come a long way in its implementation of various features of Sphinx. The new version, 3.0, is a major rewrite and quite a departure especially in terms of setup. Also, it includes fairly advanced facet searching built into it. Lastly, this version is compatible only with Rails 3.1 or above. Installation Sphinx installation on Linux is pretty straightforward. Downloading and compiling from source is a preferred method of Sphinx installation, despite the fact that apt and yum repositories are almost up-to-date. The newer versions of Sphinx has multi-query support with mysql, and hence it’s better to compile it with mysql development headers included. $ wget $ tar xvzf sphinx-2.0.7-release.tar.gz $ cd sphinx-2.0.7-release/ $ ./configure --with-mysql $ make $ sudo make install Once Sphinx is installed successfully, you can install Thinking Sphinx as a gem or bundle it in your application. $ gem install thinking-sphinx -v "~> 3.0.2" If mysql is your database of choice, you will have to make sure the mysql2 gem version is either locked at 0.3.12b4 or 0.3.12b5. The earlier versions of mysql2 gem will throw the following exception : undefined method `next_result' for Mysql2 The error occurs because the previous versions of the mysql2 gem did not have multiquery support, and Sphinx now has that out-of-the-box. Configuration Thinking Sphinx has two main configuration files. In the earlier versions, the first file was named sphinx.yml, but has been renamed to thinking_sphinx.yml. The second file is .sphinx.conf (e.g development.sphinx.conf) and is used to interface Sphinx with the database. Whenever a fresh index is created, a fresh conf file is created which lists all the Sphinx queries based on the defined indices and connection details in database.yml. thinking_sphinx.yml is an extension of this file where you can pass extra options to improve your search results. Use Case Let’s say we have an application with the following models : - Vendor – name, rating - Shop – name, description, vendor_id, location - Product – name, sku, description, price, shop_id with the following model associations - Vendor – has_many shops - Shop – belongsto vendor, hasmany products - Product – belongs_to shop We have the following use cases which we will cover in our article: - Search Vendor, Shop, Product individually - Search across all models - Search via asociation - Define Facets to Create filters Basics – Definition of Indices. Thinking Sphinx 3.0 takes a cleaner approach to the definition of indices compared to earlier versions. To start defining an index, you first need to create a directory named ‘indices’ under the app folder. $ mkdir indices Let’s follow our use case and create three index files in our indices folder: - vendor_index.rb - shop_index.rb - product_index.rb The index file definition includes the name of class on which need to search. It should be the same as the model class name. The indices for attributes can be defined simply by writing : indexes column_name However, there are a few reserved keywords for Sphinx (e.g status). To make these columns acceptable by Sphinx, you would have to define them as a symbol. indexes :status According to our use case, let’s write our first index for the vendor model. This will index the vendor name and rating. We will use rating as a parameter to sort our search results for the vendor. ThinkingSphinx::Index.define :vendor, :with => :active_record do indexes name indexes rating, :sortable => true end Now, while searching for products and stores, we need vendor name to be a common criteria for each search. So, if we need to search for a product called “Batman Action Figure” in the vendor “Marvel Toys”, we could search for it using the vendor name and find all the products related to it. Here is how it is done: ThinkingSphinx::Index.define :vendor, :with => :active_record do indexes name, :as => vendor_name indexes rating, :sortable => true end Inside our other indexes, the associations are defined as: shop_index.rb ThinkingSphinx::Index.define :shop, :with => :active_record do indexes name, description, location has vendor(:name), :as => :vendor_name end product_index.rb ThinkingSphinx::Index.define :product, :with => :active_record do indexes name, description indexes price, :sortable => true has shop.vendor.name, :as => :vendor_name end In both the files above, we have called vendor_name using associations. Shop belongs to a vendor, so we could make a direct call from vendor and call it vendor_name, whereas in product, we called it via the shop association. Running and Generating the Index Once, we’re done with writing the indexes in our files, we would need to generate an index and run our Sphinx server. $ rake ts:index $ rake ts:start Searching Once our Thinking Sphinx is up and running, we can write controller methods to search and display the results. Running search on individual models looks like this: @search_products = Product.search(params[:search], :ranker => :proximity, :match_mode => :any) If you want to create an application wide search, you can call the ThinkingSphinx.search method to define models to be searched. You can tie this to any route and pass the search term as a parameter. def search @search = ThinkingSphinx.search(params[:search], :classes => [ Vendor, Store, Product], :ranker => :bm25, :match_mode => :any, :order => '@weight DESC', :page => params[:page], :per_page => 10) end Ranking uses different algorithms like bm25 and proximity for generating best matches within the search results. Sorting uses an order field and can be defined to sort the results in different ways. Based on rating, alphabetical, or created_at are just some of the ways it can be sorted. @weight is a default keyword that contains Sphinx ranking value. Other Stuff Field Weights : We can rank our search results according to different fields inside a particular model: @search_products = Product.search(params[:search], :ranker => :proximity, :match_mode => :any, :field_weights => {:description => :15, :name => 10}) You can also write field weights inside your index files using the set_property rule like this: :set_property :field_weights => {:description => 15, :name => 10}) Getting excerpts from the search results: @excerpter = ThinkingSphinx::Excerpter.new 'product_core', params[:search], { :before_match => '<span class="match">', :after_match => '</span>', :chunkseparator => ' … '} Adding Facets : Facet-based search is used when you need to filter according to different classes or parameters. Facet definition can be done by simply defining a facet => true rule against the attribute to facet in the index file. indexes name, :facet => true This and then just rebuild the index. rake ts:rebuild In your controller, facet accepts the same parameters as search, so your facet would look like this : @facets = ThinkingSphinx.facets(params[:search], :class_facet => false, :page => params[:page], :per_page => 10) If no facets are defined on any model and a facet search is written, it would fall back to class facets, calling the search on individual model classes. You can turn it off by calling false inside your facet rule, as shown above. You can display the facet results in your view in the following way: <% @facets[:class].each do |option, count|%> <%= link_to "#{option} (#{count})", :params => { :facet => option, :page => 1}%> <%end%><br/> Searching for partial words can be done using min_infix_len inside your thinking_sphinx.yml or inside your index file using set_property. This means it will match at the least 3 characters before declaring it a match. min_infix_len is not advisable to be kept at 1, as it could be a serious memory hog. development: mem_limit: 128M min_infix_len: 3 test: mem_limit: 128M min_infix</em>len: 3 production: mem_limit: 128M min_infix_len: 3 Delta Indexes Sphinx, by default, runs indexes from scratch everytime you run and index command. In order to avoid Sphinx starting from scratch, we can define delta indexes. This will only index the documents that are newly created. set_property :delta => true Conclusion Thinking Sphinx 3.0 brings along a lot of advancements and bug fixes from previous versions. It takes a very clean approach, placing the search code outside your app models. Therefore, as queries start getting complex, the code remains readable. Hopefully, this article has inspired you to give Thinking Sphinx a try in your application.
https://www.sitepoint.com/app-search-with-thinking-sphinx-3-0/
CC-MAIN-2018-26
refinedweb
1,346
63.09
Python 3 and pandas , a data analysis toolkit for Python that's widely used in the scientific and business communities. To install pandas, see the instructions on the pandas website. You'll also need OpenPyXL , a third-party library that pandas uses for reading and writing Excel files. To install it, see the instructions on the OpenPyXL website. Sections covered in the tutorial: A note about the code examples : Some lines of code in the examples may wrap to the next line because of the article's page width. When copying the examples in this tutorial, ignore the line wrapping. Line breaks matter in Python. Python . For all the possible data you can retrieve from your Zendesk product, see the "JSON Format" tables in the API docs . Most APIs have a "List" endpoint for getting multiple records. Let's say you retrieved all the posts in a community topic and sideloaded the users who wrote the posts. The resulting data structure in Python usually mirrors the JSON data returned by the API. In this case, it would consist of a Python dictionary containing one list of posts and one list of users. Each item in the lists would consist of a dictionary Python, you can use the built-in pickle module to serialize and deserialize complex data structures such as your dictionary of posts and users. See Serialize the data to reuse it in the tutorial mentioned above. In your script, the first step is to get the API data and assign it to a variable. Create a file named write_posts.py and paste the following code in it: import pandas as pd topic = pd.read_pickle('my_serialized_data') The serialized data is read from the my_serialized_data file, reconstituted as a dictionary, and assigned to a variable named topic . Tip : The code assumes the pickle file is in the same folder as the script. If it's in another folder, import the built-in os library and use it to specify the file path: import os import pandas as pd topic = pd.read_pickle(os.path.join('..', 'pickle_jar', 'my_serialized_data')) Munge the data An Excel worksheet consists of a 2-dimensional table of rows and columns. Unfortunately, your data isn't in a neat 2-dimensional structure that can be easily written to Excel. It's in a dictionary consisting of a list of posts and a list of users. Each item in the lists consists of a dictionary of properties. See Get the data from the API above for the structure. The data also includes a lot of extra information you don't want in your Excel file. For example, each record contains all the attributes listed in the Posts API doc . You want only the following data about each post: - post id - title of the post - date created - name of the person who created it This section teaches you how to munge your complex dictionary into a 2-dimensional data structure with 4 columns. It uses pandas DataFrames to do the job. A DataFrame is a fundamental, 2-dimensional data structure in pandas. You can think of it as a spreadsheet or a SQL table. Topics covered: - Create the DataFrames - Convert the ISO 8601 date strings - Merge the DataFrames - Clean up after the merge The section only scratches the surface of how you can use pandas to munge data. To learn more, see the pandas docs . Create the DataFrames Add the following lines to your script to convert the posts and users lists in your topic dictionary into 2 DataFrames: posts_df = pd.DataFrame(topic['posts'], columns=['id', 'title', 'created_at', 'author_id']) users_df = pd.DataFrame(topic['users'], columns=['id', 'name']) The DataFrame() method in each statement takes the list data from the topic dictionary as its first argument. The columns parameter specifies the keys of the dictionaries in the list to include as columns in the resulting DataFrame. For more information, see DataFrame in the pandas docs. You can view the DataFrames created in memory by adding the following temporary print statements: print(posts_df) print(users_df) Save the file. In your command line tool, navigate to the folder with the script and run the following command: $ python3 write_posts.py Your data should be written to the console. Additional columns wrap if they don't fit the display width. If you're satisfied everything is working as expected, delete the temporary print statements. Convert the ISO 8601 date strings Sometimes you have to clean up data for analysis. For example, the 'created_at' dates returned by the API are ISO 8601 format strings such as '2015-08-13T16:38:39Z' . OpenPyXL, the library pandas uses to work with Excel files, writes these dates to Excel as strings. Once they're in Excel, however, you can't easily reformat the strings as dates. OpenPyXL does write Python date objects as custom formatted dates in Excel. So if you need to use the date format in Excel for your analysis, you could convert each string in the 'created_at' column into a Python date object. You can use the apply() method of the column object to specify a Python lambda expression that modifies the data in each row of the column. A lambda expression is a one-line mini function. Modify your script as follows to import the build-in dateutil.parser library and then use it to convert the 'created_at' strings. Ignore the line break caused by the right margin. The statement should be on a single line. import dateutil.parser ... # rest of script posts_df['created_at'] = posts_df['created_at'].apply(lambda x: dateutil.parser.parse(x).date()) The conversion statement works as follows: The expression posts_df['created_at']selects the column in the DataFrame The lambda expression in the apply()method converts each ISO 8601 string in the column into a Python dateobject. It basically says, "For the data in each row, which I'll call x, make the following change to x" The dateutil parser converts the ISO 8601 date string into a datetimeobject. Next, the date()method converts the datetimeinto a dateobject The resulting column is assigned back to the 'created_at' column in posts_df Merge the DataFrames The posts_df DataFrame contains most of the data you want to write to Excel, including the 'id', 'title', and 'created_at' columns. However, the 'author_id' column only lists user ids, not actual user names. The associated user names are contained in users_df , which was derived from sideloading users with the API. In the same way you can join two tables in SQL using a common key in both tables, you can merge two DataFrames using a common key in both DataFrames. The common key in your DataFrames is the user id, which is named 'author_id' in posts_df and 'id' in users_df . Add the following statement to merge the DataFrames: merged_df = pd.merge(posts_df, users_df, how='left', left_on='author_id', right_on='id') The merge() method joins the two DataFrames using user ids as the common key ( left_on='author_id', right_on='id' ). A 'left' merge ( how='left' ) is the same as a left join in SQL. It returns all the rows from the left DataFrame, posts_df , including rows that don't have matching key values in users_df . Because you're using users_df as a lookup table, make sure it doesn't have any duplicate records. The users_df DataFrame is made up of sideloaded data from the API. Sideloaded data may contain duplicate records because the same record may be saved many times during pagination. To remove duplicate records, you can modify the users_df variable declaration as follows (in bold ): users_df = pd.DataFrame(topic['users'], columns=['id', 'name']).drop_duplicates(subset=['id']) The drop_duplicates() method looks at the values in the DataFrame's 'id' column and deletes any row with a duplicate id. Clean up after the merge The two original DataFrames have a column named 'id'. You can't have two columns with the same name in the merged DataFrame, so pandas adds a '_x' and a '_y' suffix to the overlapping column names. For example, if you added the following temporary statement to the script: print(list(merged_df)) and then ran the script, the following list of column names would be printed in the console: ['id_x', 'title', 'created_at', 'author_id', 'id_y', 'name'] Because DataFrame column names are used as column headings in an Excel workbook, you decide to rename the 'id_x' column to 'post_id' as follows: merged_df.rename(columns={'id_x': 'post_id'}, inplace=True) The merged DataFrame also includes the 'id_y' and 'author_id' columns that you don't want in your Excel file. You can drop the columns with the following statement: merged_df.drop(['id_y', 'author_id'], axis=1, inplace=True) The axis=1 argument specifies that you're referring to a column, not a row. Write the data to Excel After you're done munging the data, you can write the data to Excel as follows: merged_df.to_excel('topic_posts.xlsx', index=False) print('Spreadsheet saved.') The index=False argument prevents the to_excel() method from creating labels for the rows in Excel. Save the file. In your command line tool, navigate to the folder with the script and run the following command: $ python3 write_posts.py Check for the topic_posts.xlsx file in the folder containing your script and open it in Excel. It should contain your post data. Hi Charles, Thanks for another awesome article. I pulled 'Ticket Metrics' data instead of 'Posts' in your example and it worked great. The only weird thing is that up until October, 2015 # of created/solved tickets is consistent with what I see in GoodData, but starting in September, 2015 and prior the numbers are off (much smaller # of created and no data at all on solved tickets). I'm not getting any error messages on hitting the rate limit etc. Do you know what can be causing this? Thanks a lot! Viola Please sign in to leave a comment.
https://help.zendesk.com/hc/en-us/articles/229137027-Writing-large-data-sets-to-Excel-with-Python-and-pandas
CC-MAIN-2017-51
refinedweb
1,638
63.49
November 03, 2007 A Value Proposition by Gary Tanashian As the rot in Wall Street's dark alleys works its way from the inside out, from the seediest hedge funds' leveraged 'investment' vehicles to Main Street's financial institutions (pensions, 401K's, savings, etc.) gold has taken center stage, closing above $800 for the first time in its still young bull market. Fear and anxiety are increasing as the US Dollar falls further below serious long term support and in this environment, gold is an emotional conduit through which growing fears of fiat monetary instability pass. Picture a burning building with a limited number of exits and a large crowd trying to pile through the door. Let's call it a... oh I don't know... let's call it a casino. Gold is the object of many strange and varied perceptions, perhaps because it is an ancient asset that has always stirred basic human instincts for wealth, good fortune and even survival. But in light of the perverted and multi-headed monster we call a financial system - with seemingly infinite instruments of 'profit' limited only by the imagination of financial engineers - perceptions toward gold have become distorted, helped by an enabling Wall Street and mainstream financial media. The main point to remember is that gold does nothing; it just sits there and does not care about the crazy gyrations going on all around it. But to understand and accept this, casino patrons must first accept that the metrics they have been schooled in and the rules they have been taught over the fiat decades to play by are not applicable. Filling the void that this lack of understanding creates is a whole host of opinions, many disparaging and/or dismissive. Others simply attempt to fit this "asset class" into conventional metrics. The inspiration for this missive was a recent SeekingAlpha piece by Brad Zigler called All That Glitters May Not Be So Golden. Mr. Zigler did not write a 'hatchet piece' on gold but what I find interesting is his and many other financial media correspondents' analysis of gold as a return (or lack thereof) instrument. Gold pays no risk premium as it carries no default risk. But in the world of financial media-fed perceptions that is a bad thing. No return you say? No markup? No leverage? Who needs that?! Gold is about value and nothing more in my opinion. That is why I refuse to get excited when its fiat currency denominated price goes up and why I also remain at a normal pulse rate when said 'price' declines sharply. I do agree that when trading or investing in the gold miners (as I do) it is important to keep traditional metrics in mind. But the miners are my casino of choice and I most certainly do not see the gold miners as gold, a gold equivalent or anything other than a potentially hugely leveraged play on an enduring asset of value. Back in the real world, players are just beginning to get the hint that the risk they have taken on in the hunt for return in some very dark corners has come at a price and the price is a massive debit against the entire system of something for leveraged nothing. Yes, gold pays no premium but neither is it subject to this debit because it never went anywhere to begin with. It Is What It Is (this is the credo by which the website was created) and as a barometer of global financial sentiment its exchange value is rising versus a whole host of paper promises not to mention many hard assets. So what many investors now need is a sort of 12 step program as they attempt to 'put down the crack pipe' and come to an understanding that real value has nothing to do with return (unlike modern portfolio and asset allocation theory) and it certainly has nothing to do with leverage. Mr. Zigler's assertions and my responses: Debate has raged for some time now about the utility of gold in a portfolio. Forget, for a moment, the breathless claims of infomercial touts and Parade magazine advertisers. Think, instead, of asset class selection. Why should anyone add gold -- or, for that matter, any asset -- to a portfolio? The answer that comes immediately to many people's minds is "return." It's the promise of outsized, and often outlandish, returns that entices people to call that 800 number in the wee hours of the morning to get their hands on the yellow metal. There should be no debate. An asset of historic value belongs in a portfolio if debt obligations (bonds) and calls on corporate earnings (stocks) belong there. I agree, the 800 number pitch men are seedy characters capitalizing on fear and insecurity, but why are they part of the conversation? Have you ever seen the movie Boiler Room? The world of stock scams dwarfs that of unscrupulous precious metals dealers. Gold isn't the end-all, be-all, however. In the long term, the metal's price is notoriously unstable. Since gold's price was allowed to float in 1970, its annualized standard deviation -- its price variance -- has been clocked at nearly 20 percent, versus 15 percent for blue-chip stocks. And in that time, gold's return has only averaged 8 percent. The S&P 500 earned 11 percent per year. 'do we remain on the upside or have the secular changes beginning in and around 2000 marked a decided switch to the inevitable payment to the piper (of the debt used to keep the dream alive)?' If you think there is still productive upside, you will see gold's 'return' as sub-par. If you believe that secular changes are at hand, you are looking for that exit door in a crowded casino and you don't give a damn about return. You want to stay whole. So what return can we expect from gold? Well, financial theory says you can't expect any increase in an asset's value without growth prospects. Stocks' expected return derives from earnings growth. Issuers of corporate securities can create things and grow. There's a real prospect for a company trading its shares or warrants to be worth more and more as the result of management decisions. Gold itself doesn't produce earnings, and for that reason its expected return can be approximated as zilch. Nada. Bupkis. Mr. Zigler is correct. Gold provides no 'return' in the modern asset allocation theory sense of the word. But in bringing the word 'value' into the equation he again shows how modern portfolio theorists are trained; no return, no 'growth' =.. »
http://www.safehaven.com/article-8755.htm
crawl-001
refinedweb
1,117
60.14
In the first and second installments of Functional thinking, I surveyed some functional programming topics and how they relate to Java™ and its related languages. This installment continues this exploration, showing a Scala version of the number classifier from previous installments and discussing some academia-tinged topics such as currying, partial application, and recursion. Number classifier in Scala I've been saving a Scala version of the number classifier for last because it's the one with the least syntactic mystery, at least for Java developers. (Recapping the classifier's requirements: Given any positive integer greater than 1, you must classify it as perfect, abundant, or deficient. A perfect number is a number whose factors, excluding the number itself as a factor, add up to the number. An abundant number's sum of factors is greater than the number, and a deficient number's sum of factors is less.) Listing 1 shows the Scala version: Listing 1. Number classifier in Scala package com.nealford.conf.ft.numberclassifier object NumberClassifier { def isFactor(number: Int, potentialFactor: Int) = number % potentialFactor == 0 def factors(number: Int) = (1 to number) filter (number % _ == 0) def sum(factors: Seq[Int]) = factors.foldLeft(0)(_ + _) def isPerfect(number: Int) = sum(factors(number)) - number == number def isAbundant(number: Int) = sum(factors(number)) - number > number def isDeficient(number: Int) = sum(factors(number)) - number < number } Even if you've never seen Scala until now, this code should be quite readable. As before, the two methods of interest are factors() and sum(). The factors() method takes the list of numbers from 1 to the target number and applies Scala's built-in filter() method, using the code block on the right-hand side as the filtering criterion (otherwise known as a predicate). The code block takes advantage of Scala's implicit parameter, which allows a placeholder with no name (the _ character) when a named variable isn't needed. Thanks to Scala's syntactic flexibility, you can call the filter() method the same way you call an operator. If you prefer, (1 to number).filter((number % _ == 0)) also works. The sum() method uses the by-now familiar fold left operation (in Scala, implemented as the foldLeft() method). I don't need to name the variables in this case, so I use _ as a placeholder, which leverages the simple, clean syntax for defining a code block. The foldLeft() method performs the same task as the similarly named method from the Functional Java library (see Resources), which appeared in the first installment: - Take an initial value and combine it via an operation on the first element of the list. - Take the result and apply the same operation to the next element. - Keep doing this until the list is exhausted. This is a generalized version of how to apply an operation such as addition to a list of numbers: start with zero, add the first element, take that result and add it to the second, and continue until the list is consumed. Unit testing Even though I haven't shown the unit tests for previous versions, all the examples have tests. An effective unit-testing library named ScalaTest is available for Scala (see Resources). Listing 2 shows the first unit test I wrote to verify the isPerfect() method from Listing 1: Listing 2. A unit test for the Scala number classifier @Test def negative_perfection() { for (i <- 1 until 10000) if (Set(6, 28, 496, 8128).contains(i)) assertTrue(NumberClassifier.isPerfect(i)) else assertFalse(NumberClassifier.isPerfect(i)) } But like you, I'm trying to learn to think more functionally, and the code in Listing 2 bothered me in two ways. First, it iterates to do something, which exhibits imperative thinking. Second, I don't care for the binary catch-all of the if statement. What problem am I trying to solve? I need to make sure that my number classifier doesn't identify an imperfect number as perfect. Listing 3 shows the solution to this problem, stated a little differently: Listing 3. Alternate test for perfect-number classification @Test def alternate_perfection() { assertEquals(List(6, 28, 496, 8128), (1 until 10000) filter (NumberClassifier.isPerfect(_))) } Listing 3 asserts that the only numbers from 1 to 100,000 that are perfect are the ones in the list of known perfect numbers. Thinking functionally extends not just to your code, but to the way you think about testing it as well. Partial application and currying The functional approach I've shown to filtering lists is common across functional programming languages and libraries. Using the ability to pass code as a parameter (as to the filter() method in Listing 3) illustrates thinking about code reuse in a different way. If you come from a traditional design-patterns-driven object-oriented world, compare this approach to the Template Method design pattern from the Gang of Four Design Patterns book (see Resources). The Template Method pattern defines the skeleton of an algorithm in a base class, using abstract methods and overriding to defer individual details to child classes. Using composition, the functional approach allows you to pass functionality to methods that apply that functionality appropriately. Another way to achieve code reuse is via currying. Named after mathematician Haskell Curry (for whom the Haskell programming language is also named), currying transforms a multi-argument function so that it can be called as a chain of single-argument functions. Closely related is partial application, a technique for assigning a fixed value to one or more of the arguments to a function, thereby producing another function of smaller arity (the number of parameters to the function). To understand the difference, start by looking at the Groovy code in Listing 4, which illustrates currying: Listing 4. Currying in Groovy def product = { x, y -> return x * y } def quadrate = product.curry(4) def octate = product.curry(8) println "4x4: ${quadrate.call(4)}" println "5x8: ${octate(5)}" In Listing 4, I define product as a code block accepting two parameters. Using Groovy's built-in curry() method, I use product as the building block for two new code blocks: quadrate and octate. Groovy makes calling a code block easy: you can either explicitly execute the call() method or use the supplied language-level syntactic sugar of placing a set of parentheses containing any parameters after the code-block name (as in octate(5), for example). Partial application is a broader technique that resembles currying but does not restrict the resulting function to a single argument. Groovy uses the curry() method to handle both currying and partial application, as shown in Listing 5: Listing 5. Partial application vs. currying, both using Groovy's curry() method)}" The volume code block in Listing 5 computes the cubic volume of a rectangular solid using the well-known formula. I then create an area code block (which computes a rectangle's area) by fixing volume's first dimension ( h, for height) as 1. To use volume as a building block for a code block that returns the length of a line segment, I can perform either partial application or currying. lengthPA uses partial application by fixing each of the first two parameters at 1. lengthC applies currying twice to yield the same result. The difference is subtle, and the end result is the same, but if you use the terms currying and partial application interchangeably within earshot of a functional programmer, count on being corrected. Functional programming gives you new, different building blocks to achieve the same goals that imperative languages accomplish with other mechanisms. The relationships among those building blocks are well thought out. Earlier, I showed composition as a code-reuse mechanism. It shouldn't surprise you that you can combine currying and composition. Consider the Groovy code in Listing 6: Listing 6. Partial-application composition def composite = { f, g, x -> return f(g(x)) } def thirtyTwoer = composite.curry(quadrate, octate) println "composition of curried functions yields ${thirtyTwoer(2)}" In Listing 6, I create a composite code block that composes two functions. Using that code block, I create a thirtyTwoer code block, using partial application to compose the two methods together. Using partial application and currying, you achieve similar goals to mechanisms like the Template Method design pattern. For example, you can create an incrementer code block by building it atop an adder code block, as shown in Listing 7: Listing 7. Different building blocks def adder = { x, y -> return x + y } def incrementer = adder.curry(1) println "increment 7: ${incrementer(7)}" Of course, Scala supports currying, as illustrated by the snippet from the Scala documentation shown in Listing 8: Listing 8. Currying in Scala object CurryTest extends Application { def filter(xs: List[Int], p: Int => Boolean): List[Int] = if (xs.isEmpty) xs else if (p(xs.head)) xs.head :: filter(xs.tail, p) else filter(xs.tail, p) def dividesBy(n: Int)(x: Int) = ((x % n) == 0) val nums = List(1, 2, 3, 4, 5, 6, 7, 8) println(filter(nums, dividesBy(2))) println(filter(nums, dividesBy(3))) } The code in Listing 8 shows how to implement a dividesBy() method used by a filter() method. I pass an anonymous function to the filter() method, using currying to fix the first parameter of the dividesBy() method to the value used to create the code block. When I pass the code block created by passing my target number as a parameter, Scala curries up a new function. Filtering via recursion Another topic closely associated with functional programming is recursion, which (according to Wikipedia) is the "process of repeating items in a self-similar way." In reality, it's a computer-sciencey way to iterate over things by calling the same method from itself (always carefully ensuring you have an exit condition). Many times, recursion leads to easy-to-understand code because the core of your problem is the need to do the same thing over and over to a diminishing list. Consider filtering a list. Using an iterative approach, I accept a filtering criterion and loop over the contents, filtering out the elements I don't want. Listing 9 shows a simple implementation of filtering with Groovy: Listing 9. Filtering in Groovy def filter(list, criteria) { def new_list = [] list.each { i -> if (criteria(i)) new_list << i } return new_list } modBy2 = { n -> n % 2 == 0 } l = filter(1..20, modBy2) println l The filter() method in Listing 9 accepts a list and a criteria (a code block specifying how to filter the list) and iterates over the list, adding each item to a new list if it matches the predicate. Now look back at Listing 8, which is a recursive implementation of the filtering functionality in Scala. It follows a common pattern in functional languages for dealing with a list. One view of a list is that it consists of two parts: the item at the front of the list (the head), and all the other items. Many functional languages have specific methods to iterate over lists using this idiom. The filter() method first checks to see if the list is empty — the critically important exit condition for this method. If the list is empty, simply return. Otherwise, use the predicate condition ( p) passed as a parameter. If this condition is true (meaning I want this item in my list), I return a new list constructed by taking the current head and a filtered remainder of the list. If the predicate condition fails, I return a new list that consists of just the filtered remainder (eliminating the first element). The list-construction operators in Scala make the return conditions for both cases quite readable and easy to understand. My guess is that you don't use recursion at all now — it's not even a part of your tool box. However, part of the reason lies with the fact that most imperative languages have lackluster support for it, making it more difficult to use than it should be. By adding clean syntax and support, functional languages make recursion a candidate for simple code reuse. Conclusion This installment completes my survey of features in the functional-thinking world. Coincidentally, much of this article was about filtering, showing lots of ways to use it and implement it. But this isn't too much of a surprise. Many functional paradigms are built around lists because much of programming boils down to dealing with lists of things. It makes sense to create languages and frameworks that have supercharged facilities for lists. In the next installment, I'll talk in depth about one of functional programming's building blocks: immutability. Resources Learn - The Productive Programmer (Neal Ford, O'Reilly Media, 2008): Neal Ford's most recent book discusses tools and practices that help you improve your coding efficiency. - Scala: Scala is a modern, functional language on the JVM. - Functional Java: Functional Java is a framework that adds many functional language constructs to Java. - The busy Java developer's guide to Scala: Dig more deeply into Scala in this developerWorks series by Ted Neward. - "Practically Groovy: Functional programming with curried closures" (Ken Barclay et al., developerWorks, August 2005): Read more about functional programming with Groovy. -. Get products and technologies - ScalaTest: ScalaTest is a unit-testing library for Scala and Java.
http://www.ibm.com/developerworks/library/j-ft3/index.html
CC-MAIN-2014-35
refinedweb
2,204
52.9
Whew! That was a long title. Also, the code can work with any SQL Server database or other database you want to use to create a nested treeview. Project Files Here. My client, a construction company, needs a Web based treeview that emulates the Treeview and organization seen in Quickbooks where you have a Customer record and jobs beneath them. You can also have sub-jobs or in their case, change orders. For instance: ABC Company Job 1001: Office Construction Job 1050: Los Angeles Store front 1050.001: Room Addition XYZ Company Job 1020: Hotel Rooms 1020.002: Custom Bathroom/Jacuzzi Tubs And so on. There is the Customer record, a job number, and then any number of change orders. To simplify things, I’ve created a table with just the fields necessary to create the nested treeview above. I’ve removed the Quickbooks specific fields that are used to create the nested treeview (ListID, and ParentID). We will use the table’s identity integer to create our nested relationships. I’ll explain the Quickbooks integration later. The key fields in the database for this to work are: Table: tblProjects project_uno (integer, identity, key) CoProjName (string) - The Company name from Quickbooks. ProjNumber (string) - The job number from Quickbooks Parent_cd (integer) - The Customer and Job Records are in the same table. The Parent_cd is either set to 0 – a top-level Customer record – or set to the project_uno of its parent. In the above example, the following would be true. ABC Company & XYZ Company would have a unique project_uno. Their parent_cd would be equal to 0. Job 1001 and 1050 would have their own unique project_uno and their parent_cd would be equal to the project_uno of ABC Company. In turn, the change order record, 1050.001, would have a unique project_uno and a Parent_cd equal to the project_uno of Job 1050. For instance: Project_uno CoProjName ProjNumber parent_cd 1 ABC Company - 0 2 Office Const.. 1001 1 3 Los Angeles St.. 1050 1 4 Room Addition 1050.001 2 The ASP.NET Page On my asp.net page, I create 3 server controls. asp:Button ID: btnShowTree (to run the code that creates the treeview) asp:Literal ID: someinfo (used to display the value from a selected node in our treeview) asp:TreeView ID: thelist (our Treeview Control) Building the Treeview from Code A treeview is made up of Nodes and childNodes. Every top level item listed is a node and any sub-level item listed is a childnode. In our data above, ABC Company is a node. Job 1001 and 1050 are a childNodes of the ABC Company node. Job 1050.001 is a childnode of the childnode for Job 1050. Node Note: I would rather MS have implemented everything as nodes – ie: a childnode should not need to be referred to as a childnode. It is a childnode because it is a node added to another node. It would have made the code even simpler. To create the nodes and childnodes I used two basic routines. One to build the top level nodes and one to build the childnodes. The childnode subroutine is called recursively to address any sub-level childnodes. Some Basics Before we look at the code, let’s understand a little bit about creating Nodes and childnodes. When creating a brand new set of nodes and sub-nodes, here is some of the code. First.. I am starting with an empty node on my page. You can create the treeview in code as well but I don't. Let’s create a parent (top-level) node. //first clear any nodes from the treeview at the start. thelist.Nodes.Clear(); // create a new node object named “pn” TreeNode pn = new TreeNode(); //the next two lines set set the text and the underlying value of the node pn.Text = “ABC Company”; //strconame – variable to used in the actual code pn.Value = “0”; //strvalue – variable to be used in the actual code //Set the URL to a non-active link. This makes the node non-selectable and // simply a container for childNode (job data). This is what I want for my application pn.NavigateUrl = “#”; //add the node to the treeview on my page. thelist.Nodes.Add(pn); That’s it.. You’ve now added a new top-level node. Creating a sub-node In my code, I pass the above created node to a sub-routine. However, the following shows the code to create a child node using the node “pn” above. //create a node object – same as a parent node TreeNode cn = new TreeNode(); //fill in the text and the value of the node object cn.Text = “1001: Office Construction”; //strJobNo + ": " + strJobName are the variables I will use in my actual code cn.Value = “4”; //strvalue is the variable I will use – this is the project_uno value; //add the child node to the previously created node (parent node) pn.ChildNodes.Add(cn); That creates a single node and a child of that node. If you created a new treenode and then added it as a child to the node object, “cn”, you would have 3rd level of nodes. Getting Recursive In order to create any level of childnodes, the procedure that creates child nodes will call itself to look for any child nodes for the node it is creating. Be sure you close/cleanup your connection, command, and datareader objects.. or disaster will occur. Your Environment/namespaces My aspx page is named, treeviewdb.aspx and the c# code-behind page is treeviewdb.aspx.cs In addition to the default namespaces, I include: using System.Data; //needed to access dataobjects using System.Data.SqlClient; //for my sql connection and reader using System.Configuration; // to access my connection string in web.config I want to access my data connection in web.config because it is more maintainable/flexible than having connection strings defined wherever they are used. If you change database names, servers, or users, you’ll be happy you did this. GetParentJobs This… hmm.. I probably don’t need to tell you what this does. ====================== protected void GetParentJobs() { //get records that have NO parent – a parent_cd of 0. string strSQL = "Select * from tblProjects where Parent_cd = 0 order by CoProjName"; /* the next 5 lines retrieve your connection string create your connection object open your connection create the command object create your datareader (your recordset) */ your variables – I don’t need to stuff values but I like to. string strconame = ""; string strvalue = ""; string strURL = "#"; // loop through your data reader as long as there are records. // I then create a treenode, set my variables to values from the database, // and add those values to the node object. while (r.Read()) { TreeNode pn = new TreeNode(); strconame = "" + (string)r["CoProjName"].ToString(); strvalue = "" + (string)r["project_uno"].ToString(); pn.Text = strconame; pn.Value = strvalue; pn.NavigateUrl = strURL; thelist.Nodes.Add(pn); // this is the subroutine to create child nodes. I pass it the current nodes’ // project_uno value. It will be used to find any records whose parent_cd match this value // I also pass it the current node GetChildJobs(strvalue, pn); } //cleanup your datareader, command, and connection. r.Close(); cmdProj.Cancel(); cxn.Close(); } GetChildJobs And this accordingly does what it says too. protected void GetChildJobs(string inParent, TreeNode innd) { //a sql string to retrieve project records with the parent_cd equal to the parent_uno passed to the subroutine. string strSQL = "Select * from tblProjects where parent_cd = '" + inParent + "' order by ProjNumber"; // retrieve connection string, create your connection, command, and datareader objects variables string strvalue = ""; string strparent_cd = ""; string strJobNo = ""; string strJobName = ""; // loop through your datareader while (r.Read()) { //create a treenode object, fill variables from the datareader, // and set text and value of your node object.; // add the created node to the node you passed to this routine. innd.ChildNodes.Add(cn); GetChildJobs(strvalue, cn); } // close all the data things... r.Close(); cmdProj.Cancel(); cxn.Close(); } And that is basically it. I have a couple other sub-routines. I have one that I call from the button that calls the GetParentJobs subroutine. I could have just called it when the page loads but I want a little more control than that for testing. I also created a sub-routine that retrieves the text and the value from a selected childnode and displays I in the literal I’ve included on the page. You can retrieve the page and a text file with some notes here. But what about Quickbooks Ahh yes.. I use this same sub-routine with a project where we are using Quickbooks data. So.. same sub-routines but some differences. Quickbooks ListID and Parent ListID First, while I still have a project_uno, and I use that to set the value of a given node, I do not use it in deriving my tree structure. Instead, I synchronize (pull) data from Quickbooks into SQL. In Quickbooks, every customer and job - which are really the same object, have a ListID and potentially a ParentRef/ListID. The ListID takes the place of the project_uno and the ParentRef/ListID takes the place of the parent_cd. In quickbooks, a sub-job has a unique ListID and the ParentRef/ListID is equal to the ListID of a company file or job (in the case of change orders). The big trick is, of course, connecting to and synchronizing Customer and Job data from Quickbooks. But that is a tale for another time. If you have questions, please leave a comment on the blog or email me at info [@] Matthew Moran Online [.] com (remove spaces and brackets – sorry, I’m avoiding spam).
http://it.toolbox.com/blogs/matthewmoran/creating-nested-node-and-childnodes-using-aspnet-sql-server-quickbooks-data-and-the-microsoft-treeview-control-54231
CC-MAIN-2014-52
refinedweb
1,595
66.13
This page explains what Spot VMs are and how they work in Google Kubernetes Engine (GKE). To learn how to use Spot VMs, refer to Use Spot VMs. Overview of Spot VMs in GKE Spot VMs are Compute Engine virtual machine (VM) instances that are priced lower than standard Compute Engine VMs. Spot VMs offer the same machine types and options as standard VMs, but provide no availability guarantees. You can use Spot VMs in your clusters and node pools to run stateless, batch, or fault-tolerant workloads that can tolerate disruptions caused by the ephemeral nature of Spot VMs. Spot VMs remain available until Compute Engine requires the resources for standard VMs. To maximize your cost efficiency, combine using Spot VMs with Best practices for running cost-optimized Kubernetes applications on GKE. To learn more about Spot VMs, see Spot VMs in the Compute Engine documentation. Benefits of Spot VMs Spot VMs and preemptible VMs share many benefits, including the following: - Lower pricing than standard Compute Engine VMs. - Useful for stateless, fault-tolerant workloads that are resilient to the ephemeral nature of these VMs. - Works with the cluster autoscaler and node auto-provisioning. In contrast to preemptible VMs, which expire after 24 hours, Spot VMs have no expiration time. Spot VMs are only terminated when Compute Engine needs the resources elsewhere. How Spot VMs work in GKE When you create a cluster or node pool with Spot VMs, GKE creates underlying Compute Engine Spot VMs that behave like a managed instance group (MIG). Nodes that use Spot VMs behave like standard GKE nodes, but with no guarantee of availability. When the resources used by Spot VMs are required to run standard VMs, Compute Engine terminates those Spot VMs to use the resources elsewhere. Termination and graceful shutdown of Spot VMs When Compute Engine needs to reclaim the resources used by Spot VMs, a termination notice is sent to GKE. Spot VMs terminate 30 seconds after receiving a termination notice. On clusters running GKE version 1.20 and later, the kubelet graceful node shutdown feature is enabled by default. The kubelet notices the termination notice and gracefully terminates Pods that are running on the node. If the Pods are part of a Deployment, the controller creates and schedules new Pods to replace the terminated Pods. The kubelet grants non-system Pods 25 seconds to gracefully terminate, after which system Pods (with the system-cluster-critical or system-node-critical priority classes) have five seconds to gracefully terminate. During graceful Pod termination, the kubelet assigns a Failed status and a Shutdown reason to the terminated Pods. When the number of terminated Pods reaches a threshold of 1000, garbage collection cleans up the Pods. You can also delete shutdown Pods manually using the following command: kubectl get pods --all-namespaces | grep -i shutdown | awk '{print $1, $2}' | xargs -n2 kubectl delete pod -n Scheduling workloads on Spot VMs GKE automatically adds the cloud.google.com/gke-spot=true label to nodes that use Spot VMs. You can schedule specific Pods on nodes that use Spot VMs using the nodeSelector field in your Pod spec, like in the following example: apiVersion: v1 kind: Pod spec: nodeSelector: cloud.google.com/gke-spot: "true" Alternatively, you can use node affinity to tell GKE to schedule Pods on Spot VMs, similar to the following example: apiVersion: v1 kind: Pod spec: ... affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: cloud.google.com/gke-spot operator: In values: - true ... You can also use nodeAffinity.preferredDuringSchedulingIgnoredDuringExecution to prefer that GKE places Pods on nodes that use Spot VMs. Preferring Spot VMs is not recommended, because GKE might schedule the Pods onto existing viable nodes that use standard VMs instead. Using taints and tolerations for scheduling To avoid system disruptions, use a node taint to ensure that GKE doesn't schedule critical workloads onto Spot VMs. When you taint nodes that use Spot VMs, GKE only schedules Pods that have the corresponding toleration onto those nodes. If you use node taints, ensure that your cluster also has at least one node pool that uses standard Compute Engine VMs. Node pools that use standard VMs provide a reliable place for GKE to schedule critical system components like DNS. For information on using a node taint for Spot VMs, see Use taints and tolerations for Spot VMs. Using Spot VMs with GPU node pools Spot VMs support using GPUs. When you create a new GPU node pool, GKE automatically adds the nvidia.com/gpu=present:NoSchedule taint to the new nodes. Only Pods with the corresponding toleration can run on these nodes. GKE automatically adds this toleration to Pods that request GPUs. Your cluster must have at least one existing non-GPU node pool that uses standard VMs before you create a GPU node pool that uses Spot VMs. If your cluster only has a GPU node pool with Spot VMs, GKE doesn't add the nvidia.com/gpu=present:NoSchedule taint to those nodes. As a result, GKE might schedule system workloads onto the GPU node pools with Spot VMs, which can lead to disruptions because of the Spot VMs and can increase your resource consumption because GPU nodes are more expensive than non-GPU nodes. Cluster autoscaler and node auto-provisioning You can use the cluster autoscaler and node auto-provisioning to automatically scale your clusters and node pools based on the demands of your workloads. Both the cluster autoscaler and node auto-provisioning support using Spot VMs. Spot VMs and node auto-provisioning Node auto-provisioning automatically creates and deletes node pools in your cluster to meet the demands of your workloads. When you schedule workloads that require Spot VMs by using a nodeSelector or node affinity, node auto-provisioning creates new node pools to accommodate the workloads' Pods. GKE automatically adds the cloud.google.com/gke-spot=true:NoSchedule taint to nodes in the new node pools. Only Pods with the corresponding toleration can run on nodes in those node pools. You must add the corresponding toleration to your deployments to allow GKE to place the Pods on Spot VMs. You can ensure that GKE only schedules your Pods on Spot VMs by using both a toleration and either a nodeSelector or node affinity rule to filter for Spot VMs. If you schedule a workload using only a toleration, GKE can schedule the Pods onto either Spot VMs or existing standard VMs with capacity. If you require a workload to be scheduled on Spot VMs, use a nodeSelector or a node affinity in addition to a toleration. To learn more, see Scheduling workloads on Spot VMs. Spot VMs and cluster autoscaler The cluster autoscaler automatically adds and removes nodes in your node pools based on demand. If your cluster has Pods that can't be placed on existing Spot VMs, the cluster autoscaler adds new nodes that use Spot VMs. Default policy Starting in GKE version 1.24.1-gke.800, you can define the autoscaler location policy. Cluster autoscaler attempts to provision Spot VMs node pools when resources are available and the default location policy is set to ANY. With this policy, Spot VMs have a lower risk of being preempted. For other VM types, the default cluster autoscaler distribution policy is BALANCED. Modifications to Kubernetes behavior Using Spot VMs on GKE modifies some guarantees and constraints that Kubernetes provides, such as the following: On clusters running GKE versions prior to 1.20, the kubelet graceful node shutdown feature is disabled by default. GKE shuts down Spot VMs without a grace period for Pods, 30 seconds after receiving a preemption notice from Compute Engine. Reclamation of Spot VMs is involuntary and is not covered by the guarantees of PodDisruptionBudgets. You might experience greater unavailability than your configured PodDisruptionBudget. Best practices for Spot VMs When designing a system that uses Spot VMs, you can avoid major disruptions by using the following guidelines: - Spot VMs have no availability guarantees. Design your systems under the assumption that GKE might reclaim any or all your Spot VMs at any time, with no guarantee of when new instances become available. - There is no guarantee that Pods running on Spot VMs will shut down gracefully. GKE might not notice that the node was reclaimed until a few minutes after reclamation occurs, which delays the rescheduling of those Pods onto a new node. - To ensure that your workloads and Jobs are processed even when no Spot VMs are available, ensure that your clusters have a mix of node pools that use Spot VMs and node pools that use standard Compute Engine VMs. - Ensure that your cluster has at least one non-GPU node pool that uses standard VMs before you add a GPU node pool that uses Spot VMs. - Use the Kubernetes on GCP Node Termination Event Handler on clusters running GKE versions prior to 1.20, where the kubelet graceful node shutdown feature is disabled. The handler gracefully terminates your Pods when Spot VMs are preempted. - While the node names do not usually change when nodes are recreated, the internal and external IP addresses used by Spot VMs might change after recreation. - Use node taints and tolerations to ensure that critical Pods aren't scheduled onto node pools that use Spot VMs. - Do not use stateful Pods with Spot VMs. StatefulSets inherently have at-most-one Pod per index semantics, which preemption of Spot VMs could violate, leading to data loss. - Follow the Kubernetes Pod termination best practices. What's next - Learn how to use Spot VMs in your node pools. - Learn how to scale your deployed apps. - Learn more about Spot VMs in the Compute Engine documentation. - Take a tutorial about deploying a batch workload using Spot VMs in GKE.
https://cloud.google.com/kubernetes-engine/docs/concepts/spot-vms?hl=tr
CC-MAIN-2022-33
refinedweb
1,626
53.81
Update 5-10-2017: The first release of Visual Studio 2017 Tools for Azure Functions is now available to try. As discussed in the Visual Studio 2017 Toolspost and these 2015 tools were preview tools that provided us great feedback and learning. However, as outlined in our roadmap post, the pivot to precompiled functions with a focus on .NET Standard 2.0 means we have no plans to release any further updates to 2015 at this time. We would encourage everyone to try out the new tools for Visual Studio 2017. Today we are pleased to announce a preview of tools for building Azure Functions for Visual Studio 2015. Azure Functions provide event-based serverless computing that make it easy to develop and scale your application, paying only for the resources your code consumes during execution. This preview offers the ability to create a function project in Visual Studio, add functions using any supported language, run them locally, and publish them to Azure. Additionally, C# functions support both local and remote debugging. In this post, I’ll walk you through using the tools by creating a C# function, covering some important concepts along the way. Then, once we’ve seen the tools in action I’ll cover some known limitations we currently have. Also, please take a minute and let us know who you are so we can follow up and see how the tools are working. Getting Started Before we dive in, there are a few things to note: - These tools are offered as a preview release and will have some rough spots and limitations - They currently only work with Visual Studio 2015 Update 3 with “Microsoft Web Developer Tools” installed - You must have Azure 2.9.6 .NET SDK installed - Download and install Visual Studio Tools for Azure Functions For our sample function, we’ll create a C# function that is triggered when a message is published into a storage Queue, reverses it, and stores both the original and reversed strings in Table storage. - To create a function, go to: - File -> New Project - Then select the “Cloud” node under the “Visual C#” section and choose the “Azure Functions (Preview) project type - This will give us an empty function project. There are a few things to note about the structure of the project: - appsettings.json is where we’ll store configuration information such as connection strings It is recommended that you exclude this file from source control so you don’t check in your developer secrets. - host.json enables us to configure the behavior of the Azure Functions host - For the purposes of this blog post, we’ll add an entry that speeds up the queue polling interval from the default of once a minute to once a second by setting the “maxPollingInterval” in the host.json (value is in ms) - Next, we’ll add a function to the project, by right clicking on the project in Solution Explorer, choose “Add” and then “New Azure Function” - This will bring up the New Azure Function dialog which enables us to create a function using any language supported by Azure Functions - For the purposes of this post we’ll create a “QueueTrigger – C#” function, fill in the “Queue name” field, “Storage account connection” (this is the name of the key for the setting we’ll store in “appsettings.json”), and the “Name” of our function. Note: All function types except HTTP triggers require a storage connection or you will receive an error at run time - This will create a new folder in the project with the name of our function with the following key files: - function.json: contains the configuration data for the function (including the information we specified as part of creating the new function) - project.json (C#): is where we’ll specify any NuGet dependencies our function may have. Note: Azure functions automatically import some namespaces and assemblies (e.g. Json.NET). - run.csx: this contains the body of the function that will be executed when triggered - The last thing we need to do in order to hook up function to our storage Queue is provide the connecting string in the appsettings.json file (in this case by setting the value of “AzureWebJobsStorage”) - Next we’ll edit the “function.json” file to add two bindings, one that gives us the ability to read from the table we’ll be pushing to, and another that gives us the ability to write entries to the table - Finally, we’ll write our function logic in the run.csx file - Running the function locally works like any other project in Visual Studio, Ctrl + F5 starts it without debugging, and F5 (or the Start/Play button on the toolbar) launches it with debugging. Note: Debugging currently only works for C# functions. Let’s hit F5 to debug the function. - The first time we run the function, we’ll be prompted to install the Azure Functions CLI (command line) tools. Click “Yes” and wait for them to install, our function app is now running locally. We’ll see a command prompt with some messages from the Azure Functions CLI pop up, if there were any compilation problems, this is where the messages would appear since functions are dynamically compiled by the CLI tools at runtime. - We now need to manually trigger our function by pushing a message into the queue with Azure Storage Explorer. This will cause the function to execute and hit our breakpoint in Visual Studio. Publishing to Azure - Now that we’ve tested the function locally, we’re ready to publish our function to Azure. To do this right click on the project and choose “Publish…”, then choose “Microsoft Azure App Service” as the publish target - Next, you can either pick an existing app, or create a new one. We’ll create a new one by clicking the “New…” button on the right side of the dialog - This will pop up the provisioning dialog that lets us choose or setup the Azure environment (we can customize the names or choose existing assets). These are: - Function App Name: the name of the function app, this must be unique - Subscription: the Azure subscription to use - Resource Group: what resource group the to add the Function App to - App Service Plan: What app service plan you want to run the function on. For complete information read about hosting plans, but it’s important to note that if you choose an existing App Service plan you will need to set the plan to “always on” or your functions won’t always trigger (Visual Studio automatically sets this if you create the plan from Visual Studio) - Now we’re ready to provision (create) all of the assets in Azure. Note: that the “Validate Connection” button does not work in this preview for Azure Functions - Once provisioning is complete, click “Publish” to publish the Function to Azure. We now have a publish profile which means all future publishes will skip the provisioning steps Note: If you publish to a Consumption plan, there is currently a bug where new triggers that you define (other than HTTP) will not be registered in Azure, which can cause your functions not to trigger correctly. To work around this, open your Function App in the Azure portal and click the “Refresh” button on the lower left to fix the trigger registration. This bug with publish will be fixed on the Azure side soon. - To verify our function is working correctly in Azure, we’ll click the “Logs” button on the function’s page, and then push a message into the Queue using Storage Explorer again. We should see a message that the function successfully processed the message - The last thing to note, is that it is possible to remote debug a C# function running in Azure from Visual Studio. To do this: - Open Cloud Explorer - Browse to the Function App - Right click and choose “Attach Debugger” Known Limitations As previously mentioned, this is the first preview of these tools, and we have several known limitations with them. They are as follow: - IntelliSense: IntelliSense support is limited, and available only for C#, and JavaScript by default. F#, Python, and PowerShell support is available if you have installed those optional components. It is also important to note that C# and F# IntelliSense is limited at this point to classes and methods defined in the same .csx/.fsx file and a few system namespaces. - Cannot add new files using “Add New Item”: Adding new files to your function (e.g. .csx or .json files) is not available through “Add New Item”. The workaround is to add them using file explorer, the Add New File extension, or another tool such as Visual Studio Code. - Function bindings generate incorrectly when creating a C# Image Resize function: The settings for the binding “Azure Storage Blob out (imageSmall)” are overridden by the settings for the binding “Azure Storage Blob out (imageMedium)” in the generated function.json. The workaround is to go to the generated function.json and manually edit the “imageSmall” binding. - Local deployment and web deploy packages are not supported: Currently, only Web Deploy to App Service is supported. If you try to use Local Deploy or a Web Deploy Package, you’ll see the error “GatherAllFilesToPublish does not exist in the project”. - The Publish Preview shows all files in the project’s folder even if they are not part of the project: Publish preview does not function correctly, and will cause all files in the project folder to be picked up and and published. Avoid using the Preview view. - The publish option “Remove additional files at destination” does not work correctly: The workaround is to remove these files manually by going to the Azure Functions Portal, Function App Settings -> App Service Editor Conclusion Please download and try out this preview of Visual Studio Tools for Azure Functions and let us know who you are so we can follow up and see how they are working. Additionally, please report any issues you encounter on our GitHub repo (include “Visual Studio” in the issue title) and provide any comments or questions you have below, or via Twitter. Join the conversationAdd Comment FYI to anyone installing this that had .NET Core projects with a project.json file, it appears that update also installs new .NET Core tooling that is possibly incompatible with project.json? After installing, my project appears to have no files, and I also get the following error: ————————— Microsoft Visual Studio ————————— The project system has encountered an error... A diagnostic log has been written to the following location: “C:\************\AppData\Local\Temp\VsProjectFault_2c1dba5d-03af-4e52-a40f-5e45e4400288.failure.txt”. ————————— OK ————————— That diagnostic file contains the following: ===================== 12/1/2016 11:33:47() =================== 12/1/2016 11:40:34() =================== @Peder thanks for reporting this, we’re invetigating I can confirm this just happened to me as well. This is really causing me some pain. I have uninstalled the tooling, but I am still getting errors like the one above in Visual Studio 2015. When I open an existing .Net Core solution, I need to unload the project and reload it before it works again. Is there any cleaning up you can recommend that the uninstall didn’t do (I manually deleted the preview3 SDK that had appeared)? Following on from Russell’s post, i didnt remove the Azure Functions preview tooling but unloaded and then loaded the Core project. This loaded the project and i could compile and run. So it seems it’s just the initial load that’s throwing the error. It gets worse… I have mostly got used to unloading the project and reloading it every time I open Visual Studio (albeit very annoying). But I have just tried to publish to Azure and it just sits there doing nothing. The build part completes, but the publish never starts. Cancelling the publish from the Web Publish Activity window does nothing. The only option I have is to close Visual Studio and reopen it… then unload the project and reload. I’m at the point of uninstalling Visual Studio and reinstalling now. Not happy. Think I’ll stick to trusty Web Jobs for the foreseeable future. Donna from the Functions team here. Russell, thanks for your patience and sorry for all of the hassle! For the situation you’re describing with “publish to Azure”, is it the Core project where publish never starts, or the Functions project? Btw, we’re working on allowing you to publish an assembly to Azure Functions, which will make the tooling a lot less custom. Donna, I feel Russell’s pain! When i publish the Functions project the process starts and throws “The target GatherAllFilesToPublish does not exist in the project.” Publishing the core project does absolutely nothing. OK – the updated package has resolved the .NET core issues. I can now publish my core app. However, the “GatherAllFilesToPublish” target is still missing when i publish my Functions app. Stephen, thanks for filing the GitHub issue at, we’ll follow up there. I’m having the same issue when attempting to create an Azure Functions type project from within Visual Studio: The project system has encountered an error. The following error occurred during discovery of project files on disk.). A diagnostic log has been written…. @Stephen, “GatherAllFilesToPublish” does not apply to Azure Functions which is why it is still unavailable. That option only applies to MSBuild, and Azure Functions simply publish the source to Azure Exactly the same for me. I uninstalled both Azure Functions and NET Core tooling, and then installed back only Net Core tooling preview 2 and the specific problem was fixed. Thanks for these. Just what I was waiting for. Makes function so much easier with the whole flow of git to visual studio to reply. May I ask what is the “Azure Storage Blob out (imageSmall)” you speak of? I’m looking to do a resize azure function but basedon the name of this it sounds like there is something built in or a tutorial out there where it’s done already? @Steve, I was referring to the C# function template. There is a template to create an Azure function designed to resize an image pushed into blob storage named “Image resize – C#” that generates the template for a function designed to resize an image that is saved in blob storage Is there a way to publish from command line? I’m thinking of continuous deployment scenario, when the deployment is done on CI/CD server @trailmax you can configure App Service including functions for continuous deployment by connecting them to your source control. Let me know if this will meet your needs @trailmax Andrew’s link works (for App Service Continuous Deployment), but we also have a Functions-specific topic. Note that Functions are usually deployed as scripts, which means you only need to do a content publish. Yay! glad to know Microsoft is working on this!.. have been waiting for this long enough! I agree! 🙂 When can we except support for Visual Studio 2015 Community edition? My bad, seems to be working with Visual Studio 2015 Community Correct, this works with Visual Studio Community Hi team, Thanks for the great news. Is anywhere aware of any reports that the new extension is breaking .NET Core projects in VS2015? I can’t open my project any more 🙁 Happy to grab a trace to help out resolve the issue. HI Christos, we have a repro and are currently debugging. Unfortunately the only workaround is to uninstall the functions preview and then repair your 2015 installation. Per the updated text at the beginning of the post, we shipped an update that fixes this issue What about having multiple functions? Do I scope them in single project or do I need to create separate projects for each? If you have multiple functions that would go in a single Function App, then put them all in the same Function App project. 1 .funproj = 1 Function App Do you plan to add support for VS2017RC, or do we need to wait for the RTM? @Julius, we are working on support for 2017, unfortunately I can’t give a commitment as to exactly when it will make it. I guess the current project.json structure as described here will be obsolete in VS 2017 and beyond? (will be migrated to .csproj?) Donna here from the Azure Functions team. @Stef: The project.json as used here is specific to the Functions runtime, not Visual Studio. As such, it will continue to be supported in version 1.x of the Functions runtime (see the product documentation for more about project.json:). So, project.json will be supported in VS 2017 when the Functions tooling is available there. In the future, Azure Functions will likely move away from project.json, but we haven’t yet finalized the design or the timeline. It may be in a new version of the Functions runtime (2.x), for instance. what about VS 2017? We are working on support for 2017, I however can’t commit to exactly when it will be ready at this time How can I add an external dll to an azure function that is created using this visual studio tools for azure functions i figured it out – had to add a “bin” directory under the function just like when using the dev tools weird that I had to add an additional dll to run it locally for microsoft.sqlserver.types that was not needed in the browser version of these c# azure function tools Ed, the reason is likely that you were referencing some assemblies that are available in the Functions runtime in Azure (see). However, I don’t see that assembly in the list, so I’m curious why you saw this behavior. Thank you for wasting my time by breaking the core projects. Honestly, “Azure Functions” is a huge joke, half-baked non-working solution again in an attempt to catch up with the rest of the world. I have a tip – don’t fall behind in the first place. @Unhappy, we’re sorry that this initial release broke core projects in 2015, we released an update yesterday evening that fixes this issue. Beyond the Visual Studio tools which we know are not yet finished as called out above, I would love to understand what other aspects of Azure Functions you think are half-baked. The link to .net 2.9.6 .NET SDK gives an error Server Error in ‘/web’ Application. Runtime Error Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated. @Steve, thanks for the comment, when I tried the link it appears to be working for me, please let me know if you’re still having issues I got this too using Firefox today. I opened the link using Edge instead and it worked fine. So for anyone getting this error, try it in another browser. Nice article. However, I am stuck at one place. Why the user name is $MyApplication… ? Do we need to create this user on Azure portal? I am trying with the my Azure portal user, and it is giving me Unauthorized error. I am not sure what other settings we need to perform on Azure portal @Nirman, this is currently a confusing UI as you shouldn’t need to be aware of those, but those credentials are automatically generated in Azure for publishing to consume when you provision the app. Azure creates a user name and password for tools to use, as your user credentials are issued a token that expires relatively regularly which would break some scenarios such as automated deployment from a build server on a regular basis. Can you describe the steps you are taking that is resulting in the Unauthorized error? No, it doesn’t really work. Installed tools, created new Functions project, created C# timer-based function, nothing added my own. Run => ‘A ScriptHost error’. Closed Visual Studio… @Alex, sorry to hear that. Can you clarify did Visual Studio pop up the error and cause Visual Studio to crash, or was that error in the Azure functions run time console window that appeared? Hi Andrew, I can confirm I experienced the same issue with the C# Timer Trigger. The error shows up in the Azure functions runt ime console window. @Andrew, I can confirm this same issue. I created a brand new C# Timer Trigger function. When trying to run it I get “A ScriptHost Error has occured” before eventually getting the following error: “Unable to retrieve functions list: No MediaTypeFormatter is available to read an object of type ‘FunctionEnvelope[]’ from content with media type ‘text/plain’.” Thanks for confirming, this issue is being tracked on the Functions GitHub repo at Thank you for the article. I was able to make it up to the point of publishing my function. When clicking “New” to “Create App Service” all of the dropdowns are empty. I am connected to my account, I see my email address in the upper right hand corner of the window. I can connect to my account using the “Cloud Explorer”. I see all of my plans, services and accounts there. But nothing displays when trying to create a new app service when setting up a profile for publishing. @Chris, two questions: -What update version of Visual Studio 2015 are you running (Update 1, U2, or U3)? -Are you connecting to the public Azure or a private cloud (i.e. Azure Stack)? – U3 – public I’ll paste the complete “about” content in the reply below Hi Chris, could you share the contents of the Help -> About window from VS please? The complete content is: Microsoft Visual Studio Professional 2015 Version 14.0.25431.01 Update 3 Microsoft .NET Framework Version 4.6.01055 Installed Version: Professional LightSwitch for Visual Studio 2015 00322-40000-00000-AA946 Microsoft LightSwitch for Visual Studio 2015 Visual Basic 2015 00322-40000-00000-AA946 Microsoft Visual Basic 2015 Visual C# 2015 00322-40000-00000-AA946 Microsoft Visual C# 2015 Visual C++ 2015 00322-40000-00000-AA946 Microsoft Visual C++ 2015 Visual F# 2015 00322-40000-00000-AA946 Microsoft Visual F# 2015.21129 Common Azure Tools 1.8 Provides common services for use by Azure Mobile Services and Microsoft Azure Tools. File Nesting 2.6.67 Automatically nest files based on file name and enables developers to nest and unnest any file manually HideMenu 1.0 Hides the Visual Studio main menu, similar to Windows Explorer and Internet Explorer JavaScript Language Service 2.0 JavaScript Language Service JavaScript Project System 2.0 JavaScript Project System JetBrains ReSharper Ultimate 2016.2.2 Build 106.0.20160913.91321 JetBrains ReSharper Ultimate package for Microsoft Visual Studio. For more information about ReSharper Ultimate, visit. Copyright © 2016 JetBrains, Inc. NPM Task Runner 1.4.81 Adds support for npm scripts defined in package.json directly in Visual Studio’s Task Runner Explorer. Includes full support for Yarn NuGet Package Manager 3.5.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit. PreEmptive Analytics Visualizer 1.2 Microsoft Visual Studio extension to visualize aggregated summaries from the PreEmptive Analytics product. ReadyRoll SQL Projects 1.13.19.1823 Develop your databases ‘online’ and simplify deployment using ReadyRoll database projects. Visit for more information. Copyright © 2016 Redgate Software. All rights reserved. This software contains components from Red Gate Software Ltd. This software contains components from Component Owl. SQL Server is a registered trademark of Microsoft Corporation. Visual Studio is a registered trademark of Microsoft Corporation. ReadyRoll contains code from the following open source software: NuGet SemVer .NET Api Menees Diff Controls Log4Net Extended WPF Toolkit Code InfoBox VSX This product contains icons from distributed under a free backlink license. For license details or other notices relating to the above software, please see NOTICE.TXT and EULA.TXT in the ReadyRoll application folder. ReSharper.AutoFormatOnSave 1.0 Runs silent Reformat Code command upon file save. SQL Server Data Tools 14.0.61021.0 Microsoft SQL Server Data Tools TechTalk SpecFlow 2015.1 TechTalk SpecFlow – Binding business requirements to .NET code, ToolWindowHostedEditor 1.0 Hosting json editor into a tool window TypeScript 1.8.36.0 TypeScript tools for Visual Studio Visual Commander 2.6.0 For more information about Visual Commander, see the website at. VsVim 2.2.0.0 VsVim is a Vim emulator for Visual Studio Web Essentials 2015.3 3.0.235 Adds many useful features to Visual Studio for web developers. Requires Visual Studio 2015 @Chris, Thanks for the suggestion, but the dropdowns remain empty. I am behind a proxy which uses a self-signed certificate in order to read encrypted traffic within the local network. Is it possible that this screen uses a different cert store than the standard machine cert store, and so an error is occurring? We have had an issue in the past where VS was not able refresh license information because of this. Why no support for visual basic? We don’t currently plan to support Visual Basic scripts for Azure Functions. However, in the next couple of months we will support publishing and running .NET assemblies as the implementation of the function body, and these can be authored in Visual Basic (or any .NET language). Is there a best practice for copying post-build DLLs of dependent class libraries into function directories? I’ve added project build dependencies so that my class libraries build along with my function project, but prior to deploying I’d like to copy the resultant DLLs into my functions project. I could create a VSTS NuGet package, but that seems like overkill when my functions project is already a member of a solution that contains its build dependencies. Used to be able to fake this by deploying a Web App project to a Function App because it allowed a bin directory with project references. Trying to do this “right” by using the new tooling which removes that option I like to think we can do better than my current solution: . . . Brandon, I think some of your second reply got cut off. This question just got asked on StackOverflow here (). If you customize the build output of your class library, you can write to your function project directory. The .funproj format will automatically pull in files that are in the root directory, so they will be published automatically. This is definitely far more manual than it should be! This GitHub issue tracks the improvement: Hi, I’ve created a function app and run it locally. Everything works great: all the bindings, etc. However, when I right click on the project and select Publish, “Microsoft Azure App Service” is not available as an option. Only Custom and Import are visible. Are you logged in to Azure in Cloud Explorer? If you have a regular web project, are you able to publish to App Service? As a workaround, you can create a new Azure Function in the Azure Portal and download a publish profile: 1. Go to New -> Compute -> Azure Function App 2. Go to Function App Settings in the lower left 3. In the “Manage” section, click “Go to App Service Settings” 4. In the top toolbar, in the “…More” section, select Get Publish Profile. Donna, Thanks for getting back to me. It hadn’t occurred to me to try with a regular web project. When I did, I also did not see Azure App Service as a target for publishing. I’ll have to look in to what might be causing this. In the meantime, I’ve been deploying my Function App project using GitHub with the Continuous Delivery capability, and it works great. I’ll probably be staying with that for now. If I can’t get it to work in the future, I’ll take your advice about using the generated Publish Profile. Thank you. @Michael, what Update version of Visual Studio 2015 are you using? Andrew: It’s VS 2015 Community. 14.0.25431.01 Update 3 @Michael, The tooling seems great however when using the continuous deployment from Azure portal the tooling seems to break. It wants the solution as a sibling to the project file. If you move the solution down one level (or the project up one) then you no longer can debug the function in visual studio. Is there a work around for this? Project structures Example 1: Can’t deploy but can debug Solution1 /FunctionA Example 2: Can deploy but can’t debug Solution1 FunctionA @kapopken, can you provide more details on your project structure and how you’re doing continuous deployment (VSTS, GitHub, etc?). It might be easier if you just file a GitHub issue at so we can help troubleshoot. I confirm the problem creating a new Functions project from Visual Studio, adding the created git repo to VSTS and then enabling continuous deployment from Functions portal. It all boils down to incompatible requirements for the directory structure. VS creates a project in this way: SolutionFolder -git repo stuff -solution file -ProjectFolder –host.json –appsettings.json –Functions folders —Function code When syncing this solution via git repo on VSTS, this directory structure is preserved. If I enable integration from Fx’s portal, the entire repo is downloaded into the wwwroot folder, so the structure is once again preserved. But this structure is incompatible to the way Fx host expects it to be, i.e. wwwroot -host.json -Functions folders –Function code This causes the function not to be recognized. I’m also going to post as an issue on github. Thanks! Thanks for the details. For anyone else who’s interested, follow the discussion on this GitHub issue: Is there a way to allow CORS when running the Function App project in Visual Studio? Not currently, but we have a bug to track this: Okay I’ll keep an eye on it, thanks. For now I’m just adding the “Access-Control-Allow-Origin” header to responses. Is it possible to debug an existing function? Actually, I have some functions already hosted on Azure, but I can’t create an “Existing Function” to generate the *.funproj project. Thanks, Jerry. @Jerry at this time we unfortunately don’t have built in tooling to automatically create a function project from an existing function. A couple of options: –You can remote debug the existing function in Azure through Cloud Explorer –Create an empty function project in Visual Studio, then download your existing function source using the Kudu Console view () and drop the files into the function project directory. You can also use FTP or a “local Git” repo to download the Function source. See Just a query, how will these visual studio tools work in conjunction with ARM templates? Will there be native support to link them together? @James, the template for a function app can be exported during create (the button to export is in the bottom left of the dialog). You can then edit the template in the json editor which has extended support for arm templates or imported into an arm template project. Sorry, what do you mean by this? Which dialog are you talking about? If you develop the azure function in visual studio, can you not add a web deploy package like you can do with normal websites? I tried this, but it does not provide the publish parameters. Is it possible for the user to rename the run.csx file (if using c#)? I’ve found it a bit confusing when writing a function app with multiple functions to have several files open in the document well, all with the name “run.csx”. Yes, you can specify a different filename using the “scriptFile” property in function.json. See example here: Sweet, thanks Donna. I’ve just attempted to deploy top Azure and it worked… except the app settings weren’t deployed, or at least weren’t picked up by the deployment, is this a known issue? Yes, currently appsettings.json is only used locally. How are we supposed to read those app settings when running functions locally? My appsettings.json file has several entries in the `Values` object (`AzureWebJobsStorage`, `AzureWebJobsDashboard` and `Test`) but accessing them through ConfigurationManager.AppSettings in my function does not work: ConfigurationManager.AppSettings.Count == 0. Am I missing something? In some of my functions, I reference configured values via ConfigurationManager to get at various App Service level app settings and connection strings. Maybe I am simply overlooking something…. Is there support for this? This is not currently supported, but we have an open issue to track the request: Update System.Configuration.ConfigurationManager.Appsettings property to read appsettings.json #33 Taking the tooling for a spin. I have a CSharp Function and and F# Function in the same project. Hitting F5 the C# one works just fine. F# one spits out an error about binary-incompatibility of FSharp.Core.dll. “The following 1 functions are in error: FSharp1: Error opening binary file ‘C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v2.0\2.3.0.0\FSharp.Core.dll’ : The referenced or default base CLI library ‘mscorlib’ is binary-incompatible with the referend F# core library ‘C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v2.0\v2.3.0.0\FSharp.Core.dll’. Consider recompiling the library or making an explicit reference to a version of the library that matches the CLI version you are using. “ I am from China, my Azure Functions CLI(1.0.0-beta8) always downloaded failed, even I enabled VPN. But I can install Azure Functions CLI(1.0.0-beta5) through npm with VPN. Where can I get offline install package? Still working on the 2017 RC support? trying to avoid multiple versions of all the tools on my Surface. Thx u ping Does the SDK support imperative binding for Azure functions using the IBinder interface to bind to custom blob locations? Yes, you can use any Azure Functions feature. See Hi! The link to “Azure 2.9.6 .NET SDK” in Getting Started is broken. Is there a way to run/debug function with “Manual Trigger” in Visual Studio? I have it up and running, but don’t know how to simulate manual trigger. You have to run the CLI directly to run the function. See for a walkthrough Hi, I followed the example up to this point: in run.csx file: #r “Microsoft.WindowsAzure.Storage” using System; using System.Text; using Microsoft.WindowsAzure.Storage.Table; public static void Run(string myQueueItem, IQuerable tableReaderBinding, ICollector tableWriterBinding, TraceWriter log) { log.Info($”C# Queue trigger function processed: {myQueueItem}”); } public class Message : TableEntity { public string Original { get; set; } public string Reversed { get; set; } } ============================================== in project.json file: { “frameworks”: { “net46”:{ “dependencies”: { “Microsoft.WindowsAzure.Storage” : “8.0.1” } } } } ==================================================== I ran into the following errors when I started an instance in CLI: run.csx(10,5): error CS0246: The type or namespace name ‘IQuerable’ could not be found (are you missing a using directive or an assembly reference?) Function compilation error run.csx(10,5): error CS0246: The type or namespace name ‘IQuerable’ could not be found (are you missing a using directive or an assembly reference?) Could someone please help? Thanks, He Never mind. Spelling error. “IQuerable” “IQueryable” Hello! Do I understand right that appsettings.json contains same application settings as in portal “FunctionApp->Function App Settings -> Go to App Service Settings -> Application Settings -> App Settings & Connection Strings” ? If so, how I can find something like this script in portal ? Mabe using Kudu? I would also like to know this. In particular I am trying to figure out how to put a db connection string in appsettings.json that can be used consistently with the portal. appsettings.json is only used locally. You can pull down the settings from your function app using `func azure functionapp fetch-app-settings` when using the CLI directly. See Is deploying through VSTS currently not supported? We’re very excited about using Azure Functions but want the build process to be similar to all of our other assets. When we attempt to build through VSTS, the build fails when it reaches the Import for Microsoft.AzureFunctions.Prop in the funproj. This is the resulting path: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\AzureFunctions\Microsoft.AzureFunctions.Props Azure Functions today are entirely source driven as they are dynamically compiled at run time. Set VSTS to not build, and it will work to deploy them through VSTS Hello – the experience was great except for the following (on a consumption plan with another existing Azure Function in app service): * intellisense for referenced packages (as you know) * deployment to Azure did not update the app settings correctly (had two settings with longer names (15+ characters). first was added but had the second’s value. The second did not add. * the referenced nuget packages did not download until the file was remotely edited. Cheers, Jeff Thanks for the report Azure Bot Service as it show as Function app does it get similar tooling as Azure Functions and now as you get zip file it show as solution in visual studio so normal intellisense dont work IntelliSense: is it normal that for C# WebHook function members of the object are not listed?.. IntelliSense only works for primitive runtime types and objects defined in the same file at this time Is there currently an issue with the designer tools from the portal. I’ve just attempted to access an existing function app and also created a new one. The designer returns “Server Error”, 401 – Unauthorised. I’m prompted with a user name / password (very weird). I enter my azure credentials to no avail. Hello, When debugging function locally or remotely, my breakpoints are not hitting. Message “The breakpoint will not currently be hit. No symbols have been loaded for this document.” My function is a simple C# timer, and works fine in Azure portal. I have tried loading symbols using break, selecting module and load and various suggested options from internet but none worked. Please advise. Thanks, Ali Has anyone tried to read from EventHubs using this tooling? My bindings look like this { “type”: “eventHubTrigger”, “name”: “myEventHubMessage”, “direction”: “in”, “path”: “messagecounter”, “connection”: “eventHub” } and my appsettings.json “Values”: { “eventHub”: ‘myconnectionstring’ } This works fine if i create it via the portal but with the tooling I get EventHubReader: Microsoft.Azure.WebJobs.Host: Error indexing method ‘Functions.EventHubReader’. Microsoft.WindowsAzure.Storage: Value cannot be null. Parameter name: connectionString. Any help would be appreciated Could you post an issue in this repo? Is tooling for Azure Functions confirmed to be in the VS 2017 RTM? I understand this is just a preview but I am wanting to run only a specific function during development. When I debug all the functions in the FunctionsApp are in effect running. I realize that I can manually update the function.json file to disable all but the function I am working on but that feels kludgey and I worry about leaving a function disabled when I push (which is another issue). Is there a way to debug only one function? Is it best-practice to include the function.json in source control? In my case I pull many settings from the App Settings into my function.json so I have no problem with them being in source-control since I can control per environment via the App Settings. I could make the function.json disabled attribute reference the App Settings and control everything from there but that again seems like a workaround rather than good form. For Functions-related questions, it’s best to use forums as we may lose track in blog post comments. Please post here in the future: Running the entire Functions host is by design, but we can consider a feature that would make it easier to enable only one function. function.json should be included in source control. Most bindings don’t allow using a connection string directly, you have to specify a key for appsettings.json. Btw, not sure it helps but you can also control which functions are enabled in host.json This is great to see, I tried this out on an existing Azure Function and it worked smoothly. One point – the ‘Create App Service’ image shows this first field as being ‘Function App Name’. For me it looked like: Thanks again Is this tooling now in VS2017 or available separately or not there yet? Just added a note to the top of the post, tools for 2017 are not available yet When will the tooling come to Visual Studio 2017 We had to put tools for 2017 on hold in order to finish the 2017 release. We are starting to work on them again now, but I can’t promise a specific date yet Just adding a data point for people interested in the tools for VS2017. How is support for VS2017 coming along? We had to put tools for 2017 on hold in order to finish the 2017 release. We are starting to work on them again now, but I can’t promise a specific date yet Hi, Is this going to be updated any time soon for the Azure SDK 3.0? Thanks Need it too. I’ll post a workaround on Another plus 1 for VS2017, but also for a timeframe on increased intellisense for both special cased imports like Newtonsoft.Json, and also for user-imported dlls. I hadn’t realised quite how lazy I’ve got, and come to depend so much on being prompted with available methods and properties. Is there a Github repo we can report issues and track progress? Thanks! Nich: we’re working on VS 2017 support, which is tracked by this GitHub issue: You can report issues at. We’re not publicly tracking progress at a feature level, but I will publicly post updates at I’m evaluating Azure Functions to replace our EPH based Archive service which reads events from Azure IoT Hub and writes to Azure Table Storage in a certain format. I’m using EventHub Trigger binding as input, and a custom binder for Table Storage which uses DynamicTableEntity. While the function is working fine, when run locally it is very slow in writing to Table Storage when compared to our service. I’ve observed similar delays after deploying to Azure as well. Some of the logs with duration pasted below. Please suggest how to improve performance when using Azure Function. Line 816: TableHistoryService function archived message at 3/10/2017 4:42:12 PM after 121.521 seconds. Line 819: TableHistoryService function archived message at 3/10/2017 4:42:12 PM after 152.543 seconds. Line 822: TableHistoryService function archived message at 3/10/2017 4:42:12 PM after 150.664 seconds. Line 825: TableHistoryService function archived message at 3/10/2017 4:42:12 PM after 143.664 seconds. Line 828: TableHistoryService function archived message at 3/10/2017 4:42:13 PM after 137.788 seconds. Line 831: TableHistoryService function archived message at 3/10/2017 4:42:13 PM after 62.81 seconds. Line 834: TableHistoryService function archived message at 3/10/2017 4:42:13 PM after 98.901 seconds. Line 837: TableHistoryService function archived message at 3/10/2017 4:42:13 PM after 78.936 seconds. I have followed the Visual Studio 2015 pre-requisites and the “Azure Functions (Preview)” project type is not available under the “Cloud” node for “Visual C#” section. The Azure SDK 3.0 was installed and had to be uninstalled to install the Azure SDK 2.9.6. James, did you get it working? I’m t-rying this out with VS 2015 community, with Azure SDK 2.9.6 installed (according to the Web PI)and installing the download. WHen I try to create a new project the Azure Functions project template doesn’t show? What might I be missing? I’m having the same problem. Still investigating. I’ve tried to install these tools several times and tried to access the project template both from VS 2015 and VS 2017. I’m wondering if the problem is that I’m running the community editions? Hi Cori & Gabe. Same problem here. Have you managed to find a fix? Also using Community but about to try with a Pro trial. Also, are you guys on Windows 8.1? Same issue with Pro. Azure Function team ? I’ve fallen back to using VS Code and git to manage the function I’m playing around with since these tools apparently aren’t ready for primetime and aren’t really supported. Interesting since they’re promoted prominently on the Azure Functions challenge page. Perhaps we’ll get some attention? And I’m on Windows 10, FWIW. Just added to see if we can get some more attention on this problem. I’m having the same issue. Has anyone figured this out yet? I installed the SDK (the Web Platform Installer installed 3.0, not 2.9.6). I go to install the Function Preview, and it says a version of the program is already installed so it exits the installer. I go into Visual Studio and the Azure Functions project is not around. *sigh* OK, so I just noticed the note at the top and not working with 3.0 So how the heck do I get an all-inclusive installer for 2.9.6? This whole system is stupid. I can’t easily uninstall SDK 3.0, and the WebPI even says I already have 2.9.6 installed…like seriously? Hi, I was using the functions projects for several weeks. Now I had to reinstall my Computer and can’t get the function extension working again in VS2015. The only Thing I changed knowlingly was, that I first installed VS2017, and then installed VS2015 again, to get Azure Functions Support for my existing Projects. So I can’t use my existing projects anymore! VS2015 tells me .funproj is unsupported application. Any idea what to do now? Hi, I have the same problem. Have you found a solution? “there are no Azure Function Tools currently available for Visual Studio 2017. We are actively working on the 2017 tools, and will provide an update in the next few weeks regarding our plans and strategy.” Why does Microsoft release an uncomplete version of Visual Studio ?!? It’s the same issue with SSDT BI tools (SSIS packages). Each new release comes with a bunch of “to-be-released” tools and frameworks. Frustrating! Please try to ship the complete new platform as one final bundle! My solution with VS 2015 Update 3: 1. Uninstall Azure App Service Tools 3.0; 2. Install 2.9.6. Azure Function project template will be ready! How can I add the “GoogleCloudKey” in appsettings.json in VS 2015 Azure Functions? At the web portal of azure function I just copy the complete text from the google json file into my new variable “GoogleCloudKey”. In VS2015 it doesn´t work. Why and how can I make it? Hi, I have all the prerequisites installed but still not able to see the functions option when creating a new project? running VS 2015 u3 professional. AZURE APP service version 3.0.0 seems to be included within Azure SDK now , thus installing SDK first as per the instructions is basically shooting yourself in the foot and making it impossible to install Azure app service 2.9.6 . this page needs to be updated
https://blogs.msdn.microsoft.com/webdev/2016/12/01/visual-studio-tools-for-azure-functions/
CC-MAIN-2018-05
refinedweb
7,961
64.61
For each play of the game, the user is supposed to enter their bet. He or she must have sufficient funds remaining in their bankroll to cover their bet and so it's under $100.00. The program then draws a card and displays it to the user. Then it asks the user if he or she thinks the next card will be higher or lower and draws a second card. The second card has to be different in some way, be it face, suit or both. If the user guessed correctly, the bet is added to their bankroll. If not, the bet is subtracted from their bankroll. Display the amount of the user's bankroll after each game before asking whether the user wishes to play again. Now here's what I have: Playing Card import java.util.Random; public class PlayingCard { private int face; private int suit; //------------------------------------------------------------------- // Sets up the playing card by drawing it initially. //------------------------------------------------------------------- public PlayingCard () { drawCard(); } //------------------------------------------------------------------- // Draws the playing card by randomly choosing face and suit values. //------------------------------------------------------------------- public void drawCard () { face = (int) (Math.random() * 13) + 2; suit = (int) (Math.random() * 4); } //------------------------------------------------------------------- // Returns true if the current playing card is exactly the same as // the card passed in as a parameter. //------------------------------------------------------------------- public boolean isEquals (PlayingCard c) { return (face == c.face && suit == c.suit); } //------------------------------------------------------------------- // Returns the face value of the current playing card. //------------------------------------------------------------------- public int getFace() { return face; } //------------------------------------------------------------------- // Returns the suit value of the current playing card. //------------------------------------------------------------------- public int getSuit() { return suit; } //------------------------------------------------------------------- // Returns the current playing card as a string. //------------------------------------------------------------------- public String toString() { String cardName = null; switch (face) { case 2: cardName = "Two"; break; case 3: cardName = "Three"; break; case 4: cardName = "Four"; break; case 5: cardName = "Five"; break; case 6: cardName = "Six"; break; case 7: cardName = "Seven"; break; case 8: cardName = "Eight"; break; case 9: cardName = "Nine"; break; case 10: cardName = "Ten"; break; case 11: cardName = "Jack"; break; case 12: cardName = "Queen"; break; case 13: cardName = "King"; break; case 14: cardName = "Ace"; } switch (suit) { case 0: cardName += " of Clubs"; break; case 1: cardName += " of Spades"; break; case 2: cardName += " of Hearts"; break; case 3: cardName += " of Diamonds"; break; } return cardName; } } The Hi-Lo Game import java.util.Scanner; import java.util.Random; public class HiLoGame { public static void main (String[] args) { double bankroll, bet; int lostGames, tiedGames, totalGames, wonGames; Scanner scan = new Scanner (System.in); System.out.println("\n\nThis program implements a Hi-Lo game using"); System.out.println("a standard deck of 52 playing cards. You are"); System.out.println("required to enter your bankroll as well as the"); System.out.println("amount of money you wish to bet."); System.out.print("\n\nHow much is in your bank? "); bankroll = scan.nextDouble(); System.out.print("\n\nHow much would you like to bet? "); bet = scan.nextDouble(); System.out.println("First card: " + getFace + " of " + getSuit); System.out.print("\n\nDo you think the second card will be higher or lower?"); String choiceString = scan.nextLine(); choiceString = choiceString.toLowerCase(); PlayingCard = cardOne = new PlayingCard(); PlayingCard = cardTwo = new PlayingCard(); if (cardOne.getface() < cardTwo.getTwo.getface() && guess.equals("higher")) do { cardTwo.drawCard(); } while (cardOne.isEquals(cardTwo)); if (choiceString > 0) if (choiceString == cardTwo) { System.out.println("Good job! You're right!"); bankroll = bankroll + bet; wonGames++; totalGames++; System.out.println("The amount in your bankroll is " + bankroll + "."); System.out.println("Would you like to play again?"); } if (choiceString < cardTwo) { System.out.println("Sorry, your guess was too low."); bankroll = bankroll - bet; lostGames++; totalGames++; System.out.println("The amount in your bankroll is " + bankroll + "."); System.out.println("Would you like to play again?"); } else { System.out.println("Sorry, your guess was too high."); bankroll = bankroll - bet; lostGames++; totalGames++; System.out.println("The amount in your bankroll is " + bankroll + "."); System.out.println("Would you like to play again?"); } System.out.println("You played "+ totalGames +" games total."); System.out.println("You won " + wonGames + " times, lost " + lostGames + " times, and tied " + tiedGames + " times."); System.out.println("The amount left in your bankroll is " + bankroll + "."); } } How can I configure my code so that it reads off of PlayingCard.java? Also what can I do to make it understand 'Higher' or 'Lower' for the second card?
http://www.dreamincode.net/forums/topic/164147-hi-lo-java/
CC-MAIN-2017-09
refinedweb
686
68.87
The following script import numpy as np` import plotly.plotly as py import plotly.graph_objs as go from plotly.graph_objs import * from plotly.offline import download_plotlyjs, init_notebook_mode, iplot init_notebook_mode(connected = True) rand = np.random.randn(100) trace = go.Histogram(name = "distance of overpass from Rome's station", x = rand, autobinx = False, xbins = dict(start = 0.1, size = 10, end = rand.max()) ) data = [trace] fig = go.Figure(data = data) iplot(fig) is running in Jupyter notebook with Python 3 kernel. The problem is that whatever is the the change in the attributes of nbins (start, size, end) the histogram’s bins don’t cange in the plot. I wrote this script as an example, so I did it for Python’s Plotly, but I’d actually like to perform a histogram for pandas module that is with the use of dataframe’s column as x variable.
https://community.plotly.com/t/assigning-xbins-attritutes-doesnt-change-histograms-bins/5361
CC-MAIN-2020-40
refinedweb
145
61.02
About this talk Xamarin.Forms introduces shared user interface code to your ecosystem. It gives you the control to write your UI code once, and it runs everywhere. Transcript I wanted to start this talk by asking you a question and that question is when was the last time you thought "This is why I love programming"? And by that I mean remembering that first little spark you got, from whenever the first time you got into programming was. For me it was when I got a book on HTML 3.2 when I was 12 and I remember putting something into the title tag and the very feeling of putting something into a title tag in notepad and having it appearing in the title bar of Netscape Navigator gave me an absolute feeling of control that I think I've been chasing ever since. The last time I thought that I got that same feeling was like "Holy shit, so much control, this is amazing" was when I was playing with something called Xamarin.Forms and this is what I was here to talk to you about today. So just to get us started, in order to understand what Xamarin.Forms is, let's first talk about what Xamarin is. And Xamarin is essentially a ported version of a few different SDKs, which are, so you've got the IOS SDK, the Android SDK and the Windows phone SDK all ported into C# and you've got every single API available but you can write using the tools that you already know. Now this is really good for businesses with established .net teams because rather than having to go out and hire a bunch of people that know Java, hire a bunch of people that know IOS, you can repurpose the skills that you've already got. So you can have this either portable class library or a shared project of all your business logic there to be shared between applications. But then once you've done that, you then have to, you do have to do all your user interface stuff separately. You still do it in C# and Xamarin provides amazing tooling for actually constructing that, but you still have to have quite in-depth knowledge about the life cycle of each ecosystem. So what Xamarin.Forms does is it hopes to introduce this extra layer here, which is your shared user interface code. Now from a native mobile app standpoint, this is the absolute holy grail of development really, because you write it once and then it runs everywhere. Now the point where this differs from something like PhoneGap, Cordova or something, is you're talking about actual native controls. Now I come from a web background and the whole Cordova thing when I first got into it was like wow, this is really cool, like I can actually run, you get the icon on your home screen and it's really cool, but as soon as you start pressing the buttons it just feels a bit like a web app in a wrapper, it's just, it's not there. Even there's tools like Ionic, which make it super clean to develop native looking apps and you write it once and you can do conditional compilation in that instance, where you do an Android version. And yeah, it kinda works but it's not like real native. What Xamarin.Forms does is it actually gives you the controls to write your user interface code once and when you write a button in Xamarin.Forms, it is a button on Android and it is a button on IOS. Nobody cares about Windows phone but it can do that as well. So here we've got a Galaxy running. You'll know my pass code by the end of it, it's not particularly complex. So we're gonna try and put something on here and then I've got an iPhone 7 running as well. And we're gonna start literally from scratch, because what I want to do today is just show you how easy it is to do this, write your code once and run anywhere. So we're literally gonna start right at the beginning, which is from the new solution button. Obviously I'm running Xamarin Studio on the Mac here because I want to deploy quite quickly to the IOS devices. Microsoft does provide all the tooling that you need to be able to do this from Visual Studio as well, and you can actually deploy to either a remote simulator or a remote IOS device using the remote build agent tools that Microsoft provides there. So what we're gonna do is in Xamarin Studio, we're gonna go into and do a new Forms App, we'll call it HelloDotNetSheff. We're gonna target Android and IOS in this instance, we're gonna use a portable class library and we're gonna use XAML for our user interface files to start with. Now let's just double check that I've got my internet connexion still so we can get the new get packages to start with and that's fine so let's go ahead and create that. Okay, while Xamarin Studio goes off and adds some of our packages, this is casting at a really, really high DPI. But I'll just talk you through some of the life cycles of the different projects. So in your IOS project it starts, so obviously this would be done either in Swift or Objective-C normally but it's just been literally ported over to C# and you start out with your main.cs file and you nominate this file called your app delegate which anybody who's done IOS before will tell you is your starting point. And as opposed to your traditional Xamarin project, where you might instantiate your app wherever you want to begin there, you actually include Xamarin.Forms from this point, from your app delegates, sorry, and you load it in here in this new app bit, which you would see would come from Xamarin.Forms. Likewise in the Android project, you've got your main activity, where you nominate your main activity, but here we call this forms.init function here. And what that does is, so you'll see down the side here, that's our IOS project and our android project, and then that means that we've then got this hook in to our Xamarin.Forms project up here. Now where this starts is this app.xaml, which has a CodeBehind of app.xaml.cs. Now this nominates our, it's created us a starting page, which is this HelloDotNetSheff. Let's see if we can increase the font size a little bit. So this is our starting point so you can see by default we've got as a label, we've got our content here which is declared like this and then a label with a few different attributes and it just says "Welcome to Xamarin.Forms", so let's start by just customising this a little bit and we'll just say "Hello .Net Sheff". And we'll select our project up here, so we'll go on the IOS device and we'll try and send it to my iPhone over here. So we'll kick that off and wait for it to build. Okay so we can see it's deploying to the device here, so let's squizz over to my iPhone. You can see this has deployed our IOS application to here. So let's just very quickly do the same with our Android project as well, so we'll stop that. Right, now you'll be relieved to hear that Vysor, which is the programme we're using to get the Android video signal, doesn't take audio, so we shouldn't get some horrendous infinite loop like we did just then. So let's just check where we're up to with this. So you can see here in Xamarin Studio we've got our status up here. Just get it deploying onto the device and it should auto-launch for us in a sec just on here. Any moment now. - [Audience Member] Is it 'cause you're not plugged in? - Right, here we go. Again, great, so that's our very basic example. Now just see how we're doing for time, so the next thing we're gonna do is try and introduce some navigation to our app. So we're just gonna try and go from one screen to another and I'll hopefully drop on some native controls there and you can see these controls rendered natively on each device. So we'll start by adding a new XAML page and we'll call this our second page. Now by default, I'll come to this at the end and talk about different ways of architecting your Xamarin apps. But by default, the XAML files work, so you just have a XAML page and then it has this CodeBehind page and you can call different functions based on events in your XAML file, to the CodeBehind. So on this second page here, what we'll begin with is we'll start by creating a stack layout. Xamarin.Forms comes with a few different types of layouts that you can use, a stack layout, if you're experienced in CSS, it's almost like declaring all of the children as display block. It's quite similar to the Flexbox model that a lot of modern layout engines use. We'll give it some vertical options, which tells us where we want it to appear. We're gonna go for centre, so vertical we'll just go for centre and horizontal we want to do as fill and expand, so that it fills the full width here. Now that we've got that stack layout, we can start to put in a few different controls. So and you start by doing a slider, because both operating systems come with a slider. I'm then also gonna use a picker, which I just have in a little snippet over here. And then underneath our picker, let's just add in a date picker as well. And then just for good measure we'll add in a switch. The docks are so well written, it's very, very clear, it's got a full, they call it, confusingly they call these views, every little, What you would consider a view in MVC land is actually a page and then each component is called a view. Which can get confusing, especially when you're doing a Xamarin project and doing a web project and trying to talk about both at once. So that's our second page. So what we need to do then is enable us to get to our second page. So we're gonna come back to our first page, which is our HelloDotNetSheff page, and we'll take this, so this label here, if we're adding another item to it, that also needs to be in a stack layout. So we'll do another stack layout. We'll centre it. And we'll put that label back in and then we'll create a button. We'll give it some text to say "Take me to the second page". And the default way of doing this, this isn't, again, how you would do it in production, but just to show you the ease from getting from zero to cross-platform apps faster than you can say Xamarin.Forms as the title suggests, we're gonna do it using the out of the box method, which is using this clicked event. And then Xamarin Studio handily provides us this little task that says "Handle Clicked". So we're gonna create this handle clicked method, we come down here to our CodeBehind and insert that in there. Then just going to copy over this other snippet, which is just, we're gonna rewrite this as an Async which says we're gonna use the navigational object to push our second page. Now that's all very well but unfortunately at the moment the way Xamarin.Forms architects itself is pages that navigate between each other have to exist within a navigation container. So we need to come into our entry point here, which is our app.xaml.cs and here we're just gonna take this, where we declare our main page, that's our starting point for our app, so that's the route that we declared in our Android and IOS projects, so in our app delegate on IOS and our main activity on Android, that comes through and this main page thing is where it starts. So we're just gonna... Just gonna call a new navigation page and then within the navigatin page we're gonna start it with that HelloDotNetSheff page, which is what it started us with. Now, oo I'm still debugging. Now if we've done everything correctly, somebody tell me if I've missed something. We'll start on our IOS project again. We'll deploy it to my iPhone again, Volume set to zero. Alright. Oh yeah, thank you. Let's try again. I do wish it would give us some more feedback here. Oh right, deploying to device, so hopefully that should be us getting started over here. So you can see we've got our Hello .Net Sheff label at the top, so underneath that in our stack layout is our default button. Ever since IOS 7, they have this background-less thing which to me makes absolutely no sense. Red text and blue text, give it a nice background Apple, come on. And then if I click the second button, you can see we've got our native slider here, which, because I've not put any padding on it, is actually quite difficult to grab. There we go. So we've got a native slider right here. If I use the select thing, that's the select snippet that I put in, I can use the date picker and the buttons. And like I say, compared to Cordova, it's native, it feels native. As soon as you press the button, there's no oh, this is a web wrapper just executing some CSS, it's real. So just to show how it looks on Android. Let's just come round here. Again, if you did want to do anything custom, per platform here as well and if the newer versions of Xamarin.Forms have literal code tags that you can use, you basically define an XML namespace up at the top there. And your extra XML namespace you would then define like an Android name space and an IOS name space and you would basically get, okay on IOS I want this button here but actually on Android I want this special kind of button which I've specifically engineered for that platform. So if we come round here you can see it's exactly the same on Android, except it looks like an Android application. You can see our default button is an actual real Android button. And if I go onto the next page you can see I've got native page transitions, my slider goes up and down, I've still got the same data there, I've got a native date picker here as well and I've got a nice material design little toggle there. So that's literally from new project to a cross-platform app in what's no time at all. So if you were gonna get started with this, what do you want to do next, in terms of moving forward? First thing I'd recommend is getting started with the Xamarin University course on their website. It makes it look like it costs 2,000 pounds a year, which is great if you've got an employer that will sponsor you to go and learn this, it's a really, really valuable skill set. But their basic stuff, they've got at least three or four hours of starter content which will get you up and running really, really quickly and give you quite a deep knowledge. The next thing that I would recommend as well is providing an MVVM framework. My colleagues Nick and Andy did a fantastic job of researching these least year for us when we were starting on a Xamarin.Forms project. We used FreshMvvm in the end. Other frameworks are available. And that enables you to do some really neat stuff with data bindings and just writing it in a really nice maintainable way. And the next thing I would recommend as well is doing the Xamarin traditional approach. Obviously it's brilliant being able to do the shared user interface code, but sooner or later you're gonna have to get a deeper understanding of the app life cycles of each of the different platforms, especially when it comes to what's called custom renderers, which is where you start putting different things on IOS and different things on Android as well. So yeah, that's it, yeah, any questions? Nope, alright, brill, thanks for your time.
https://www.pusher.com/sessions/meetup/dotnetsheff/from-0-to-cross-platform-mobile-apps-faster-than-you-can-say-xamarin-forms
CC-MAIN-2019-39
refinedweb
2,921
76.96
This is a discussion on help me with first program within the C++ Programming forums, part of the General Programming Boards category; help... please help i need help! hurry, please help me! i must turn this in in a minute! Yes, you do... Here's a hello world program for you... Beyond that, I can only advise picking up a book and reading. Also, don't reply to your own posts 5 minutes after you make them. Actually - I'm going to let you flounder. This program can be done in 2 seconds if you actually pick up a book, and since you've already bumped this thread twice, I'll just let you suffer. -Govtcheez govtcheez03@hotmail.com You need to have... #include <iostream.h> ...before main(). Your main() should return an int i.e. int main() Strings need to be in double quotes and statements within your main() need a ; after them eg... cout << "Hello World!"; return 0; Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream. HaHa...you sure do. main() {cout<<hello world return 0} How about this: cout is an object, and objects arnt built in. Its defined elsehwere, so to start you need: include<iomanip.h> next prob...your returning 0, but main isnt set to return anything...heck its not even set as void...and it takes no params, spo that should be void...so... int main(void) and lastly...code lines end in a semi colon. Putting it all together... Code:include<iomanip.h> int main(void { cout << "Hello World"; return 0; } Last edited by TrojanGekko; 02-22-2002 at 08:47 AM. ______________________ The Gekko Sorry cheez, concurrence again, but I think that it is a first for me at least, that someone has bumped their thread twice while I was typing an answer. One for the record books huh? Guess no more help here. Now, let me see that IP address again...! Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream. thanx u guys were more helpful than govtcheez and please dont hack me adiran... lol thats the funniest program i ever saw! we actually read the first chapter before we even got to turn on the computers in my class lol... and that hello world thing is in the main page of this site! you could have copied and pasted it... well i guess we were all newbie once...and i still am...but this is ridiculous Paro
http://cboard.cprogramming.com/cplusplus-programming/11542-help-me-first-program.html
CC-MAIN-2014-15
refinedweb
419
86.71
Using the autodivider feature in jQuery Mobile (take two) Almost a year ago I blogged about using the autodivider feature in jQuery Mobile. This is a simple feature that enhances list views with dividers. It makes content a bit easier to parse when working with a large list. One of my readers, Fher (who has a cool name - I kind of imagine her/him as a fire-breathing wolf), asked if there was a way to add a bubble count to the dividers. You can see an example of this on the docs for listview, but this is what the feature looks like: So, the short answer is no, you can't do this with autodividers. Why? While the feature allows you to build a function to create dynamic dividers, it only lets you specify the text for the divider, not random HTML. However, if you are willing to give up having the "pretty bubble" effect, you can simply use it as part of the label. To make that work, I modified my code a bit from the previous demo (and again, you can read that here, I'd suggest checking it out just so you can see the context). Here is the complete JavaScript code. (The HTML didn't change.) $>"); } /* Create a generic func to return the label */ var getLabel = function(d) { return (d.getMonth()+1)+ "/" + d.getDate() + "/" + d.getFullYear(); } /* Now that we have a func, use it to generate a label to count hash */ var dateCount = {}; for(var i=0, len=dates.length; i<len; i++) { var l = getLabel(new Date(dates[i])); if(dateCount.hasOwnProperty(l)) { dateCount[l]++; } else { dateCount[l] = 1; } } dateList.listview({ autodividers:true, autodividersSelector: function ( li ) { var d = new Date(li.text()); var label = getLabel(d); return label + " (" +dateCount[label] +")"; } }).listview("refresh"); }); The first change was to abstract out the code used to generate the divider - basically turning the date value into a label. Once I have that, I iterate over my data to figure out how many unique date labels I have. This is done with a simple object and a counter. Finally, my autodividersSelector function is modified to make use of this count. Here is the result. There you go. Not exactly rocket science, but hopefully helpful. It is possible to create dividers with list bubbles, just not quite as simply as this entry demonstrates. I'll show that tomorrow.
https://www.raymondcamden.com/2014/11/18/Using-the-autodivider-feature-in-jQuery-Mobile-take-two
CC-MAIN-2020-45
refinedweb
398
65.01
Docker ID accountsEstimated reading time: 1 minute Your free Docker ID grants you access to Docker services such as the Docker Store, Docker Cloud, Docker Hub repositories, and some beta programs. Your Docker ID becomes repository namespace used by hosted services such as Docker Hub and Docker Cloud. All you need is an email address. This account also allows you to log in to services such as the Docker Support Center, the Docker Forums, and the Docker Success portal. Register for a Docker ID Your Docker ID becomes your user namespace for hosted Docker services, and becomes your username on the Docker Forums. Go to the Docker Cloud sign up page. Enter a username that will become your Docker ID. Your Docker ID must be between 4 and 30 characters long, and can only contain numbers and lowercase letters.. Once you register and verify your Docker ID email address, you can log in to Docker services. For Docker Cloud, Hub, and Store, log in using the web interface. You can also log in using the docker login command. (You can read more about docker login here.) accounts, docker ID, billing, paid plans, support, Cloud, Hub, Store, Forums, knowledge base, beta accessaccounts, docker ID, billing, paid plans, support, Cloud, Hub, Store, Forums, knowledge base, beta access Warning: When you use the docker logincommand, your credentials are stored in your home directory in .docker/config.json. The password is base64 encoded in this file. If you require secure storage for this password, use the Docker credential helpers.
https://docs.docker.com/docker-id/
CC-MAIN-2017-47
refinedweb
255
62.78
01 December 2011 04:57 [Source: ICIS news] SINGAPORE (ICIS)--JX Nippon Oil & Energy is planning to shut three of its Japan-based paraxylene (PX) units in 2012 for maintenance that will take 40 days, a company source said on Thursday. JX Nippon Oil & Energy will shut its 350,000 tonne/year Mizushima-based unit from the end of January to the middle of March, followed by its 400,000 tonne/year Chita-based facility from May to June, he said. The third facility in ?xml:namespace> The company operates eight PX production facilities in five locations in Japan and can produce up to 2.57m tonnes of material per ann
http://www.icis.com/Articles/2011/12/01/9513026/jx-nippon-oil.html
CC-MAIN-2015-06
refinedweb
111
59.64
File Upload This guide will show you how to upload files to your Web Server from your WebClient application. 1. Import the attached zip Java Project into your Eclipse Workspace. 2. Right click your Java Project, and select Properties. Under “Java Build Path”, add reference in the Projects tab to the “FileUploadServlet” project. And in the Libraries tab, add a reference to the “commons-io-2.1.jar”, which is in the “FileUploadServlet” project. 3. Right click your Web Project, and select Properties. Under “Java Build Path”, add reference in the Projects tab to the “FileUploadServlet” project. 4. Right click your Web Project, select New, then Servlet. Check the option “Use an existing Servlet class or JSP”. Then click “Browse” to add the existing UploadServlet to your web project. This will update the web.xml with your new servlet. 5. For the Web Project, select the Deployment Assembly property and click 'Add…'. Select Project, then select the FileUploadServlet project. Click 'Add…' again, then 'Archives from Workspace', then 'Add…' again. Now expand the FileUploadServlet project and select the two commons*.jar files. 6. In your WebClient.properties file, add the following setting. # Upload Servlet Location Define.WSUPLOAD=/{Your Web Project name}/UploadServlet The default value will be /{Your Web Project name}/UploadServlet. If you want to change the url-pattern for your upload servlet in the web.xml file, the “/UploadServlet” part of this setting will need to change to whatever you set your url-pattern to: <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> 7. In Plex, create an upload pattern function called “~WebUploadShell”. This should inherit from “~WebShell” and “~DetailPopup”. 8. Create two fields “UploadFileName” and “UploadControl” with the following triples and values: 9. Add the field “UploadFileName” to the ~WebUploadShell panel in a region called “UploadP”. 10. In the panel editor for “~WebUploadShell”, hide the label for “UploadFileName”, and add the following control name to the edit for “UploadFileName”: UploadFile:OtherFormsArea:template=UploadFileEdit:default NOTE: There are 2 upload templates “UploadFileEdit” provides a Browse button to allow the file to be selected, while “DragUploadFileEdit” provides a region where a file can be dragged to. Both templates take up the size of the edit control on the panel and display a progress bar within the region while the file is being uploaded. Currently the “UploadFileEdit” template is the only one that can be used multiple times on the same panel, each time must use a unique control name. 11. In the panel editor for “~WebUploadShell”, create an event called “UploadComplete” and attach it to the “Updated” physical event for the “UploadFileName” edit control. 12. Create a source code object “SaveUploadDestination”. Add 2 parameters fields “UploadFileName” and “UploadControl”. Add the following source code: import com.adcaustin.webplex.WebPlexLog; import javax.servlet.http.*; // Store the upload destination in a session attribute so it can be retrieved by the UploadServlet try { HttpServletRequest request = (HttpServletRequest) getApp().getFromUserStorage("javax.servlet.http.HttpServletRequest" ); HttpSession session = request.getSession(); session.setAttribute(&(2:).toString() + "UploadDestination", &(1:).toString()); } catch (Exception e) { WebPlexLog.errorLog(e, "Error setting session attribute"); } NOTE: The upload template allows for multiple upload controls on the same panel, so you will need to call this code for each control, passing in the control name each time. The control name is the first part of the control name parameter before the first colon, so in the example above it will be “UploadFile”. 13. In the action diagram for “~WebUploadShell”, add the following code: Map the parameters of the API Call passing in the panel field and control name: 14. Now that the patterns are created, have whatever function you want to have upload capability inherit from “~WebUploadShell”. 15. In the “Edit Point Set Upload Folder”, you will need to set the location on the Web Server where you want the file to upload to UploadP<UploadFileName> and do a Put UploadP. If you need to perform code when the upload completes, please put this code in the UploadComplete event. When running, the UploadFileName field will appear as an upload button. When clicked, it will take you to a file selection window, when selected, the file will begin uploading. NOTE: The placement of the UploadFileName field in the panel is based on a different html form than that of regular WebClient. It positions relative to the top of the panel, not relative to other objects. So, it will take some experimentation to get the placement exactly how you want it. Additional Notes By default, the upload template will allow a single file to be uploaded at a time. It can be configured to allow multiple files at a time on supported browsers* by adding the “multiple” parameter to the control name, e.g. UploadFile:OtherFormsArea:template=UploadFileEdit:default:multiple * Due to a limitation in Internet Explorer, only single files can be uploaded at a time. Filenames can be encoded to prevent issues saving files with unsupported characters, e.g. uploading file “Chinese 工作的呢?.txt” will normally be saved as “Chinese ¹¤×÷µÄÄØ£¿.txt” but the filename can be encoded in UTF-8 as “Chinese+%C2%B9%C2%A4%C3%97%C3%B7%C2%B5%C3%84%C3%84%C3%98%C2%A3%C2%BF.txt”. To specify this, add the “encfilename” control name parameter, e.g. UploadFile:OtherFormsArea:template=UploadFileEdit:default:encfilename=UTF-8 The upload control displays the filename of the last file uploaded. To clear the value, just perform a “Put” statement on the control field, e.g. Put UploadP<UploadFileName> Please sign in to leave a comment.
https://support.cmfirstgroup.com/hc/en-us/articles/115000503666-CM-WebClient-File-Upload-Setup
CC-MAIN-2019-35
refinedweb
928
57.47
Suds on Pythonista Hi all, I am looking for a bit of help getting Suds to work on Pythonista. I have written a quick script to install the actual library.(Well I actually just modified one from here, but it seems to do the job. The problem is that I get an error when I import suds. It looks to me like Pythonista does not contain the 'new' module. This seems to be a standard module in Python 2.x, any thoughts on adding it? Or modifying Suds? Sorry, seems like an oversight on my part. You should be able to get the <code>new</code> module running pretty easily though. Just copy the code from here and add it to the script library (name it "new", the .py extension is appended automatically, but not shown, or just modify your download script accordingly): Thanks. Thats seems to have moved me along a bit. But now I am getting the following error. Any thoughts? Traceback (most recent call last): File "<string>", line 1, in <module> File "/var/mobile/Applications/87540C84-03EE-4FE0-89AC-A8BB0712E05A/Documents/suds/init.py", line 154, in <module> import client File "/var/mobile/Applications/87540C84-03EE-4FE0-89AC-A8BB0712E05A/Documents/suds/client.py", line 23, in <module> import suds.metrics as metrics AttributeError: 'module' object has no attribute 'metrics' I don't get that error when I <code>import suds</code> after running your script. What are you doing exactly that leads to this? I restarted pythonista and it imports now! Thx for the assistance.
https://forum.omz-software.com/topic/158/suds-on-pythonista
CC-MAIN-2017-34
refinedweb
258
68.87
This is a simple example taken from MSDN about multi-threading or, the way I like to say it, "Doing two things at once." I've modified the original example to make it easier to see how everything interacts. Easier for me anyway, since we are all different. One explanation may be adequate for some and not for others. I hope this can shine some light for some, as it did for me. Far from being any type of Guru on the subject, I'll try and explain it the best I can from my point of view. I honestly don't understand everything about threads, delegates and so on. The important thing in my mind is that I understood enough to have it do what I wanted in the end. The next step is understanding the rest. On start-up, a thread is fired that updates a label counting from 0 to 999. Buttons on the form give you the ability to start another thread that does the same thing, only at a slower pace. This shows you that both threads are separate from one another. Well, I guess it all started when I wanted to do two things at once, say, look up files in a directory. I wanted to have a nice progress bar move up and down or at least be able to move the Window around while it's doing it. If there's something I hate, it's not knowing if the application in front of me is alive or dead. After hours and hours of getting the error message, "Cross-thread operation not valid," I figured my way around it. Thread.Abort(). I tried several things and attempted to understand them as best I could. What I came up with was something that does exactly the same thing, but without Thread.Abort(). I hope this is a good thing. I haven't gotten any errors and believe me, I tried to click everywhere and at different moments to get one. An error I did get was, "Could not access an object that was in the process of disposing itself." In my case, this is the label I'm constantly trying to modify. I hope the ifstatement helps. If not, I'm sure someone will point it out. Anyway, I'd like to consider this a work in progress. By getting constructive comments, I'll be in a better position to make changes, learn and hopefully help others. This is, after all, a helpful community. I left the original code fragments and pasted the new code right under it so that people can compare the two. I hope I did better this time than the last. BeginInvoke()rather than Invoke(). Using Invoke()makes a synchronous call to the thread, causing the thread itself to wait until the GUI is updated before continuing on its way. BeginInvoke(), on the other hand, makes that call asynchronously. This means that the thread will continue working without waiting for the GUI to update itself. In this case, that is the label's Textproperty. So if for some reason the GUI hangs, my counter will keep on working without waiting for the label to update its text property from, say, 2 to 3 and so on. For a more concrete explanation, I suggest -- as it was to me -- reading the article here by Mr. S. Senthil Kumar. I also suggest reading the comments at the end of this page from the other users. This way you'll better understand the changes and why I made them. Abort()on it. This gives a certain amount of time to the thread to join. If for some reason it doesn't do so, it will kill it with Abort(). The code in has been changed accordingly and, as always, you should read up on the comments made by users, since the explanation is quite clear on the reasons to do so. A typo has been corrected thanks to Don Driskell; I was assigning nulltwice on a thread. I guess that's it then! I don't see much more that can be done without re-writing the whole article. Of course, I'm still trying learn and understand threads. Over time, I'll try and find the time to write another article. Threads are not as simple as portrayed here, but it's a start. Ok, let's start with the references at the top of the file. When you start a new project, be sure to add System.Threading with the others. If not, the only thread that will run will be the main application. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; Secondly, you'll need to declare a delegate and some threads. Think of them like this: The threads are little bits of code that will run parallel to each other, much like sprinters in the 100 meter dash. So, Thread threadLeft is runner 1 and Thread threadRight is runner 2. As for the delegate, well I try and look at it this way: It is a function that can be attached and executed in a thread other than the main thread. A better way to think of it may be that they are like pointers in C and C++. delegate void SetTextCallback(string text); private Thread threadLeft = null; private Thread threadRight = null; private volatile bool _stopLeft = false; #added this Ok, now let's have a thread run on start-up. It's actually surprising how much code you need to do this. In my example, I have a label that will count from 0 to 999, all the while still being able interact with the form. For example, click a button and move it around. These are the parts you need. I'll have threadleft start first. public Form1() { InitializeComponent();this.threadLeft = new Thread(new ThreadStart(this.ThreadProcSafe)); this.threadLeft.Start(); btnStartLeft.Text = "Stop Left"; } So, what we have here is pretty simple. InitializeComponent(); prepares all of your labels, buttons, etc. When that's done, it moves on to the new thread. The simplest way to explain it is this way, which is the way in which I understand it: Create a new instance of threadleft. When it's started, fire off the ThreadProcSafe() function. Let's look at that function now. The code below has been changed from this: private void ThreadProcSafe() { for (int x = 0; x < 1000; x++) { this.SetText(x.ToString()); Thread.Sleep(600); } } To this: private void ThreadProcSafe() { int x = 0; while(!_stopLeft) { this.SetText((x++).ToString()); Thread.Sleep(600); } } Once _stopLeft is true, the loop is exited and stops calling the function that changes lbl_left's Text property. ThreadProcSafe() is a very simple while loop. Nothing fancy, it just increments an integer by 1 and finishes once _stopLeft equals true. Thread.Sleep(600); in the loop is used to slow the counting process down. Since ThreadProcSafe() is in a separate thread, sleep only affects the while loop. It's also calling another function, SetText(string text). This is where the delegate comes in. The code below has been changed from this: private void SetText(string text) { if (this.lbl_left.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.lbl_left.Text = text; } } To this: private void SetText(string text) { try { //If needs to be invoked, invoke it then //call the delegate if (!lbl_right.Disposing) { if (this.lbl_left.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); //this.Invoke(d, new object[] { text }); this.BeginInvoke(d, new object[] { text }); // ***Replaced the Invoke line with BeginInvoke, // making it asynchronous*** } //If already invoked then update label with new value. else { this.lbl_left.Text = text; } } } catch (Exception e) { MessageBox.Show(e.Message); } } If I paraphrase the online MSDN, they say this about the Invoke method: It provides access to properties and methods that have been exposed by an object. Well, the object exposed in our case will be the label called lbl_left. Then we'll have access to its properties, such as Text. So, threadLeft starts and calls ThreadProcSafe, in which the while loop calls SetText. Once we have the ability to change the label's properties, we change Text to our integer from our loop. This will go on until you stop the application or kill the thread somehow. Since it's in its own thread, we can make a button to stop it. Here's the bit of code to do so. The code below has been changed from this: if (this.threadLeft != null && this.threadLeft.IsAlive) { this.threadLeft.Abort(); //Very, very BAD! this.threadLeft = null; SetText("Left"); btnStartLeft.Text = "Start Left"; } To this: if (!_stopLeft) { _stopLeft = true; if (!this.threadLeft.Join(1000)) { this.threadLeft.Abort(); } SetText("Left"); btnStartLeft.Text = "Start Left"; } Slap this in a button, in this case, the left button. It's actually pretty easy to understand. The reason for the if statement is that I have the start and stop functions associated with the same button. If the thread is not running, only having this.threadLeft.IsAlive as a condition will throw the message, "Object reference not set to an instance of an object." This basically means that it doesn't exist or is not instantiated with new. The way around it is to check if it's null. I know this.threadLeft = null; is probably overkill on my part, but I just want to make sure. Have a look at the code for the right button and you'll see that it's pretty much the same thing. If you still have threads running when you click the "X" on your form, they may not stop correctly. Override OnClose and slap it some code to check if any threads are running. This way, when you close the application with the "X," you are sure to stop the threads before closing the application. The code below has been changed from this: protected override void OnClosed(EventArgs e) { //Check if thread on the Left is alive //If alive (or not null) stop it. if (this.threadLeft != null && this.threadLeft.IsAlive) { this.threadLeft.Abort(); this.threadLeft = null; } base.OnClosed(e); } To this: protected override void OnClosed(EventArgs e) } _stopLeft = true; _stopRight = true; if (!this.threadRight.Join(1000)) //1000 milliseconds to execute one loop { this.threadRight.Abort(); //If it takes more than 1000ms then Abort is called } if (!this.threadLeft.Join(1000)) { this.threadLeft.Abort(); } base.OnClosed(e); } The thread is given 1000 milliseconds to execute one loop, hit the flag that says to stop and exit gracefully. If it takes more than 1000ms, then Abort() is called on the thread to kill it forcefully. Thanks, J4amieC, you explained it well. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/threads/SimpleThreading.aspx
crawl-002
refinedweb
1,802
75.5
Ticket #12076 (closed defect: fixed) QueryPerformanceCounter() Anomalies => Fixed in SVN Description Host: Ubuntu 10.10 Guest: Windows XP Pro, v5.1 SP3 Anomalies are observed with 64-bit counter value provided via QueryPerformanceCounter(). These anomalies being to appear after the VirtualBox is running continuously for ~4 days. The counter frequency is 3,579,545 Hz; host/guest time synchronization is disabled (GetHostTimeDisabled = '1') The guest calls QueryPerformanceCounter() every 50mS (0x2BB21 counts), logging the previous and current counter values when: (a) the previous count > current count, or (b) the current count is much larger than previous count (increase of 1 second or more, i.e., > 0x370000 counts) The following counter query results are logged: 1. Last > Cur Time: 0x0000011B:7FFFC526 > 0x0000011A:80001858 2. Last > Cur Time: 0x00000135:7FFFE61B > 0x00000134:80002C01 3. Last > Cur Time: 0x00000136:7FFFDB9F > 0x00000135:800021C0 4. Last > Cur Time: 0x0000013E:7FFFEBC2 > 0x0000013D:80003983 5. Last > Cur Time: 0x00000146:7FFFBCFE > 0x00000145:800003E8 6. Last > Cur Time: 0x00000147:7FFFF8EA > 0x00000146:80003EDA 7. Last << Cur Time: 0x00000183:FFFFC9DC << 0x00000185:00005E92 8. Last > Cur Time: 0x00000185:7FFFD751 > 0x00000184:8000402C 9. Last > Cur Time: 0x00000189:7FFFD519 > 0x00000188:80006D8F 10. Last << Cur Time: 0x00000188:FFFFC076 << 0x0000018A:0000071D At 3.579 MHz, the event of d31..d0 going from 0x7FFF:FFFF to 0x8000:0000 occurs every 1200 seconds (20 minutes). Note the third and fifth cases, where the bits d35..d32 went from 0x6 (b0110) to 0x5 (b0101) -- this is a subtraction, not just a clearing of bit d32. Log entries 7 and 10 appear to show bit d32 double-incrementing on the roll-over of d31..d0 from 0xFFFFFFFF to 0x1:00000000 The effect is, to the guest, time appears to jump forward or backward by 20 minutes. -- end of description Attachments Change History comment:2 in reply to: ↑ 1 ; follow-up: ↓ 3 Changed 5 years ago by asdel Replying to ramshankar: As far as I can see, the latest TSC fixes in 4.2.x wasn't backported to 4.1.x release. Could you, if possible, try upgrading to 4.2.18? Yes, we will upgrade and rerun the test. Since the anomaly required several days to manifest, we will need to let the upgraded version run for a while before reporting back. comment:3 in reply to: ↑ 2 Changed 5 years ago by asdel Now running v4.2.18. After approx 24 hrs, anomaly 'Type 1' has again appeared: Last > Cur Time: 0x0000051:7FFFD7E2 > 0x00000050:80001F38 comment:4 Changed 5 years ago by ramshankar Thanks. Could you please upload the VBox.log for the VM you are seeing this issue. comment:5 Changed 5 years ago by frank I think this problem was fixed in 4.2.x. Please update to 4.2.18. comment:6 Changed 5 years ago by asdel To reiterate: updated to 4.2.18 and the both forward and backward-jump anomalies are still present. We are seeing the anomaly on some hardware platforms but not others (same VirtualBox host/guest arrangement on all platforms). Note, the original problem description says QueryPerformanceCounter() is being called every 50mS, but it should say every 5mS (the count values reflect the 5mS period). comment:7 Changed 5 years ago by ramshankar I can't find any official documentation that guarantees that QueryPerformanceCounter() is monotonically increasing nor do I know which time source it is looking at in the VM. In fact, from my understanding it determines the time source(s) at runtime. It's unlikely that it's reading the TSC in this case though. I'm not ruling out a bug in our device emulation/interrupt delivery but we'll need a better understanding of what happens here (wraparound/sign extension/interrupt latency issues etc.) From the frequency, it's most likely using the ACPI timer in which case the 32-bit wraparound is expected but how correctly Microsoft deals with this is a bit fuzzy. See also comment:8 Changed 5 years ago by asdel Thank you for the feedback. To close one thought: since my last posing, the anomaly has been observed on both our hardware platforms, so a hardware-unique issue appears unlikely. Changed 5 years ago by asdel - attachment MAC_VBox.log added Log file under MAC OSX Changed 5 years ago by asdel - attachment QPC_Check.cpp added Source for Windows app demonstrating QueryPerformanceCounter anomaly comment:9 Changed 5 years ago by asdel Update to report that the anomaly is also present with Mac OSX host (the companion .log file has been attached). I have also attached source code for a simple program that detects and reports any anomalies found. An interesting consistency between the Linux and Mac platforms is that the anomaly only appears after 24+ hours of operation, and when it does appear, it is at first sporadic (i.e. occurring once every several hours). Eventually, it becomes more regular, and ultimately establishes a reliable 10-minute period. Are there specific suggestions on how else we might assist in achieving a better understanding of the fundamental issue? comment:10 Changed 5 years ago by klaus It would help to get the result from such a test program on real hardware which uses the same type of time source, i.e. the ACPI timer (sometimes called PMTIMER). The hardware implements only a 32 bit counter, and to me it looks like there is some quirk with extending it to 64 bits (honestly I have a hard time imagining how to do this safely at all with this brain-damaged hardware)... comment:11 Changed 5 years ago by Petr Vones I can confirm the issue with 4.3.6. The counter goes backward very often Host: Windows 7 x64 Guest: Windows Server 2008 R2 x64 Core i5 2540M HT enabled, VT-x enabled, Nested paging enabled, 2 CPU Here is the sample C# code: using System; using System.Diagnostics; using System.Threading; namespace PerformanceCounterTest { class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); long lastValue = sw.ElapsedTicks; for (int i = 0; i < 1000; i++) { Thread.Sleep(1); long elapsed = sw.ElapsedTicks; long diff = elapsed - lastValue; if (diff <= 0) Console.WriteLine("Loop: {0}, Error diff: {1}", i, diff); lastValue = elapsed; } sw.Stop(); Console.WriteLine("Stop"); } } } Sample output (Release configuration, no debugging): Loop: 2, Error diff: -263820 Loop: 13, Error diff: -239370 Loop: 16, Error diff: -261904 Loop: 20, Error diff: -261749 Loop: 51, Error diff: -261078 Loop: 57, Error diff: -261983 Loop: 61, Error diff: -259806 Loop: 78, Error diff: -261652 Loop: 85, Error diff: -261453 Loop: 100, Error diff: -262647 Loop: 113, Error diff: -262865 Loop: 116, Error diff: -261389 Loop: 145, Error diff: -261829 Loop: 152, Error diff: -261208 Loop: 169, Error diff: -261680 Loop: 186, Error diff: -262212 Loop: 218, Error diff: -261561 Loop: 240, Error diff: -261688 Loop: 246, Error diff: -261788 Loop: 250, Error diff: -259956 The same sample code has zero error output on the same machine running in host system. It has also zero error output on Virtual PC or VMWare virtualized machines. comment:12 Changed 5 years ago by Petr Vones Additional information, after restart of the virtual machine the issue has disappeared. Log of the broken session added. After saving the machine state and restoring the session the issue has appeared again with less occurence: Loop: 1, Error diff: -17926 Loop: 205, Error diff: -18108 Loop: 208, Error diff: -17730 Loop: 528, Error diff: -12459 Loop: 848, Error diff: -17473 Loop: 935, Error diff: -18373 Stop Changed 5 years ago by Petr Vones - attachment VBoxBroken.log added Session with broken counter comment:13 Changed 5 years ago by klaus Too bad that no one provided the information I tried to get in my previous reply - are any of the systems (physical or virtual) where the first test program runs without glitches which use PMTIMER (i.e. show a base frequency of 3.579 MHz)? I'm asking because this timer is only 32 bit, and it could be an OS bug which is hidden by the fact that Windows usually doesn't pick this time source. Also, the 2nd test program clearly shows a very different pattern and thus there might be a different issue behind it - but as there is no information what timer is used for the C# this is even harder to make any progress than with the original one. The only bit of useful information I can take from the log is that the TSC rate is very unusual... it is measured as 2.491681920 GHz, whereas the CPU declares itself to run at 2.60GHz. That's over 4% off. Also, there are suspicious RTC timer rate changes (first few very short, just ~15 msecs, but the 2nd last one 5 seconds and the last one over 83 seconds) - but they don't match your test program, which takes samples every millisecond, until it reaches 1000 loops, so overall it'll run for a bit more than a second. comment:14 Changed 5 years ago by florian I am not that familiar with all these timers so what I am writing might be completely wrong... If this is the case please correct me... Wouldn't it be sufficient to specify /USEPMTIMER in windows xp boot.ini file. As far as I understood it this will force windows to use the PMTIMER. I have done this on one pysical test machine and the frequency returned from QueryPerformanceFrequency has changed from something close to cpu frequency which indicates that TSC is used to 0x369e99 which is 3.579 MHz which indicates that PMTIMER is used. I have started our test program yesterday evening. As we only see the time jumping after more than 24 hours uptime I will report about the results tomorrow or maybe even better the day after tomorrow. I will post the code of our test program together with the results but it is almost the same compared to the test program of asdel. If I am wrong it would be nice if someone can post a comment so that I can stop this and spare some time... comment:15 Changed 5 years ago by florian Here are the logs both "Virtual Machine 1" and "Virtual Machine 2" are affected by the problem the "Physical Machine" works like a charm. I will let the machines run so that we can see that the frequency of the time jump increases with increasing uptime of the virtual machines. Virtual Machine 1 Frequency: 369e99 2014-02-17 14:16:20.978 Overflow from lower part are 1199 seconds ActTime=1cf51e ActPerfTime=195b7eab3 2014-02-20 00:14:15.868: PerfError -1198.862613 ActPerfTime=ae8013a59c 2014-02-20 01:14:16.075: PerfError -1198.863378 ActPerfTime=b08035319e snapshot: 201402200739 Virtual Machine 2 Frequency: 369e99 2014-02-17 14:15:30.512 Overflow from lower part are 1199 seconds ActTime=1c284b ActPerfTime=18a892e82 2014-02-20 05:34:16.174: PerfError -1198.862579 ActPerfTime=be802f9ccf 2014-02-20 07:14:14.829: PerfError -1198.862586 ActPerfTime=c2800b4370 snapshot: 201402200739 Physical Machine Frequency: 369e99 2014-02-17 16:08:45.828 Overflow from lower part are 1199 seconds ActTime=4c2c ActPerfTime=45f11bd snapshot: 201402200740 Changed 5 years ago by florian - attachment virtualMachine1.log added Changed 5 years ago by florian - attachment virtualMachine2.log added Changed 5 years ago by florian - attachment checkTime.cpp added comment:16 Changed 4 years ago by frank - Summary changed from QueryPerformanceCounter() Anomalies to QueryPerformanceCounter() Anomalies => Fixed in SVN We think we finally found and fixed the problem. The next 4.3.x maintenance release will contain the fix. comment:17 Changed 4 years ago by frank - Status changed from new to closed - Resolution set to fixed Fix is part of VBox 4.3.18. As far as I can see, the latest TSC fixes in 4.2.x wasn't backported to 4.1.x release. Could you, if possible, try upgrading to 4.2.18?
https://www.virtualbox.org/ticket/12076
CC-MAIN-2018-47
refinedweb
1,988
72.05
Conceptually I don't see any difficulties with using Slide for Cocoon, in fact this is what we have in the planning at our company. I've seen the Slide/Repository integration developements in the latest Cocoon CVS-HEAD but don't really understand what the need is for all that code. The concept of Slide is that it is abstracted from the level of the application. It basically substitutes tomcat's file-system based resource context with its own slide based resource context, thus making it completely transparent to the application. What that means in terms of a usage scenario is something like the following: - Configure a new Slide namespace and start Slide-Tomcat - Drop an unpacked cocoon into the WebDAV root, i.e. in Slide under /files In the default configuration of Slide, you can now edit your content/stylesheets/sitemaps over WebDAV at , administer Slide at , and surf cocoon at The thing you need to remember is that since the Slide resources have been installed as jndi resources under the context, source resolving that depends on absolute filesystem paths will not work. I am not sure how Cocoon handles this exactly but I do foresee some potential problems in this area. >From the Slide user guide: "Any web application which is designed so that it doesn't access the files within its web application directory using direct filesystem access should run without any modification (file access should be replaced by calls like ServletContext.getResource, which abstract filesystem access). This includes applications like Jasper, and any web application written according to Sun's guidelines" -----Oorspronkelijk bericht----- Van: Michael Homeijer [mailto:M.Homeijer@devote.nl] Verzonden: maandag 23 september 2002 12:06 Aan: 'Martin Holz '; 'cocoon-dev@xml.apache.org ' Onderwerp: RE: WebDAV sitemap There's allready a RequestMethodSelector that can do map:select type="webdav". I prefer this one since I don't like writing code. ;-) I don't think Slide can do the job here, because it works om a standard type of repository or interface, not on an application build in Cocoon. With webdav on Cocoon you can map the protocol to anything written in Cocoon. Your application will then act as a virtual webdav repository. I am not sure what can be reused to implement this. Michael -----Original Message----- From: Martin Holz To: cocoon-dev@xml.apache.org Sent: 23-9-2002 11:45 Subject: Re: WebDAV sitemap On Monday 23 September 2002 10:07, Michael Homeijer wrote: > Hi, > > I found and received info on slide, but I was thinking of a sitemap that > has matchers and additional actions, transformers etc. that make supporting > webdav from an application much easier. This way you can easily expose an > application as a webdav resource. A sample sitemap would contain the > following matchers: > > <map:match > <map:act > <map:generate > <map:serialize/> > </map:act> > </map:match> > > <map:match > </map:match> > > <map:match > </map:match> > > <map:match > </map:match> > > etc. > > Does this make sense? Yes, adding Webdav methods to the cocoon makes sense. However it would duplicate the work done for the slide webdav servlet. Slide webdav contains lot of code, so porting it to cocoon is a major project. Do you want to extend the matcher or introduce a new one? You could do either <map:match type="wildcard" method="PROPFIND" pattern="**./ > .... </map:match> or <map:match type="wildcard" pattern="**./ > <map:select <map:when ... </map:when> <map:when ... </map:when> </map:select> </map:match> I would prefer the second solution, since you don't have to change existing matchers. Mart
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200209.mbox/%3C84F0A43A4248CE45B5C0E20F4C40779C5FB0@naomi.webworks.nl%3E
CC-MAIN-2014-15
refinedweb
591
53.61
As the name indicates a Canvas is a region where you can draw things such as circles, triangles, ovals or any other shape. Basically it is a graphical component that represents a region. It has got a default method which is paint() method. Canvas class can be sub classed to override this default method to define your own components as shown below in the example. import java.awt.*; import java.applet.*; public class MyCanvas extends Applet { public MyCanvas() { setSize(80, 40); } public void paint(Graphics g) { g.drawRect(0, 0, 90, 50); g.drawString("A Canvas", 15,15); } } Here is the Output: Download this example.
http://www.roseindia.net/java/example/java/awt/canvas.Shtml
CC-MAIN-2016-30
refinedweb
105
66.03
ARP spoofing, also called ARP Cache poisoning, is one of the hacking methods to spoof the contents of an ARP table on a remote computer on the LAN. Two addresses are needed for one computer to connect to other computer on an IP/Ether network. One address is the MAC address; the other is the IP address. A MAC address is used on a local area network before packets go out of the gateway; an IP address is used to surf the Internet through a gateway. There is a protocol that asks "who has this MAC address" and answers the question; that is called ARP (Address Resolution Protocol). What the ARP asks the target address for sending is called the ARP Request or ARP who has, and the ARP that responds to the request is called the ARP Request or ARP who has. Although wrong information is inserted into ARP, the computer believes that the information of the ARP is valid and saves the information in own ARP table for a while. This is ARP spoofing. Fig 1 ARP Spoofing. This program needs the WinPcap driver and has been tested on WinNT/2000/XP/2003 etc. CBuildPacket CBuildPacket is a class that builds a WinArpSpoofer program. Its general purpose is to easily build a cooked packet throwing into the network. It is hard to understand and use existing libnet libraries and so forth in MS Visual.NET, so I have newly designed this class. The current version of the CBuildPacket class provides some methods for building and sending an ARP to the network. The future version of this class will provide many various types of network packets for building TCP, IP, icmp, and the like. WinArpSpoofer has been built based on the current CBuildPacket class. It could pull and collect all packets without If you do as shown above, an ARPrequest with the wrong information is sent to a target computer and the the target computer knows that the MAC address of A is the Attacker's MAC addres in the ARP table. Therefore, all the packets that the target sends to A are sent to the Attacker. ARPreply packets are used to keep ARP spoofing. Likewise, the target knows that the MAC address of A is the MAC address of the Attacker in an ARP table. Therefore, all the packets that Target sends to A are sent to Attacker.. OpenAdapter( ) BuildARP( ) SendPacket( ) CloseAdapter( ) ConvertMACStrToHex( ) #include <packet32.h> #include <BuildPacket.h> CString Target; // Ethernet Address of Target CString Attacker; // Ethernet Address of Attacker CString Gateway; // Ethernet Address of Gateway CString TargetIP; // IP Address of Target CString AttackerIP; // IP Address of Attacker CString GatewayIP; // IP Address of Gateway CString TargetMAC; // MAC Address of Target CString AttackerMAC; // MAC Address of Attacker CString GatewayMAC; // MAC Address of Gateway . . . void SpoofApp::SpoofTarget() { CBuildPacket *arpPacket = new CBuildPacket; arpPacket.OpenAdapter( AdapterName ); // To open an adapter arpPacket.BuildARP( // To build a ARP // packet Attacker, Target, ARPOP_REQUEST // for Transmission on // MAC layer GatewayIP, AttackerMAC, // Spoof IP address of // Gateway to // Attacker IP. TargetIP, TargetMAC // ); arpPacket.SendPacket(); // Send a packet to network arpPacket.CloseAdapter(); // To close the adapter } void SpoofApp::CollideTargetIP() { CBuildPacket *arpPacket = new CBuildPacket; arpPacket.OpenAdapter( AdapterName ); // To open an adapter arpPacket.BuildARP( // To build an ARP // packet Attacker, Target, ARPOP_REQUEST // for Transmission // on MAC layer TargetIP, AttackerMAC, // Collision because // source TargetIP is // dest TargetIP TargetIP, TargetMAC // ); arpPacket.SendPacket(); // Send a packet to network arpPacket.CloseAdapter(); // To close the adapter } void SpoofApp::UnspoofTarget () { CBuildPacket *arpPacket = new CBuildPacket; arpPacket.OpenAdapter( AdapterName ); // To open an adapter arpPacket.BuildARP( // To build a ARP packet Attacker, Target, ARPOP_REPLY // for Transmission on MAC // layer GatewayIP, GatewayMAC, // To recover spoofed ARP // Table TargetIP, TargetMAC // ); arpPacket.SendPacket(); // Send a packet to network arpPacket.CloseAdapter(); // To close the adapter } This article has explained what ARP Spoof is and how to use WinArpSpoof based on CBuildPacket. The WinArpSpoof program is a strong Windows-based ARP spoofer program with.
http://www.codeproject.com/Articles/6579/Spoofing-the-ARP-Table-of-Remote-Computers-on-a-LA
CC-MAIN-2014-52
refinedweb
651
55.54
Contributor 2290 Points Dec 18, 2014 01:02 PM|santhoshje|LINK You can set route /api/project/id/users using attribute routing as given below [RoutePrefix("api/Project")] public class ProjectController : ApiController { [Route("{id:int}/Users")] [HttpGet] public UserModel Users(int id) { } } route action webapi All-Star 27134 Points Dec 19, 2014 04:58 AM|Shawn - MSFT|LINK Hi, For this scenario, if you want to pass parameter within the url, you could try to change the routing template. With the default routing template, Web API uses the HTTP method to select the action. However, you can also create a route where the action name is included in the URI:<div> routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );</div> For more detailed information, you could refer to: Regards route action webapi Dec 19, 2014 05:11 AM|only_you|LINK I use attribute routing api/project/{pid}/users It works fine, if when pass parameter pid manualy. I need to pass parameter through querystring using angular $http.get() I tried this this.getItems = function () { return $http({ url: '/api/project/{pid}/users', method: 'GET', data: $.param({pid:123}) }); } In fiddler I got 404 error. route action webapi Contributor 2290 Points Dec 20, 2014 04:15 PM|santhoshje|LINK Here the issue is creating dynamic Rest url in Angular JS. I believe it is possible to make Rest call with the url you mentioned using $resource in Angular JS. Please post this requirement in Angular JS forums. route action webapi 5 replies Last post Dec 20, 2014 04:15 PM by santhoshje
https://forums.asp.net/t/2024886.aspx?Right+way+to+set+web+api+route
CC-MAIN-2018-51
refinedweb
266
53.71
It looks like the headers shipped by btrfs-progs have changed recently. The git version ships them as a submodule, and the PyPI archive includes them as well; that should work better. Search Criteria Package Details: bedup 0.10.1-1 Dependencies (9) - python - python-alembic - python-cffi - python-distribute (python-setuptools) - python-mako - python-sqlalchemy (python-sqlalchemy-0.7.9, python-sqlalchemy-git) - python-xdg - btrfs-progs (btrfs-progs-git) (make) - gcc (gcc-git, gcc-multilib-git, gcc-multilib-x32, gcc-multilib) (make) Required by (0) Sources (1) Latest Comments G2P commented on 2016-10-26 16:26 It looks like the headers shipped by btrfs-progs have changed recently. Enverex commented on 2016-10-26 15:08 Build fails pretty badly here - Crazyachmed commented on 2016-06-04 21:13 please add aarch64 to supported list. seems to work for me ;) darkbasic commented on 2016-05-18 09:27 Sorry I wanted to comment on python-editor, not bedup. Anyway I confirm that 0.10.1 fixed the build issue. G2P commented on 2016-05-18 07:34 The error fryfrog reports is fixed in. I just pushed a point release with the fix. darkbasic commented on 2016-05-18 07:16 ==> Removing existing $pkgdir/ directory... ==> Starting build()... Traceback (most recent call last): File "setup.py", line 1, in <module> from setuptools import setup ImportError: No module named 'setuptools' ==> ERROR: A failure occurred in build(). fryfrog commented on 2016-05-11 05:56 Should one still use this? I tried to build it, but it fails. Maybe gcc has had some big changes since this was last released by the source? :/ justin8 commented on 2013-12-30 07:25 FYI, for pkgbuilds, anything in 'base-devel' is assumed to be installed. that includes gcc. See: see As for conflicts with th. e git version, the git version should have a conflicts and a provides for bedup (which is already there). see: WonderWoofy commented on 2013-06-03 02:47 Yeah, bedup git totally builds and installs... I wonder where I went wrong, as looking over the PKGBUILD, mine looked pretty much the same. Now to see if it works... Thanks for that. I guess I can agree that having gcc in the makedepends certainly doens't hurt anything, and I think the ability to run makepkg w/o gcc is as it should be probably. I think the only thing with the git package is that it should have "conflicts=('bedup')" so that in the event that bedup is installed bedup-git will not error out with "file exists in filesystem". Now I wish I handn't deleted the PKGBUILD I made off of yours so that I could compare the two. I woundn't be surprised if I just had some kind of typo in there. I guess when I think about it I really didn't put much time into debugging it. omgold commented on 2013-06-02 15:55 > FYI, python-distribute is in the makedepends array, but it is actually required for bedup to run. Right. Thanks. Fixed it. > Also, I think that the 'gcc' makedepend is assumed in the case of AUR programs. I mean I know that not everything needs a C compiler, but I haven't noticed other AUR entries including 'gcc' as a makedep. Ehm, I tried it, and actually makepkg can be run without having gcc installed. So I guess, any package containing C code should have a makedepends on gcc, no? > Out of curiousity, is there any reason why you chose to use the pypi version 0.90 rather than makeing a bedup-git package? I used it, because in the instructions at the github repo it was mentioned as one of the 'official' ways to build it. As the git repo does not seem to have a tag for a newer stable version and I wanted to have a stable one, I went for pypi. > Are you familiar enough it its deps to make such a package? If so I would really appreciate it if you did that, as simply trying to convert this PKGBUILD to be a git type did not seem to work. Thoughts? Okay, I now also created a bedup-git package. Didn't stumble over anything out of the ordinary. For me it seems to work. Maybe you can give it a try.
https://aur.archlinux.org/packages/bedup/
CC-MAIN-2017-13
refinedweb
730
73.58
Uncyclopedia:Conservation Week/2008-A From Uncyclopedia, the content-free encyclopedia Hardwick Fundlebuggy Currently rewriting JxC Syndrome - Dibs on probability - The life of MC Hammer --done The UnIdiot New Jersey, hopefully THEDUDEMAN Currently rewriting TheLedBalloon - Conservapedia - Working on Lake Spooky here. - P.M., WotM, & GUN, Sir Led Balloon (Tick Tock) (Contribs) 01:50, Mar 16 Cap'n Ben - The Phantom of the Opera - rewritten - Robots -done - Transylvania - dibs RAHB I've got my eye on one or two, we'll see if I have time to finish any this time around. Under user Done: Awesome Sauce It sucks so much this qualifies. - I can't say it counts, unfortunately. It's practically the only namespace that doesn't count...except for Mediawiki:. ~ Jacques Pirat, Esq. Converse : Benefactions : U.w.p.5/03/2008 @ 00:57 Raxvulpine I'd been meaning to rewrite Post Rock for a while --- I've started at User:Raxvulpine/Post Rock. Sceptical nick Sk8R Grl I'm going for Gordon Ramsay.--XOXOXO, Love ya! Sk8R Grl Talk to Me 18:33, 4 March 2008 (UTC) - You might wanna hold off on that there - Mordillo's just put the current version up on VFH. --SirU.U.Esq. VFH | GUN | Natter | Uh oh | Pee 22:58, Mar 4 - Fine. I'll do another article on the proofreading page. Most of them suck. User:Sk8R Grl/sig 17:09, 6 March 2008 (UTC) - Worst_100_Pick-Up_Lines_of_All_Time--done - Metal_Sonic--and done. - That's 2 for me :-D User:Sk8R Grl/sig 18:43, 7 March 2008 (UTC) user:Sycamore Costa Rica, Possibly Norway Sycamore 19:29, 4 March 2008 (UTC) THE DJ Irreverent - Endangered species hopefully... Necropaxx Dibs on weasel, maybe. Inspiration is a fickle mistress. Plus I'm somewhat lazy. • • • Necropaxx (T) {~} 00:48, 5 March 2008 (UTC) Pillowcase I'll do Your future, if mine involves any spare time. MrN9000 Well, I'm going to dabble with the articles found in category:Articles to fix and category:Ugly. SysRq I'll start out with and see where it goes from there. Pandora. Naughty Budgie Try this: - Simon Cowell - Emoticons Didn't need to be rewritten that much. - Mew I am rewriting: CVJX Currently rewriting Arotenbe Axis of Fluffy Bunnies and Rainbows– done SETI– done Plot– done Orian57 - Soap Operas - (working on) The Millennium Monkey - pizza i dont know - chick magnet - falafel how am I doing? Wnt - The Matrix (films) couldn't help myself
http://uncyclopedia.wikia.com/wiki/Uncyclopedia:Conservation_Week/2008-A
CC-MAIN-2016-26
refinedweb
404
66.23
David Van Couvering wrote: > Hi, all. I have done further investigation, and conversations I have > had convince me that (a) System.exit() is the proper way to set an > exit code and (b) embedding apps in general should not be calling > main(), and (c) since we have a policy of always expecting to be > embedded, tools should have a policy of providing a callable execute() > method that doesn't do System.exit() but instead throws exceptions. > > > DB2jServerImpl.main(new String[] { "ping", "-p", "2000"} ); > > rather than > > DB2jServerImpl impl = new DB2jServerImpl() > impl.setCommand("ping"); > impl.setPort("2000"); > impl.execute(); > DB2jServerImpl is not a public class. NetworkServerControl is where the public api lives, so if we did use the JavaBean or execute approach the methods would live there. > So, I would like to propose the following: > > - Define a new abstract class, e.g. org.apache.derby.tools.BaseTool, > that looks something like this: > > public abstract class BaseTool > { I feel a little funny about NetworkServer being called a tool, but maybe it's ok for NetworkServerControl (a tool that controls the server?). > > public abstract void execute(String[] args) throws Exception; > > /** > * Basic main routine, can be overridden if needed > */ > public static void main(String[] args) > { > try > { > execute(args); > } > catch ( Exception e ) > { > e.printStackTrace(); > System.exit(1); > } > System.exit(0); > } > } > > and then have our tools implement this, e.g. > > public class MyTool extends BaseTool > { > public void execute(String[] args) throws Exception Should this be: public static void execute(String[] args) throws Exception? > { > // yada yada > } > } > > and then applications can do > > MyTool.execute(new String{ "ping" }); > Well my comment is that I am glad I took this off the starter task list when I saw you picked it up. But I have a question. With regard to Network Server, would this just be an additional way to control network server if you would prefer to use execute instead of the existing NetworkServerControl API? If so, would one be preferred over the other? I asked Rajesh to respond regarding his original Eclipse requirements, but while the execute thing sounds interesting, I wonder how it addresses the Eclipse calling model? Maybe a static method is all that is needed and execute would suffice if it is a static method. Still also I wonder about what Dan said: Never make assumptions that your Java program is controlling the JVM and has the right to call methods like System.exit, then multiple Java "main" programs can hook up together without problems. I guess that is how I would like to see it in an ideal world. Maybe that is not possible, but I would like to hear a little bit more input before we make such a decision about the public API's. Thanks Kathey
http://mail-archives.apache.org/mod_mbox/db-derby-dev/200504.mbox/%3C42716F7D.9070804@sbcglobal.net%3E
CC-MAIN-2014-41
refinedweb
453
61.36
Overview of ASP.NET Core MVC By Steve Smith ASP.NET Core MVC is a rich framework for building web apps and APIs using the Model-View-Controller design pattern.. ASP.NET Core MVC>. [Authorize] public class AccountController : Controller formatters to add support for your own formats.. Learn more about how to test controller. . Additional resources - MyTested.AspNetCore.Mvc - Fluent Testing Library for ASP.NET Core MVC: Strongly-typed unit testing library, providing a fluent interface for testing MVC and web API apps. (Not maintained or supported by Microsoft.) - Prerender and integrate ASP.NET Core Razor components - Dependency injection in ASP.NET Core
https://docs.microsoft.com/en-US/aspnet/core/mvc/overview?view=aspnetcore-5.0
CC-MAIN-2022-05
refinedweb
103
55.2
Iterator::Misc - Miscellaneous iterator functions. This documentation describes version 0.03 of Iterator::Misc, August 26, 2005. aren't as broadly useful as the ones in Iterator::Util. They are here to keep the size of Iterator::Util down. For more information on iterators and how to use them, see the Iterator module documentation. $iter = ipermute (@list); $array_ref = $iter->value(); Permutes the items in an arbitrary list. Each time the iterator is called, it returns the next combination of the items, in the form of a reference to an array. Example: $iter = ipermute ('one', 'two', 'three'); $ref = $iter->value(); # -> ['one', 'two', 'three'] $ref = $iter->value(); # -> ['one', 'three', 'two'] $ref = $iter->value(); # -> ['two', 'one', 'three'] # ...etc $iter = inth ($n, $another_iterator); Returns an iterator to return every nth value from the input iterator. The first $n-1 items are skipped, then one is returned, then the next $n-1 items are skipped, and so on. This can be useful for sampling data. $iter = irand_nth ($n, $another_iterator); Random nth. Returns an iterator to return items from the input iterator, with a probability of 1/$n for each. On average, in the long run, 1 of every $n items will be returned. This can be useful for random sampling of data. $iter = ifibonacci (); $iter = ifibonacci ($start); $iter = ifibonacci ($start1, $start2); Generates a Fibonacci sequence. If starting values are not specified, uses (1, 1). If only one is specified, it is used for both starting values. $iter = igeometric ($start, $end, $multiplier) Generates a geometric sequence. If $end is undefined, the sequence is unbounded. Examples: $iter = igeometric (1, 27, 3); # 1, 3, 9, 27. $iter = igeometric (1, undef, 3); # 1, 3, 9, 27, 81, ... $iter = igeometric (10, undef, 0.1); # 10, 1, 0.1, 0.01, ... All function names are exported to the caller's namespace by default. Iterator::Misc uses Exception::Class objects for throwing exceptions. If you're not familiar with Exception::Class, don't worry; these exception objects work just like $@ does with die and croak, but they are easier to work with if you are trapping errors. For more information on how to handle these exception objects, see the Iterator documentation. Class: Iterator::X::Parameter_Error You called an Iterator::Misc function with one or more bad parameters. Since this is almost certainly a coding error, there is probably not much use in handling this sort of exception. As a string, this exception provides a human-readable message about what the problem was. Class: Iterator::X::Exhausted You called.
http://search.cpan.org/~roode/Iterator-Misc-0.03/Misc.pm
CC-MAIN-2015-06
refinedweb
416
59.5
Author: Eventi Source: // welcome to reprint, please keep this statement. Thank you! 1 The origin of the C language In 1972, Dennis Ritch and Ken Thompson of Bell Labs designed the C language while developing the UNIX operating system. The C language is based on the B language (invented by Thompson). 2 C language features 2.1 Advantages Design features: Can easily complete self-oriented planning, structured programming and modular design; programs written in C language are easier to understand and more reliable. Efficiency: It runs fast and is closer to the efficient features and fine-tuning capabilities of assembly language. Portability: The C program only needs to be slightly modified or not modified, and can be compiled and run on other systems by the C compiler of other systems. Regardless of whether you use a home computer, a professional workstation, or a mainframe; whether you use Windows, Unix, Linux, or Mac operating systems; from 8-bit microprocessors to supercomputers, you can find C compilers for specific systems. Powerful and flexible: Many operating systems have C program code and compilers and interpreters in many programming languages are implemented in C. C programs can also solve physics and engineering problems, and can even be used to make movie special effects For programmers: programs can use C to access hardware and control bits in memory. 2.2 Disadvantages C is powerful, but it's easy to make mistakes. In particular, the use of pointers is very powerful, but a little carelessness is prone to errors. 3 C language standard 3.1 K & R C or Classic C In 1987, the first edition of The Programming Language, co-authored by Brian Kernighan and Dennis Ritchie, was a recognized C standard, often called K & R C or Classic C. In fact, due to the lack of official standards, the libraries provided by the UNIX implementation have become standard libraries. 3.2 ANSI / ISO C standard (also called C89 or C90 standard) The American National Standards Institute (ANSI) formed a committee (X3J11) in 1983, developed a new set of standards, and was officially announced in 1989. The standard defines the C language and the C standard library. The International Organization for Standardization adopted this C standard (ISO C) in 1990. ISO C and ANSI C are identical standards. The final version of the ANSI / ISO standard is often called C89 (because ANSI approved the standard in 1989) or C90 (because ISO approved the standard in 1990). In addition, because ANSI first issued the C standard, the industry usually uses ANSI C. 3.3 C99 Standard In 1994, the ANSI / ISO Joint Committee (C9X Committee) began to revise the C standard, and finally released the C99 standard. 3.4 C11 Standard The Standards Committee promised in 2007 that the next version of the C standard would be C1X, and finally released the C11 standard in 2011. 4 C program compilation and linking The source code of the C program is compiled by the compiler to generate object code, and the object code, library code, and startup code are generated by the linker of the linker to generate executable code. The process is shown in the following figure: 5 Basic structure of C program 5.1 Typical C Program A simple C program code: #include <stdio.h> main( void ) /* 一个简单的C程序 */ int main ( void ) / * A simple C program * / { num; /* 定义一个名为num的变量 */ int num; / * define a variable named num * / = 1 ; /* 为num赋值 */ num = 1 ; / * Assign num * / " I am a simple " ); /* 使用printf()函数 */ printf ( " I am a simple " ); / * Use printf () function * / " computer.\n " ); printf ( " computer. \ n " ); " My favorite number is %d because it is first.\n " ,num); printf ( " My favorite number is% d because it is first. \ n " , num); 0 ; return 0 ; } A simple C program can be parsed into the following structure: 5.2 Basic C Program Concepts 5.2.1 #include directives and header files #include This line of code is a C preprocessor directive. Usually, the C editor will do some preparation work on the source code before compiling, that is, preprocessor. The effect of #include <stido.h> is equivalent to typing everything in the stdio.h file into the line where it is located. 5.2.2 main () function C programs must start with the main function and end with the end of the main function. 5.2.3 Notes Proper comments can improve the readability of the program. Two comment styles are supported in C programs. details as follows: 这是一条注释,可多行注释 */ / * This is a comment, which can be multi-line commented * / 这是一条注释,只能单行注释(C99新增的注释风格) // This is a comment, which can only be a single-line comment (new C99 comment style) 5.2.4 curly braces, function bodies, and blocks { ... } In general, all C functions use curly braces to mark the beginning and end of the function body. For example, the main function: main( void ) int main ( void ) { 函数体 */ / * Function body * / } Braces are also used to combine multiple statements in a function into a unit or block. For example: (;;) for (;;) { 多条语句 */ / * Multiple statements * / } 5.2.5 Statement num; int num; This statement accomplishes two things. First, there is a variable named num in the function, and second, int indicates that num is an integer. In C, all variables must be declared before they can be used. 5.2.6 Assignment ; num = 1 ; When the int num; statement is executed, the compiler reserves space for the variable num in the computer's memory, and then stores the value in the previously reserved position when executing the line assignment expression. 5.3 Debugging the program 5.3.1 Syntax errors If you do not follow the rules of the C language, you will make grammatical errors. The compiler can usually detect this. 5.3.2 Semantic errors Semantic errors are errors in meaning. The compiler generally cannot detect this. Study Books "C Primer Plus Sixth Edition" Notes
http://www.itworkman.com/74897.html
CC-MAIN-2022-21
refinedweb
977
62.68
HOUSTON (ICIS)--Brazil consumed 1.06m dry metric tonnes (dmt) of liquid caustic soda from January through May 2014, down by 1.7 % from the 1.08m dmt consumed during the same period in 2013, the country’s association of chlor-alkali industries, Abiclor, reported this week. Brazil’s domestic production of liquid caustic soda between January and May of 2014 was 579,341 dmt, 0.3% lower than the 581,112 dmt produced during the same period in 2013, Abiclor said. Liquid caustic soda imports from January through May 2014 were 487,209 dmt, down by 3.5% from 504,939 dmt imported in 2013. The US was Brazil’s principal source at 452,016 dmt, corresponding to a 93% share. Major markets consuming liquid caustic soda in Brazil in 2014 are paper and cellulose with 142,290 dmt, chemical/petrochemical with 84,652 dmt, aluminium with 41,926, soaps and detergents with 33,646 dmt and metallurgy with 27,741 dmt. Caustic soda supply in Brazil is adequate to meet steady demand, sources said. Caustic soda producers in ?xml:namespace> With shale gas dominating the headlines and ethane a major talking point in the petrochemical industry, ICIS editors in Houston are closely monitoring the situation. See the ICIS special report on shale, ethane and US ethane exports here.
https://www.icis.com/resources/news/2014/06/26/9795928/brazil-jan-may-caustic-soda-consumption-drops-1-7-year-on-year/
CC-MAIN-2017-39
refinedweb
220
57.16
Hi,<?xml:namespace prefix = o Up to know we have used Microsoft Office Project's OLEDB Provider to extract project data from MPP files. We are currently looking at possibilities of replacing this dated interface with something like Aspose.Tasks. I’m having difficulty to extract some calculated task columns from the Aspose.Tasks API e.g. Confirmed, Cost Variance, CPI, CVP, Duration Variance, EAC etc. Perhaps I missed it, but I couldn’t find anything in the product documentation. Also, are there perhaps any documentation available that maps the MSP OLEDB task fields to those of the Aspose.Tasks API? Any assistance would be appreciated.
https://forum.aspose.com/t/calculated-columns/4928
CC-MAIN-2022-05
refinedweb
106
59.19
A great thing about building applications for the internet is that people from all around the world can benefit from your effort. You can gather new users from Taiwan to Colorado and meet their needs just as effectively. In this global context, it can be good to provide your users with local flavor to help them feel connected to you and your applications. It can also be useful for you to know where your users are coming from to make sure that your infrastructure is configured in the best way. In this post, I show you how to get started with Python geocoder using free services and the requests module to gather and leverage data. Geolocation is the process of identifying the geographical location of a person or device by means of digital information. You use some data you have to gather more data for the benefit of your users. This can be important when dealing with information for users from the EU, for example—it can help you comply with laws around data protection. Identifying where your users are can also help to provide a more bespoke and effective service. A quick note: this is a Python guide, so I'm going to make a few assumptions. I'll assume that you're using Python 3, you have it installed, and you know the basic syntax. Nothing we'll cover here is very complicated, but hopefully it'll be quite interesting. If you're having trouble getting started, have a look at the Python site. One of the key pieces of information you can use to find out where your users are is their IP address. It's possible for users to use a proxy service to seem to be from somewhere else. Having said that, for most users this is a helpful approach. I've looked into a number of applications that provide this service and have decided to use ipstack for this tutorial. If you sign up for their free account, you get 10,000 calls per month, which is more than enough to get started. I think the API for this service is quite straightforward. Once you've signed up, you'll be taken to a dashboard and get an API key. This key is used to identify your application to the service, allowing you to make the calls. Keep this information safe and private, because anyone can use it and pretend to be you. That might not be a huge deal for this free service, but it's a good habit to get into. Let's see how good the service is at finding you. Get your IP address (get it in plain text by going here), open a new tab in your browser, and paste the link below. Of course, make sure you swap out the relevant details. If everything has gone correctly, you should get a response that shows the location of your IP address—great stuff! Now you know where you are, although hopefully this wasn't news to you. It isn't going to be practical for you to do this manually in the browser for every user. Given that, we're going to use the Python requests module to make the same call and collect the information for us. import requests key = "YOUR-API-KEY" ip = "YOUR-IP-ADDRESS" url = "" + ip +"?access_key=" + key response = requests.get(url).json() print(response) Here, I'm declaring the key and IP address as variables and building up the URL using those components. I then use the requests module to carry out an HTTP request on that URL and convert the response to a JSON array. In Python, this is a dictionary, so you'll be able to access any of the individual pieces of information by adding the key name. For example, response['country_name'] will tell you what country the IP address is based in. If this was part of a larger application, I'd want to declare the key in a configuration file instead of cluttering up this code. Also, I'd like a function to pass the IP address to and get some information back. You can see from the response all of the information that you could get, but for my purposes, I'm going to get the longitude and latitude of the city closest to the IP address. I'll improve the code above by using a function. def lng_lat_from_ip(ip): url = "" + ip + "?access_key=" + key response = requests.get(url).json() return (response['longitude'], response['latitude']) longitude, latitude = lng_lat_from_ip(ip) Awesome! Now I have a function that can take the IP address and return the map coordinates. You can alter this function to return any of the keys that you'd prefer to discover or use. Once you have the user's location, you can decide how you might adapt their experience. You may store their user data differently, or you may want to do something more fun. I'm going to work out how far my users are from me. To do that, I'm going to use a module called geopy. Let's install it! pip install geopy --user Once you've installed the module, you can use it straight away. You don't need to sign up for a service to access this functionality. I'm based in Brighton, England. I'm going to use my details to find out how far my users are from here. from geopy.distance import geodesic Brighton = (longitude, latitude) # I used our function above to get this. cleveland_oh = (41.499498, -81.695391) # I looked this one up. print(geodesic(Brighton, cleveland_oh).miles) This will print the distance in miles from Brighton to Cleveland. You can change the units to meters or feet if that's more relevant. I can now let a user from Cleveland know that I am 8,336 miles away from them. You can read more about the other possibilities in the documentation. There are two ways to measure distance implemented—geodesic and great-circle—and the documentation discusses them both. In my use case, there was no difference, but you may find that one is better than the other and you need the increased accuracy. Another free and useful service that you can sign up for, GeoNames, allows you to access a wide variety of location-based data. The daily call limit to this service is 20,000, so this should be more than enough for any use case. One thing to look out for is that once you've registered, you need to enable "Free Web Services." This is a link at the bottom of the login page. I find this to be a really useful service and have used it to tell the weather where my users are and even find some interesting local Wikipedia articles. Let's find out what the weather is like. We'll start, as before, with testing in our browser, and then we can write the Python function to do the heavy lifting for us.<YOUR-LAT>&lng=<YOUR-LNG>&username=<YOURUSERNAME> The good thing is, you have a function to find your latitude and longitude from your IP address, so you can use that to gather the information. According to the weather information, there are few clouds where I am. By now, you can probably write the function yourself to carry this out for you. I'm going to construct the URL, use the requests module to make the call, and then return the output. import requests username = "YOUR USERNAME" def weather_from_lat_lng(lat, lng): url="" + lat + "&lng=" + lng + "&username=" + username response = requests.get(url).json() return response print(weather_from_lat_lng("41.499498", "-81.695391")) As before, I'm declaring my username in code here, which isn't a best practice. You could use separate configuration files or even environment variables to keep your keys safe. You can call this function and give a visual indication of cloud cover on your site. Or, less frivolously, you could track if there's any correlation between the weather and use of your application. I've just scratched the surface of the things you can do with geolocation in this guide. The GeoNames library has a lot of free services I haven't mentioned here, but the documentation is good and you've got everything you need in this guide to be able to leverage them in your applications. If you're collecting logs and metrics with a service such as Retrace, this location data would be useful to gather. You can see if there's a spike in location-specific traffic at unusual times. This can allow you to track down problems or security issues more quickly.
https://www.kevincunningham.co.uk/posts/python-geocoder/
CC-MAIN-2020-29
refinedweb
1,454
71.95
php - i want to acquire sentences by dividing them into arrays with parentheses as the search target I want to do something like this with javascript. Example: input ="exampleOh [bb + cc] Yes [U.s]: test" ↓ output [0] ="example ah" output [1] ="[bb + cc]" output [2] ="Good" output [3] ="[う .s]" output [4] =": test" What I want to do is to make an array in order of what is enclosed in [] and what is not. If i have any idea, please give me a professor. Supplement 1: The purpose is to replace the characters surrounded by [] without input with complicated rules. Example: "[bb + cc]"⇒"BC" "[U.s]"⇒"uu" "exampleOh [bb + cc] Nice [U.s]: test" ⇒"example Oh bc good uu: test" ** Addition **** Example: "[date]"⇒Current date time "[rand: 1 ~ 10]"⇒A random integer between 1 and 10 "[yourname]"⇒Calls the saved character string corresponding to the keyword "yourname" (the contents of the character string may be changed when the page transitions. No conversion if there is no corresponding character string) "[array: A, 4]"⇒The fourth character of the saved data [array: A]. No conversion if [array: A] does not exist We plan to implement such a variety of rules, The rules are not constant and are intended for site visitors to change, add, or delete. ****** In order to achieve this, I came to the question with the expectation that array partitioning with regular expressions would be reasonable. Supplement 2: [Ah!] If parentheses are confused like this, "[Ah!" "[Ah]" It doesn't matter which one you use to extract. It is okay if they are unified. ** Supplementary notes ** However, "[Ai]"and"[I]" I want to avoid reading the same character position more than once. ****** We are looking forward to your response.<(_ _)> - Answer # 1 - Answer # 2 No need to split I think. const myMap = new Map ([['[bb + cc]', 'BC'], ['[U.s]', 'uu']]); let ex = 'example ah [bb + cc] okay [ou.s]: test'; myMap.forEach ((value, key) =>{ console.log (key + '=' + value); ex = ex.replace (key, value); }); console.log (ex);// example ah bc good uu: test Working sample: 【Map-JavaScript | MDN】 [String.prototype.replace ()-JavaScript | MDN] - Answer # 3 I'm sorry, but I would like to see only the flow of conversion as well.Output result The question that is divided into arrays in [] and the replacement question in "complex rules" in [] are easier to answer if they are divided as separate questions. import java.util.LinkedList; public class memo203 { // input = "example oh [bb + cc] nice [ou.s]: test" // ↓ // output [0] = "example aa" // output [1] = "[bb + cc]" // output [2] = "OK" // output [3] = "[Uh.s]" // output [4] = ": test" / ** * Input/output * / public static void main (String [] args) { String [] input = new String [3]; String [] output; input [0] = "012 [45] 789 [ab]"; output = func (input [0]); for (String str: output) { System.out.println (str); } System.out.println (); input [1] = "012 [4 [5] 7] 89 [ab]"; output = func (input [1]); for (String str: output) { System.out.println (str); } System.out.println (); input [2] = "example ah [bb + cc] nice [ou.s]: test"; output = func (input [2]); for (String str: output) { System.out.println (str); } System.out.println (); } / ** * Convert string to array * / public static String [] func (String str) { LinkedList<String>list = new LinkedList<String>(); StringBuilder sb = new StringBuilder (); sb.append (str); int s = 0;// start int e = 0;// end while (sb.length ()>1) { s = sb.indexOf ("["); if (s>0) { list.add (sb.substring (0, s)); sb.replace (0, s, ""); } int cntL = 0; int cntR = 0; if (! (sb.indexOf ("[")<0)) { for (int i = 0;i<sb.length ();i ++) { if (sb.charAt (i) == '[') { cntL ++; } if (sb.charAt (i) == ']') { cntR ++; } if (cntL == cntR&&cntR>0) { e = i; break; } } list.add (sb.substring (0, e + 1)); sb.delete (0, e + 1); } else { list.add (sb.substring (0)); sb.delete (0, sb.length ()-1); } } System.out.println (list); String [] result = list.toArray (new String [list.size ()]); return result; } } Related articles - about php multidimensional arrays - php - use array_filter for multidimensional associative arrays - i want to acquire a specific value by adding a condition to the column value from php db - i want to add as many parent layers as there are arrays in php - [php] about combining associative arrays - i would like to know the best way to pass values such as numbers and arrays obtained with php to javascript - php - i want to display the sentences in the db using the id - is the order of associative arrays decoded by the php json_decode function guaranteed? - [php] about associative arrays - php - have an image created on canvas and submitted in a form - php - what is the best delimiter when writing a url as a regular expression? - i want to move the value of a php variable to javascript - php - about the outline of the implementation of the like function - php - the menu does not close when you press the in-page link in the hamburger menu on wordpress - php - i want to split a string with javascript - php - wordpress operation in intellij idea - php - javascript confirm doesn't work well - is there a specification when "i don't know whether or not the "negation part" itself exists" in the negativ - php - how to display select boxes in conjunction How about this?
https://www.tutorialfor.com/questions-101020.htm
CC-MAIN-2020-40
refinedweb
865
65.83
My Dell laptop is experiencing the old problem of the power adapter failing to be recognized by the computer. I know for a fact it is just a break in the data cable in the line, because if I position it just right, the cable is recognized and the computer stops throttling the CPU to 20%. Is there any way that this can be disabled, so that I don't have the fiddle with my power cord every time I plug the computer in? - What does disabling the data line detection have to do with your CPU throttling? – Ramhound Dec 27 '16 at 18:07 - @Ramhound: wild guess, but probably "on battery" power setting? Not sure why the OP is so quick to blame a data channel though, faulty Power connections on the motherboard are pretty common. – Yorik Dec 27 '16 at 18:14 - I did have a similar problem not long ago, and the OP's diagnosis turned out to be correct in my case. The only real option I had was to buy a new compatible Dell adapter. – Jeff Zeitlin Dec 27 '16 at 18:47 - 1@Ramhound Dell computers have a data line in the power brick that tells the laptop what the rating on the power adapter is. Run a quick google search and you can see what I mean. I was wondering if anyone knew how to disable the throttling feature. – user173724 Dec 27 '16 at 21:41 - Possible duplicate of Workaround for Dell "Power supply not recognised" issue – user Oct 3 '18 at 3:48 I've done some investigation into this and found that there's probably no good way to prevent recent Dell laptops from throttling the CPU when it doesn't detect an OEM AC adapter (or one with a broken data pin.) Disabling SpeedStep or "additional sleep modes" or messing with the power profiles in the BIOS makes no difference. The "Intel Extreme Tuning" utility doesn't seem to support these motherboards as all overclocking options are locked out, but when a non-OEM charger is connected up it reports that CPU thermal throttling is engaged, and CPU-Z shows the FSB multiplier down to 5x and the core voltage at 0.6 volts. My guess is that perhaps the BIOS is designed to send false motherboard temperature readings to the CPU when a non-OEM adapter is detected, causing it to throttle. It seems Dell was very serious about locking you in to OEM adapters when they designed this system. Edit: I found a utility that will allow you to disable the unknown adapter throttling, under Windows at least (I don't know yet if the utility will work under Linux, or if there is something similar.) ThrottleStop has a checkbox called "BD PROCHOT" which causes the CPU core voltage and multiplier to reset to normal when disabled. Apparently this is a "2 way signal path to the CPU. It allows other components in a laptop like the motherboard or GPU to send a signal to the CPU which tricks the CPU into thinking it is too hot", confirming that the way this "feature" is implemented by the BIOS is through sending this signal to the CPU when an unknown AC adapter is detected. - 1 - 1@sradforth Hi, I don't have a Dell laptop anymore so unfortunately I don't recall exactly how ThrottleStop operates. But you can find which toggle setting it is easily enough via running the CPU-Z utility for Windows simultaneously; if the processor is throttled it will be obvious from the real-time processor clock speed reported in the main page, it will be stuck at something like 400MHz no matter what you do. When set "correctly" the clock reported will jump up to its nominal rate in response to user activity when not idling, as expected – Bitrex Sep 11 '18 at 4:13 Here's an OS-independent program you can compile with a C compiler/GCC (so long as it has an implementation of asprintf available) and set to run automatically at system startup which should disable the throttling on these Intel-based laptops, I've used this successfully on a Dell Inspiron 5558 laptop running Xubuntu with root privilege for the program, with "msrtools" installed and "modprobe msr" in the startup file prior to program execution, to allow reading and writing the MSR-registers from the user side (other OS may require different commands for "const char* cmd" to read/write to processor register location 0x1FC and will likely require root/privileged user access for the executable whatever form that may take) #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define BUFSIZE (64) int get_msr_value(uint64_t* reg_value) { const char* cmd = "rdmsr -u 0x1FC"; char cmd_buf[BUFSIZE]; FILE* fp; if ((fp = popen(cmd, "r")) == NULL) { printf("Error opening pipe!\n"); return -1; } cmd_buf[strcspn(fgets(cmd_buf, BUFSIZE, fp), "\n")] = 0; *reg_value = atoi(cmd_buf); if (pclose(fp)) { printf("Command not found or exited with error status\n"); return -1; } return 0; } int main(void) { const char* cmd = "wrmsr -a 0x1FC"; char* concat_cmd; int ret; uint64_t* reg_value = &(uint64_t){0}; if ((ret = get_msr_value(reg_value))) { return ret; } printf("Old register value: %lu\n", *reg_value); *reg_value = *reg_value & 0xFFFFFFFE; // clear bit 0 printf("New register value: %lu\n", *reg_value); if (asprintf(&concat_cmd, "%s %i", cmd, *reg_value) == -1) return -1; printf("Executing: %s\n", concat_cmd); system(concat_cmd); free(concat_cmd); return 0; } - In my case this did not help: sudo ./ThrottleStop\n Old register value: 2359388\n New register value: 2359388\n Executing: wrmsr -a 0x1FC 2359388 – Guido van Steen Jun 18 '19 at 7:27 -Only for Intel-CPUs- Start by installing MSR-TOOLS in Linux. sudo apt install msr-tools You should load msr as a kernel module by the following command sudo modprobe msr Read the value from Model Specific Register (MSR) - 0x1FC sudo rdmsr 0x1FC Then finally write the value to the Model Specific Register (MSR) - 0x1FC sudo wrmsr 0x1FC 4004d There you go! Your CPU runs at maximum ! - Actually not on maximum. It will run with frequency which will be set to register 0x1fc, that's why its better to write value which you will read from register first – Денис Карпов Jan 3 at 0:01 'Intel Dynamic platform and thermal framework' is the program that limits your cpu from clocking in normal speed. Uninstalling Intel Dynamic platform and thermal framework should fix the problem. - welcome to superuser:- do you have any reference links to go with this answer? Please take a few minutes to read How to Answer or Help center, again welcome to superuser. – mic84 Aug 13 '18 at 2:11
https://superuser.com/questions/1160735/stop-dell-from-throttling-cpu-with-power-adapter/1193616
CC-MAIN-2020-29
refinedweb
1,113
51.31
Trouble with py-fill-paragraph Bug Description Hello, I'm trying to refill the following docstring: class BlockCache(object): def remove(self, inode, start_no, end_no=None): """Remove blocks for `inode` If `end_no` is not specified, remove just the `start_no` block. Otherwise removes all blocks from `start_no` to, but not including, `end_no`. Note: if `get` and `remove` are called concurrently, then it is possible that a block that has been requested with `get` and passed to `remove` for deletion will not be deleted. """ if end_no is None: end_no = start_no + 1 When I place the cursor on e.g. the first line ("If `end_no`...) and execute M-x py-fill-paragraph, the buffer is scrolled such that this becomes the first visible line, and the indentation is removed. No filling occurs at all. Am I doing something wrong? py-docstring-style is set to pep-256-nn. I tried with the most recent release, python- With newest python-mode.el from http:// Am 17.05.2013 03:38, schrieb Nikolaus Rath: > With newest python-mode.el from http:// > mode-devs/ > is just a no-op. The screen flickers, but nothing is changed. > hmm, please check your init file. Make sure python-mode.el is loaded before any other Python related stuff. What happens, if just M-q is called? If bug persists, output of M-x report-emacs-bug might be helpful. Andreas Seeing a minor bug WRT to indent of closing string only, which should be fixed. What's your version of python-mode? Did you try with current trunk? Thanks, Andreas
https://bugs.launchpad.net/python-mode/+bug/1180653
CC-MAIN-2017-04
refinedweb
261
77.74
Any learning is based on a blend of the known and the unknown. If we use what we know, we learn fast - but the possibilities are limited. On the other hand, if we start from scratch, we have infinite possibilities, but it would take a long, long time to get through. This tradeoff becomes more and more significant when we work with a huge amount of data - and we already know a lot about it. Computer vision is one such domain. Thanks to years of research before AI, we already know a lot about the images and what to expect in an image. Starting afresh would certainly open up many unknown frontiers. But, we can let the academic researchers focus on that. For an engineering application, we need to encash on what we know, so that our algorithms can work faster and better. Convolutional Neural Networks is an excellent example of using the known, to reduce the computational complexity. Researchers came up with the concept of CNN or Convolutional Neural Network while working on image processing algorithms. Traditional fully connected networks were kind of a black box - that took in all of the inputs and passed through each value to a dense network that followed into a one hot output. That seemed to work with small set of inputs. But, when we work on a small image of 1024x768 pixels, we have an input of 3x1024x768 = 2359296 pixels. A dense multi layer neural network that consumes an input vector of 2359296 numbers would have at least 2359296 weights per neuron in the first layer itself - 2Mb of weights per neuron of the first layer. That would be crazy! For the processor as well as the RAM. Back in 1990's and early 2000's, this was almost impossible. That led researchers wondering if there is a better way of doing this job. The first and foremost task in any image processing (recognition or manipulation) is typically detecting the edges and texture. This is followed by identifying and working on the real objects. If we agree on this, it is obvious to note that detecting the texture and edges really does not depend on the entire image. One needs to look at the pixels around a given pixel to identify an edge or a texture. Moreover, the algorithm (whatever it is), for identifying edges or the texture should be the same across the image. We cannot have a different algorithm for the center of the image or any corner or side. The concept of detecting edge or texture has to be the same. We don't need to learn a new set of parameters for every pixel of the image. This understanding led to the convolutional neural networks. The first layer of the network is made of small chunk of neurons that scan across the image - processing a few pixels at a time. Typically these are squares of 9 or 16 or 25 pixels. CNN reduces the computation very efficiently. The small "filter/kernel" slides along the image, working on small blocks at a time. The processing required across the image is quite similar and hence this works very well. If you are interested in a detailed study of the subject, check out this paper by Matthew D. Zeiler and Rob Fergus Although it was introduced for image processing, over the years, CNN has found application in many other domains. Having seen a top level view of CNN, let us take another step forward. Here are some of the important concepts that we should know before we go further into using CNN. Now that we have an idea of the basic concepts of CNN, let us get a feel of how the numbers work. As we saw, edge detection is the primary task in any image processing problem. Let us see how CNN can be used to solve an edge detection problem. On left is a bitmap of a 16x16 monochrome image. Each value in the matrix represents the luminosity of the corresponding pixel. As we can see, this is a simple grey image with a square block in the center. When we try to convolve it with the 2x2 filter (in the center), we get a matrix of 14x14 (on the right). The filter we chose is such that it highlights the edges in the image. We can see in the matrix on the right, the values corresponding to the edges in the original image are high (positive or negative). This is a simple edge detection filter. Researchers have identified many different filters that can identify and highlight various different aspects of an image. In a typical CNN model development, we let the network learn and discover these filters for itself. One visible problem with the Convolution Filter is that each step reduces the "information" by reducing the matrix size - shrinking output. Essentially, if the original matrix is N x N, and the filter is F x F, the resulting matrix would be (N - F + 1) x (N - F + 1). This is because the pixels on the edges are used less than the pixels in the middle of the image. If we pad the image by (F - 1)/2 pixels on all sides, the size of N x N will be preserved. Thus we have two types of convolutions, Valid Convolution and Same Convolution. Valid essentially means no padding. So each Convolution results in reduction in the size. Same Convolution uses padding such that the size of the matrix is preserved. In computer vision, F is usually odd. So this works well. Odd F helps retain symmetry of the image and also allows for a center pixel that helps in various algorithms to apply a uniform bias. Thus, 3x3, 5x5, 7x7 filters are quite common. We also have 1x1 filters. The convolution we discussed above is continuous in the sense that it sweeps the pixels continuously. We can also do it in strides - by skipping s pixels when moving the convolution filter across the image. Thus, if we have n x n image and f x f filter and we convolve with a stride s and padding p, the output is: ((n + 2p -f)/s + 1) x ((n + 2p -f)/s + 1) Ofcourse if this is not an integer, we would have to chop it down. Cross Correlation is essentially convolution with the matrix flipped over the bottom-top diagonal. Flipping adds the Associativity to the operation. But in image processing, we do not flip it. Now we have an n x n x 3 image and we convolve it with f x f x 3 filter. Thus we have a height, width and number of channels in any image and its filter. At any time, the number of channels in the image is same as the number of channels in the filter. The output of this convolution has width and height of (n - f + 1) and 1 channel. A 3 channel image convolved with a three channel filter gives us a single channel output. But we are not restricted to just one filter. We can have multiple filters - each of which results in a new layer of the output. Thus, the number of channels in the input should be the same as the number of channels in each filter. And the number of filters is the same as the number of channels in the output. Thus, we start with 3 channel image and end up with multiple channels in the output. Each of these output channel represents some particular aspect of the image that is picked up by the corresponding filter. Hence it is also called a feature rather than a channel. In a real deep network, we also add a bias and a non linear activation function like RelU. Pooling is essentially combining values into one value. We could have average pooling, max pooling, min pooling, etc. Thus a nxn input with pooling of fxf will generate (n/f)x(n/f) output. It has no parameters to learn. Typical small or medium size CNN models follow some basic principles. Let us check out a simple example of how a convolutional network would work. Let us start with the MNIST dataset that we used before. Let us now look at doing the same job with a Convolutional Network. We start by importing the required modules. import numpy as np import tensorflow as tf from tensorflow import keras from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D from keras.models import Sequential The next step is to get the data. For academic purpose, we use the data set build into the Keras module - the MNIST data set. In real life, this would require a lot more processing. For now, let us proceed with this. Thus, we have the train and test data loaded. We reshape the data to make it more suitable for the convolutional networks. Essentially, we reshape it to a 4D array that has 60000 (number of records) entries of size 28x28x1 (each image has size 28x28). This makes it easy to build the Convolutional layer in Keras. If we wanted a dense neural network, we would reshape the data into 60000x784 - a 1D record per training image. But CNN's are different. Remember that concept of convolution is 2D - so there is no point flattening it into a single dimensional array. We also change the labels into a categorical one-hot array instead of numeric classification. And finally, we normalize the image data to ensure we reduce the possibility of vanishing gradients. (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() train_images = train_images.reshape(60000,28,28,1) test_images = test_images.reshape(10000,28,28,1) test_labels = tf.keras.utils.to_categorical(test_labels) train_labels = tf.keras.utils.to_categorical(train_labels) train_images = train_images / 255.0 test_images = test_images / 255.0 The Keras library provides us ready to use API to build the model we want. We begin with creating an instance of the Sequential model. We then add individual layers into the model. The first layer is a convolution layer that processes input image of 28x28. We define the kernel size as 3 and create 32 such kernels - to create an output of 32 frames - of size 26x26 (28-3+1=26) This is followed by a max pooling layer of 2x2. This reduces the dimensions from 26x26 to 13x13. We used max pooling because we know that the essence of the problem is based on edges - and we know that edges show up as high values in a convolution. This is followed by another convolution layer with kernel size of 3x3, and generates 24 output frames. The size of each frame is 22x22. It is again followed by a convolution layer. Finally, we flatten this data and feed it to a dense layer that has outputs corresponding to the 10 required values. model = Sequential() model.add(Conv2D(32, kernel_size=3, activation='relu', input_shape=(28,28,1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(24, kernel_size=3, activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(10, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) Finally, we train the model with the data we have. Five epochs are enough to get a reasonably accurate model. model.fit(train_images, train_labels, validation_data=(test_images, test_labels), epochs=5) Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 49s 817us/step - loss: 0.2055 - acc: 0.9380 - val_loss: 0.0750 - val_acc: 0.9769 Epoch 2/5 60000/60000 [==============================] - 47s 789us/step - loss: 0.0776 - acc: 0.9762 - val_loss: 0.0493 - val_acc: 0.9831 Epoch 3/5 60000/60000 [==============================] - 47s 789us/step - loss: 0.0557 - acc: 0.9830 - val_loss: 0.0489 - val_acc: 0.9825 Epoch 4/5 60000/60000 [==============================] - 47s 787us/step - loss: 0.0441 - acc: 0.9864 - val_loss: 0.0493 - val_acc: 0.9845 Epoch 5/5 60000/60000 [==============================] - 47s 788us/step - loss: 0.0367 - acc: 0.9885 - val_loss: 0.0348 - val_acc: 0.9897 >keras.callbacks.History at 0x7fbf95e33e48<
https://blog.thewiz.net/convolutional-neural-networks
CC-MAIN-2022-05
refinedweb
2,004
67.35
On Nov 18, 2009, at 5:14 AM, Justin Erenkrantz wrote: > On Wed, Nov 18, 2009 at 5:57 AM, Christopher Brind <brindy@brindy.org.uk > > wrote: >> I can understand why Subversion should be made a top level project >> quickly, >> but I personally believe the namespace change is a reasonable >> request in >> order to graduate for all the same reasons that convinced me Pivot >> should >> change its namespace. >> >> It sends the wrong message not to change given the importance of >> the Apache >> namespace, imho. > > If Subversion were a Java project, maybe I would consider it more > important that it change. > > However, the Java bindings are a very small (and largely > insignificant, IMO) part of Subversion. Holding a C-based project up > for graduation because their Java bindings aren't in the org.apache.* > namespace starts to sound petty. -- justin I have a different opinion. Java package spaces have always carried significant importance in the java community in terms of who is providing stewardship of the code. Having users change the packages when they move to a *new* version requires no significant burden. It happens all the time in the Java world and we are not treading on new ground here. Regards, Alan --------------------------------------------------------------------- To unsubscribe, e-mail: general-unsubscribe@incubator.apache.org For additional commands, e-mail: general-help@incubator.apache.org
http://mail-archives.apache.org/mod_mbox/incubator-general/200911.mbox/%3C6F309908-5256-4A07-83E8-51203DEB1C49@toolazydogs.com%3E
CC-MAIN-2016-40
refinedweb
221
55.64
Opened 4 years ago Closed 4 years ago Last modified 23 months ago #26428 closed New feature (fixed) Add support for relative path redirects to the test Client Description Consider this definition, in a reusable app: url(r'^inbox/$', InboxView.as_view(), name='inbox'), url(r'^$', RedirectView.as_view(url='inbox/')), And urlpatterns = [ url(r'^messages/', include((app_name_patterns, 'app_name'), namespace='app_name')), ] This was working on 1.8, thanks to http.fix_location_header, which converts the url to something like. 1.9 introduced the "HTTP redirects no longer forced to absolute URIs" change and the fix has disappeared, the reason being "... allows relative URIs in Location, recognizing the actual practice of user agents, almost all of which support them.". Unfortunately, this is not fully the case of test.Client. It doesn't support relative-path reference - not beginning with a slash character, but only absolute-path reference - beginning with a single slash character (ref). A GET to inbox/ leads to 404. I'm using a workaround with ... url=reverse_lazy('app_name:inbox') ..., referred by a TestCase.urls attribute, to produce /messages/inbox/, but I'm not happy with this hardcoded namespace. Attachments (2) Change History (15) comment:1 Changed 4 years ago by Changed 4 years ago by comment:2 follow-up: 3 Changed 4 years ago by Does this patch fix your issue? If not, could you provide a sample of your test code so we understand exactly what you're doing? Thanks. comment:3 Changed 4 years ago by The patch does fix my issue but a simple concatenation doesn't cover all cases. Suppose your test scenario as: url(r'^accounts/optional_extra$', RedirectView.as_view(url='login/')), with: response = self.client.get('/accounts/optional_extra') I think a more appropriate code is: # Prepend the request path to handle relative-path redirects. if not path.startswith('/'): url = urljoin(response.request['PATH_INFO'], url) path = urljoin(response.request['PATH_INFO'], path) comment:4 follow-up: 5 Changed 4 years ago by Thanks for the feedback. I updated the pull request for your suggestion and added some release notes for 1.9.6. comment:5 Changed 4 years ago by comment:6 Changed 4 years ago by comment:7 Changed 4 years ago by Changed 4 years ago by Also fixes Client.get() comment:8 Changed 4 years ago by Though the fix solves the original problem i.e. assertRedirects(), the summary of the ticket suggests broader support. I've attached a patch based on the original fix, that also fixes Client.get() / Client.post() etc. when follow=True. comment:9 Changed 4 years ago by comment:10 Changed 4 years ago by comment:11 Changed 4 years ago by comment:12 Changed 23 months ago by This issue was not fully addressed. There are still a couple problems: 1) It assumes that a relative redirect does not start with '/'. But what if you redirect relative to host with a '/', as in redirecting to '/subpath' instead of ''? 2) It does not set the secure kwarg on the client.get call based on the original host scheme, because urlsplit is called only on the relative path. It seems that urlsplit should be called after building an absolute url. Should this ticket be re-opened, or a separate ticket created? comment:13 Changed 23 months ago by New ticket, please, as the fix for this one has been released for years. I think we should try to fix it in 1.9 given the regression nature of the report. A test is attached.
https://code.djangoproject.com/ticket/26428
CC-MAIN-2020-24
refinedweb
582
66.64
A few days ago a reader asked me an interesting question. He wanted to create a list of dates in jQuery Mobile and group them by date. Turns out, this is fairly easy using the Autodividers feature of the ListView widget. jQuery Mobile has supported dividers in lists for a while now, but recent editions added support for creating them automatically. Out of the box, jQuery Mobile will create dividers based on the first letter of the list item. Consider this example. <ul data- <li>Benedict</li> <li>Bleys</li> <li>Brand</li> <li>Caine</li> <li>Corwin</li> <li>Eric</li> <li>Gerard</li> <li>Julian</li> <li>Random</li> </ul> By adding autodividers="true" to the list, you get dividers based on the first letter in each name above. So the obvious next question is - how do you create dividers based on some other form of grouping - like dates? Luckily jQuery Mobile's listview widget gives you an easy way to handle this. You simply take the listview widget and define a function that returns the "selector" for an item. In abstract, it would look like this: $("some selector").listview({ autodividers:true, autodividersSelector: function ( li ) { // "li" is the list item, you can get the text via li.text() // and then you return whatever you want - in text that is return li.text().substring(0,1).toUpperCase(); } }).listview("refresh"); The method above should work the same as the default behavior. Get the first letter and upper case it. (I typed this without actually running it so if there is a typo above blame my laziness.) In order to support our date grouping, we can use this method and JavaScript date methods. Let's look at a full example. First, the HTML. Note that I've made an empty list widget that will store my data. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Divide Demo</title> <link rel="stylesheet" href="" /> <script src=""></script> <script src=""></script> </head> <body> <div data- <div data- <h1>Our Events</h1> </div> <div data- <ul data- </ul> </div> <div data- <h4>Footer content</h4> </div> </div> <script src="datestuff.js"></script> </body> </html> Now let's look at the JavaScript. /* global $,document,console,quizMaster */ $>"); } dateList.listview({ autodividers:true, autodividersSelector: function ( li ) { var d = new Date(li.text()); return (d.getMonth()+1)+ "/" + d.getDate() + "/" + d.getFullYear(); } }).listview("refresh"); }); At the top I've got a set of hard coded dates. These would typically be loaded via Ajax. I loop over them and insert them into the list. Once I've got that I can then initialize my listview and define a custom selector. As I mentioned above, I can use JavaScript date methods to return a string based on just the date portion of the date values I had above. (In other words, ignore the time.) I can also do some formatting on the date to make it look nice. Here is the final result. You can run a full demo of this below.
http://www.raymondcamden.com/2013/12/17/Using-the-autodivider-feature-in-jQuery-Mobile/
CC-MAIN-2016-07
refinedweb
510
66.64
Announcing native support for the css prop in styled-components 🎉 A new, convenient way to quickly style and iterate on your components and their boundaries has landed in styled-components 💅 As Ryan Florence once said, the essence of working with components is worrying about the right lines to draw in your app and then filling in the shapes they create with components. Invented by Sunil Pai in glamor, the css prop has taken over the CSS-in-JS world as a convenient way to build components while staying flexible with the “lines”, their boundaries. const MyButton = () => ( <button css={` color: papayawhip; background: palevioletred; `} > Click me! </button> ) By declaring the CSS inline, it’s simple to move elements around your app and iterate on them, allowing you to keep moving fast in the early stages. Then, once you feel comfortable with the boundaries you’ve chosen, you can quickly turn them into styled components and lock them into place. So far, to get support for the cssprop in styled-components, you had to use user-land libraries such as rebass. They worked great, but required a lot of manual work and the implementation wasn’t the most performant. Today, we’re excited to announce native support for the css prop in styled-components! 🎉 Enabling support for the css prop All you have to do to enable support for the css prop is to upgrade to the latest version of the styled-components Babel plugin: npm install --save-dev babel-plugin-styled-components@latest If you aren’t using the Babel plugin yet, you also have to add it to your .babelrc. That’s all there is to it, now you’re ready to css and roll! 💃🏼 Using the css prop Using the css prop is as simple as adding it to any element in your app. It supports everything a normal styled component supports 💪, including custom components, adapting based on props and theming: <h1 css="color: palevioletred;"> The css prop </h1><Button primary css={css` color: ${props => props.theme.colors.text}; background: ${props => props.theme.colors.primary}; border-radius: ${props => props.primary ? '4px' : '5px'}; `} > Click me </Button> Under the hood, the Babel plugin turns any element that has a css prop into a styled component. For example, if you were to write this BlueButton component: const BlueButton = (props) => <button css="color: blue; padding: 1em;" {...props} /><BlueButton css="background: blue; color: white;">Hey!</BlueButton> The Babel plugin would turn it into this: import styled from 'styled-components';const StyledButton = styled('button')` color: blue; padding: 1em; `const BlueButton = (props) => <StyledButton {...props} />;const StyledBlueButton = styled(BlueButton)` background: blue; color: white; `<StyledBlueButton>Hey!</StyledBlueButton> Yep, it even adds the styled-components import automatically so you don’t have to think about it. This mechanism also means that support for the css prop adds exactly 0.0kB to the runtime of the library. 😎 Huge shoutout to Satyajit Sahoo, who came up with this ingenious technique! We hope you enjoy the css prop. 💜 If you want to learn more check out the documentation, and let us know what you think in the community! As always, stay stylish out there. 💅
https://medium.com/styled-components/announcing-native-support-for-the-css-prop-in-styled-components-245ca5252feb?utm_campaign=React%2BNewsletter&utm_medium=web&utm_source=React_Newsletter_140
CC-MAIN-2020-16
refinedweb
521
52.9
hi dears. I am using Emu8086. I need to generating an array of random numbers. Are there any ready procedure or intrupt? if there are not, how can I do it? thanks. Edited by funfullson: n/a hi dears. I am using Emu8086. I need to generating an array of random numbers. Are there any ready procedure or intrupt? if there are not, how can I do it? thanks. Edited by funfullson: n/a If you have an Intel 82802 in your system.... If not, read a high precision clock register, blend the bits in a tight loop, peek at a keyboard key until a user interaction is applied such as a keystroke. You can seed the number generation from the high precision clock as well based upon computer power up time. seed = high precision clock Loop: seed = (214013 * seed + 2531011 if !keyhit goto Loop return (seed>>16)&0x7FFF Edited by wildgoose: n/a Sorry! is it pseudo code? what are these? precision clock and !keyhit. Review the Intel link. If accessing their chip its basically a white noise generator, which is a very good random. By constantly generating numbers until a key is pressed adds an additional variation of randomness to it. The precision clock, access a P4 and use one of its newer instructions to get number of clock cycles since power up. Keyhit, access the BIOS, look at the keyboard flag and see if a key has been depressed or not! rdtsc is one such instruction. These aren't beginner things to do, so if you are a beginner, start simpler! Edited by wildgoose: n/a Hi, If you are using EMU8086, I suppose you are about to learn assembly programming and generating a sequence of random numbers seems to be kind of exercise. EMU8086 does not have random number generator. Classical method for computing pseudo random numbers is the linear congruential random number generation method by Lehmer, where a new rnz is given by z(k+1) = (a*z(k) + b) mod m. For you are restricted to 16 bit registers ax, bx etc. I show you a 16 bit Lehmer generator: z = (31*z+13)%19683. Instead of 19683 you can also use 59049 (3*19683) what utilize 16bit (max. 65535) somewhat better. Below 80x86 code is embbeded in Visual C++ program. You can simply copy this code into EMUs editor (and put some entry and exit code around it). You can then watch the dx register where 10 rnz will be computed within loop RN. Deep down there is also my C function which I translated into 80x86 assembly. Between assembly and C functions there is a small difference: the return value of C function is furthermore mapped on interval [0..s-1]. This is somewhat more practial when using it. I omitted this not-that-important step in assembly code. I am sure you will be able to extend the assembly code for storing the rnz appearing in register dx in an array. (If there are problems, simply ask) int assembly86(){ __asm { ; Lehmer linear congruential random number generator ; z= (a*z+b) mod m = (31*z+13)%19683 ; Rules for a, b, m by D. Knuth: ; 1. b and m must be relatively prime ; 2. a-1 must be divisible without remainder by all prime factors of m (19683 = 3^9), (31-1)%3=0 ; 3. if m is divisible by 4, a-1 must also be divisible by 4, 19683%4 != 0, ok ; 4. if conditions 1 to 3 met, period of {z1, z2, z3,...} is m-1 = 19682 (Donald says) push ax ; save used registers push dx push bx push cx mov dx, 0xABBA ; 43962D is initial Value z for random sequence mov cx, 0x000A ; compute 0xA = 10D pseudo random numbers RN: mov ax, dx ; set new initial value z mov bx, 0x001F ; 31D mul bx ; 31 * z ; result dx:ax, higher value in dx, lower value in ax add ax, 0x000D ; +13 mov bx, 0x4CE3 ; 19683D div bx ; div by 19683D ; result ax:dx, quotient in ax, remainder in dx (this is the rnz) ;... ; processing random numbers here, first 10 RNZ (appearing in dx) are: ; 4708 8180 17397 7879 8066 13863 16423 17051 16836 10171 loop RN ; repeat computing 10 times pop cx ; restore registers pop bx pop dx pop ax } return 0; } unsigned short lehmer_sh(unsigned short s) // linear congruential random number generator by D. Lehmer // x(k+1)=((a*x(k) + b) mod m) mod s { static unsigned short a=31, b=13, m=19683, z=43962; z=(31*z+13)%19683; return z%s;} I hope this code is some help for you. -- tesu Edited by tesuji: n/a Thanks.I tried to get random number generating code from vs _by step debugging over "srand" function_ but it have used some registers from upper version than 8086 and it made me confused. there is a problem at assemby86 function.it returns same sequence of random number every time.how we can improve it? there is a problem at assemby86 function.it returns same sequence of random number every time.how we can improve it? No thanks at all! assemby86 or to be more specific the random generator inlined in assemby86 has been set up to produce the same sequence of pseudo random numbers every time one is calling it. Such behaviour is really necessary if one is doing serious physical experiments to be sure that the results be reproducible. Ok, that's not that a nice behaviour if using it for creating jokes and games. If one likes to get various sequences of pseudo random numbers one must change the seed of the related generator. In my former c function changing the seed has been controlled by the range value s. If range value s is negative its absolute value is used as to be new seed. So if one wants to get new sequence of random numbers, first call generator function with negative range value to set new seed, then second, call generator function repeatedly to compute new sequence. You seems to clever enough to extend this small assembler code getting variable seed. Meanwhile I did some statistical test on this new 16 bit generator and I am really surprised for its chi-square result is really good. The new triple (31, 13, 59049) defines a truly robust random generator, looks like to be the little daughter of Mersenne twister :) Btw, what do you make of ABBA? I myself believe that Anni Frid has been by far the best singer ever, much more better than Agneta ;) How does it strike you? Addendum: You are right, investigating the assembly code of progams using srand function within to-day VS can really be dizzying because of all the odd extended and odder extendedextended registers you have never seen on EMU8086 before. That was the vital reason why i did only use 8086 16 bit instructions. As for the interface of inline assembly with Visual C++ here one must make use of extended registers, e.g. ESI, EDI etc, for Visual C++ ony knows 32 bit instructions here. This is important to consider if you plan to store the inline generated pseudo random numbers into c++ array to using them within your c++ program. -- tesu Edited by tesuji: n/a hi dears. I am using Emu8086. I need to generating an array of random numbers. Are there any ready procedure or intrupt? if there are not, how can I do it? thanks. This is simple formula for basic LCG random generator. k = 30903 * (k & 65535) k is seed number! I implement basic random generator, you can see on web page in examples section.. ...
https://www.daniweb.com/programming/software-development/threads/292225/random-number-generating-in-assembly
CC-MAIN-2017-26
refinedweb
1,284
73.07
My Flatiron School JavaScript portfolio project: A digital vision board 5/19/21 | And just like that it’s JavaScript storyboarding time. For my fourth portfolio project in the Flatiron School program, I’m creating a vision board builder with a JavaScript front-end and Rails API back-end. I spent the majority of the day drawing out my models — Category, which is essentially the vision board itself, and Items that will be added to the visual inspiration board. My user story for this project is this: A user should be able to read and create vision boards based on categories. The project instructions really emphasize understanding the project requirements and aiming for a MVP ASAP (Minimum Viable Product, As Soon As Possible). With the added complexity of separate backend and frontend repositories, I’m sticking to simplicity and focusing on what features are required. I’m also trying to heed the advice to “build vertically, not horizontally,” aka not building all the migrations or models or controllers at once. Rather, I’m building one feature at a time. To start, I’ve generated an Item model and created namespaced routes and controllers. I have set up my has_many and belongs_to associations and have double-checked that my associations are working by implementing seed data. This time around, I want to be *extra* diligent with my commits and descriptions of the features I’ve added and git pushed. Even though, I’m still studying the JS for a more wholesome understanding— I’m currently working my way through Anthony Alicea’s Understand JavaScript Udemy course (which I highly recommend), I’m super excited to be working on my first JS project. 5/21/21 | Good morning from Day 3 of my JavaScript project build. I have a lot to do today but figured I’d write an update about yesterday’s progress before I get caught up in today’s code. Everything is moving along smoothly. I’ve been using these JavaScript project resources, which have been indispensable. They’re highly recommended for anyone else working on their very own from-scratch project. Without following these order-of-operations guidelines, I would have blindly started coding. There are so many possible entry points so having a clear-cut option saved me a lot of grief. Should I set up the front end or back end first? Just I work on both at the same time? The answer is to work on one thing at a time — and not to move onto something else until you need to in order to progress the feature you’re currently working on. Following this JavaScript Rails API Project Setup repo, I started by generating my Rails API. Then working vertically, I set up what I needed to get the items model and routes (index and create) working with its corresponding controller actions. I made sure my index route for Items was correctly exhibiting all items persisted in the database (seed data) in proper JSON before moving onto the front end. I also set up the create action in my controller in order to test the post fetch request from the front end. Then I set up my frontend separately. From there, I worked on my get fetch request after setting up an event listener with a DOMContentLoaded event. The guide helped me practice working one feature at a time, and not following patterns of building all the migrations at once or setting up all the routes or controller actions all in one go. I’m learning so much from project mode. Having debugger practice from the labs has been invaluable. Here’s a JavaScript mantra that Flatiron instructor Ayana Zaire shared in a study group that has helped in the moments when I’ve completed a function and can’t think off the top of my head what to work on next: JS MANTRA: When some event happens, I want to make what kind of fetch and then manipulate the DOM in what way? It’s a great way to think about the order of operations that adding an event spurs. You have to think about the three pillars of front-end web development: manipulating the DOM, recognizing events, and communicating with the server. When you’re coding, you’ll want to add event listeners to incapsulate when a user will do something like click a button or submit a form. The next step is thinking about whether you’re getting data (get fetch request), sending data (post fetch request), changing data (patch fetch request), or deleting data (delete fetch request). Then you want to thinking about appending information or taking a feature away. I’ve found it super helpful to think about the three pillars of front-web programming in this way. Hope sharing a helpful mantra shared in a study group helps you too! 5/22/2021 | Hello hello! Last night I finished around 8:30 p.m., which is typically an hour earlier than I would have called it quits for the day but I had finished refactoring my get and post fetch requests in my ItemApi class so it was the perfect stopping point. I watched a documentary called Some Kind of Heaven on Hulu last night. It focuses on a sprawling retirement community called The Villages in Florida where some senior citizens thrive while others flail. Although it has nothing to do with coding, which is what I needed after a long day, the incredible imagery and colors were incredibly inspiring for my coding/font-end design. One of the things I look forward to most as a full-stack web developer is creating beautiful web interfaces. Yesterday, I was able to refactor most of my code into object-oriented classes having started with functional JS. There are so many ways to write JS that I find it kind of overwhelming. For instance, with an Api class, you can write the functions as static class methods or instance methods. I decided to go with writing all the methods as instance methods kind of arbitrarily. I can’t wait to become more proficient in JS so I can develop preferences and opinions about app design. Right now, I’m guided by patterns I’ve seen in labs and in study groups. Goal for today: Make a category class and a categoryApi class that writes a get fetch request to my Category index action. Then I anticipate adding edit and delete buttons for my items and get those working with patch and delete fetch requests. Another good dev habit I started with this project is working in separate branches. This way, I can keep the main/master branch clean with working code. I’ll only merge and make a pull request after the feature I’m working on is done and working. I had a heck of a time trying to find the last commit where everything was working before breaking everything while working on my Rails final project. Hoping this will save me some time and anxiety. 5/23/21 | I’m hankering for the ocean. Can you tell? But I’m pretty much still quarantined in place and gladly making progress with my JavaScript project. I’m so nervous for the live coding part of my project assessment. Mostly because as I code, I Google everything — I also consult my notes every five seconds and watch study group videos when I can’t remember what to do next. They’re my safety net. Hopefully, after a big study sesh of the concepts I’ll feel my confidence build. This morning, I solved a pretty minor bug without too much panic or Googling. The issue: I was able to successfully filter vision board items by category by clicking on each of the buttons corresponding with each of the categories but I couldn’t un-click the button to revert the DOM to showing all items. Adding one conditional (if the button does not have class “active”) did the trick. Once it checks for the conditional, it drops down into the else (assuming it has the class “active”) to then removes it. Once removed, the CSS magically reverts to back to a normal button. Yesterday’s big win was adding a lot of basic CSS to style the page and adding a PATCH fetch request to delete the item from the DOM pessimistically (before the fetch request actually happens) and deleting the item from the database. Today’s main goal is to finish the edit/update fetch requests and manipulating the DOM on both counts. I’ll most likely do a refresh on CSS flexbox to style the rest of the content. So far, I’m super happy with how it looks. All things are lookin’ up. I think I’m a day or two away from finishing up this project. 5/24/2021 | Hi there. (I’d LOVE to be on a hike today.) Any way, I finished my project. Woot woot. I keep looking at the technical requirements of the JavaScript portfolio project and believe I have fulfilled every one. Next steps are to film a project walkthrough, submit the project, and then continue studying JavaScript in preparation for the project assessment, which I believe will be a doozy. I’m excited to start the React and Redux portions of the course — the program finale. Finishing the rest of the lessons means I’ll be good to work on my final portfolio project. Ahh, I can’t believe I’m actually on schedule to finish by June 30, the deadline of my program. After enduring a global pandemic (worrying about whether going to the grocery store possibly meant exposure to covid) and being a full-time caretaker for a parent all the while ticking off program requirements, I feel awesome to land here. Thanks for reading.
https://joannpan.medium.com/my-flatiron-school-javascript-portfolio-project-a-digital-vision-board-6b8357b07a16
CC-MAIN-2022-40
refinedweb
1,647
70.13
On some files with rearranger latest version and default settings, idea start an infinte loop, eat all my cpu on xp pro. Must kill idea to get my box back. This appear since I've upgraded both the rarranger plugin and intellij b2002 at the same time. Must be realted to the structure of the file because all files that have exaclty the same structure cause the same problem and AFIK only these files. Attached is a structure view of one of these files. Some precisions related to this view : public abstract class BackEndProvider implements Serializable public abstract class AccessProvider extends BackEndProvider public class OpenLdapAccessProvider extends AccessProvider Is there anything I can do to go further finding the problem (maybe a bug in idea apis??)? BTW, great plugin... Richard Attachment(s): structure.JPG Richard, This problem occurs only with the EAP build. If I build the plugin with IDEA #2002, it works with the EAP build but no longer works with 4.0! I am attaching version 2.7 of the plugin compiled with #2002. Rename it "rearranger.jar" and put it in your plugins directory. I would put this on the wiki site but can't upload files there at the moment. Let me know if you still have trouble. -Dave Attachment(s): rearranger2002.jar Thank you dave, not much tested, but seems the infinite loop has gone away. Thank you very much, Richard
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206785135--ANN-Rearranger-infinite-loop-with-very-high-cpu-usage-have-to-kill-idea
CC-MAIN-2020-29
refinedweb
235
76.32
on Thu Oct 09 2008, Robert <rcdailey-AT-gmail.com> wrote: > Hi, > > Is it really necessary to obtain __dict__ in order to add variables to > some object's scope? No. > For example, suppose I want to define a global > variable in a module, how would I do this? I know the first step I > must take is to import the module: > > boost::python::import( "my_module" ) > > What then? A pseudo-code example of what I would expect is something like: > > using namespace boost::python; > import( "my_module" ).attr( "my_global" ) = object( 5.0f ); Looks OK to me. In fact, import( "my_module" ).attr( "my_global" ) = 5.0f; should work. -- Dave Abrahams BoostPro Computing
https://mail.python.org/pipermail/cplusplus-sig/2008-October/013840.html
CC-MAIN-2018-26
refinedweb
108
62.44
New data backup SaaS players emerge Once upon a time in the storage market, storage service providers were all the rage. Then, the tech bubble burst and most of them went the way of the dodo bird. But with storage growth in recent years forcing companies to consider new strategies for managing data, storage service providers are making a comeback. Within that market space, meanwhile, backup and recovery is the most popular area, as users struggle with the cost of protecting more and more data, the distraction of backup and recovery management from core business and IT operations, and ever-increasing regulation. Naturally, this is the market where the lion’s share of new players are springing up. EMC Corp. and Symantec Corp. are among the heavy hitters that say they’re planning backup SaaS. But there are also some new and emerging vendors that are gaining attention in the market with the return of interest in outsourcing. One of the companies that’s made its presence known in recent weeks is Nirvanix Inc., which is aiming to be a business-to-business outsourcer for large companies. It’s come out of the gate overtly challenging Amazon’s S3 service, saying it can overcome the performance issues that have been reported by some large S3 users. The service is also offering a 99.9% uptime SLA to customers. Nirvanix claims it can offer better performance because it is constructing a global network of storage “nodes” based on the way Web content delivery systems work — by moving the storage and processing power closer to the user, cutting down on network latency. Within each of Nirvanix’s storage nodes is a global namespace layered over a clustered file system, running on Dell servers residing in colocation facilities. These nodes also perform automatic load balancing by making multiple copies of “popular” files and spreading them over different servers within the cluster. With this storage infrastructure, the company is claiming that it can offer users a wider pipe as well as a faster one, allowing file transfers of up to 256 GB. Moving forward, according to CEO Patrick Harr, the company plans to offer an archival node for “cold storage” within 6 months. One potential issue for the company in comparison to S3 is a lack of financial clout to match Amazon. Building out the storage node infrastructure will be an expensive proposition in comparison to creating software and running a typical data center, and so far, the company says it has received just $12 million in funding, some from venture capital firms and some from research grants. However, it also says 25 customers have already signed up for beta testing, and says one of those customers is supporting 50 million end users. Base pricing for the service is 18 cents per stored gigabyte per month, a “slight premium” over Amazon’s price according to Harr. The company is hoping that it can increase sales volume and drive down the price. Meanwhile, on the consumer/SMB side, a company called Intronis LLC is souping up its features in the hopes of gaining traction in the low end of the storage market. Version 3.0 of its eSureIT backup service will allow users to create a tapelike rotation scheme for files, creating backup sets and setting policies for data retention on a weekly, monthly and yearly basis. The company has added a plugin it calls Before and After, which will allow users to create scripts dictating what their computer systems should do before, during or after engaging with the Intronis service — for example, the script can have the user’s machine shut down applications prior to backup and restart them after backup has finished. Another new plugin will allow mailbox and message-level backups and restores of Exchange databases, and adds a text search for email repositories. But the biggest new development, and the one that’s taken it the better part of two years to develop, according to Sam Gutmann, co-founder and CEO, is a feature the company is calling Intelliblox, which like other enterprise-level backup services such as Asigra, backs up only changed blocks over the wire. The feature uses a set of checksum and hashing algorithms to identify blocks and keep them together with their corresponding files (an existing feature of Intronis’s service is total separation between the company’s admins and users’ data — each user is given an encryption key to access its storage at Intronis’s data center, and Intronis says it has no way of reading any of its customer data). This use of hashing algorithms also has this blogger wondering if they might also be able to offer fixed-content archiving down the road. Comment on this Post
http://itknowledgeexchange.techtarget.com/storage-soup/new-data-backup-saas-players-emerge/
CC-MAIN-2016-26
refinedweb
793
54.66
). To implicitly link to a DLL, executables must obtain the following from the provider of the DLL: A header file (.h file) containing the declarations of the exported functions and/or C++ classes. The classes, functions, and data should all have__declspec.. To successfully create and compile QT applications and use libdln.a library in Linux, you need to correctly configure and setup QT. This steps should be performed after you successfully performed steps from Software & Hardware Installation in Linux page. First, download QT sources from QT website (...), unpack archive, open terminal in unpacked folder with QT, configure QT with-release and-static flags, then compile QT sources and install QT. For this example QT 4.8.5 version was used. ./configure -release -nomake demos -nomake examples make make install After QT is compiled you can compile and run any QT application by using properqmake project_name from application sources folder. You can use terminal or QT Creator for creating applications. device_list_gui project compilation from terminal: path_to_qmake/qmake device_list_gui make To use libdlb.a library in your application project, you need to add the following to project .pro file: QMAKE_LFLAGS += -static-libgcc LIBS += /usr/local/lib/libdln.a # path to libdln.a library Also do not forget to include required header .h files to your sources for successful usage API functions from libdln.a. For example: #include "../common/dln.h" #include "../common/dln_generic.h"
http://dlnware.com/print/book/export/html/15
CC-MAIN-2019-43
refinedweb
232
51.65
Both networks got their start with OpenProjects.net. Founded by Rob 'lilo" Levin, OpenProjects.netwas the precursor to the Peer-Directed Projects Center (PDPC) and freenode. (The OpenProjects.net domain is no longer affiliated with PDPC or freenode.) OFTC separated from OpenProjects.net, at least in part, due to philosophical differences about management and fundraising. The split, which OFTC network operations committee chair David Graham calls "a very acrimonious and unpleasant separation," started in 2001. Graham says that all of OFTC's original staff members were former OpenProjects.net staffers. OFTC formed a network specifically for free software and open source projects. "The two networks have evolved separately over the half-decade since, with very few staff remaining on either side from that split." Last year, Levin was hit by a car while riding a bicycle and died due to the injuries he sustained. Christel Dahlskjaer, head of staff for freenode and a board member for PDPC, says that, since Levin's death, freenode has moved to a "more inclusive approach, where both users and staff are involved in decisions and changes pertaining to the future direction of the network." In addition, Dahlskjaer says that freenode is moving to a "more transparent system" that's more in line with the community nature of freenode. She says Levin would be "very pleased and proud of what we have achieved with both freenode and its parent organization PDPC in the months since his passing." Freenode has grown by about 8,000 users since last October, according to Dahlskjaer. For reference, the Search IRC site pegs OFTC at an average of 3,751 users over the last week, while it estimates that freenode averaged about 33,300 users over the same period. Adding 8,000 users in just six months is substantial growth. Dahlskjaer also says that the PDPC is "embraced more by the community" despite losing Levin as a fundraiser. "We are seeing a trend in donations from organizations such as the Wikimedia Foundation as well as individual donors, enabling us to focus on other projects such as arranging FOSSCON." Working together After growing apart for six years, freenode and OFTC are now working together, and seeing where cooperation might take them. Graham says that the two networks would probably not be cooperating as they are now if Levin were still in charge. However, he also says Levin was a "charismatic leader" who "always had the best interests of the free software and open source communities at heart, and it is within that spirit that we are all working." Graham says "there is no specific roadmap for further integration," but "both sides want it." The next logical step, according to Graham, would be for freenode to deploy the IRC daemon (ircd) used by OFTC. "Freenode currently uses hyperion, a highly customized ircd that is difficult to maintain. The logical next step would be for freenode to implement and roll out OFTC's ircd, which is a slightly patched version of the very robust Hybrid ircd." This looks like a strong possibility, as Dahlskjaer acknowledges that "our current IRC daemon is difficult to maintain and was not designed to cope with a network experiencing the sort of growth we are currently seeing." To that end, Dahlskjaer says that freenode is "researching several options for an ircd and services" and "paying particular attention to OFTC's Hybrid-based ircd and Charybdis, an IRC daemon based on the ircd-ratbox core." To merge, or not to merge If all this activity sounds like the precursor to moving the two networks together again, you might be right. Or not. According to Graham, the idea of a merger "has been floated" but "nothing is set in stone as far as a merger goes." What would it take to execute a merger of the networks? Dahlskjaer says that "there are a lot of technical and operational differences that would need to be worked out. "While we offer a similar service, it is no secret that freenode looks to expand beyond 'just IRC.' We work with a strong sense of community involvement in our efforts to provide infrastructure for open source projects, and to help them create vibrant communities in an environment which fosters collaboration, inclusion, and empowerment. OFTC, on the other hand, has a less hands-on approach, providing the infrastructure and letting the projects work on the community side." Both networks are part of larger organizations. Freenode is part of the PDPC, which is a non-profit (501(c)3) organization. Dahlskjaer says that PDPC is "focused on providing community services" for the FOSS community, including the FOSSCON conference scheduled for September in San Diego, Calif. In addition to FOSSCON, Dahlskjaer says that PDPC is "researching and laying the foundations for some future program ideas including, but not limited to, a code grant program, educational programs, and exploring collaboration with the peer2peer foundation." OFTC is part of Software in the Public Interest (SPI), a nonprofit organization (also a 501(c)3) that helps provide a legal umbrella for FOSS-related organizations and takes a hands-off approach with respect to members' operations. In addition to technical and organizational differences, the two networks have cultural differences to consider as well. Graham says that OFTC has a "far more hands-off" culture than freenode. "OFTC's staff do not intervene in matters with its channels unless the integrity or usability of the network itself is at risk, or if requested by the channel's staff. "Freenode, on the other hand, has an extensive system of network involvement in channel administration. Projects using freenode are able to get namespace blocks for their channels, rather than just a name. For example, were NewsForge to want an IRC channel on freenode, it would either be ##NewsForge -- note the extra hash -- or a group contact form would need to be filed to get #newsforge, with only one hash signifying it's an official channel, and #newsforge-* would be reserved for it." The way that user support is handled also differs drastically. Graham says that OFTC generally handles support via the public #oftc channel, while freenode encourages users to contact staff privately. Both work well, he says, but "are completely different approaches. "OFTC's is based on the simple premise that whoever is around can help, even if they are not a staff member, while freenode's support is handled one-on-one with staff signing in and signing out of the on-duty list." The reason for the difference, says Dahlskjaer, is that the two networks differ drastically in size. Since OFTC is smaller and more hands-off in its approach, "this is an approach that works well for them." Ultimately, the two networks may not officially merge, but Graham says that the cooperation will be beneficial either way. "There is an increasingly strong belief within both projects and in feedback that we have received that it is ultimately in the best interest of the open source and free software communities for our two projects, whose goals are shared, to work together instead of competing." Editor's note: David Graham is an editorial contractor at OSTG, Linux.com's parent organization.
https://www.linux.com/news/freenode-and-oftc-irc-networks-buddy
CC-MAIN-2019-26
refinedweb
1,198
58.92
by Michael S. Kaplan, published on 2007/12/27 10:16 -05:00, original URI: One of the interesting consequences I have noted when it comes to dealing with having a Blog with >2200 blogs in it, such as what happens when somebody comes across the Blog as it is and start randomly reading posts from it. When combined with the fact that I no longer tend to shut down comments in damn near any of them, another interesting consequence emerges: some people will start randomly commenting in posts, treating the ones from three years ago no differently than the ones written three days ago. :-) One such person is Tanveer Badar, who has been commenting in many different posts recently.... Though one fact became obvious -- no response was usually expected, since when a response was desired, the question shows up in the Suggestion Box: You wrote ages ago (in August 2005) New in Vista Beta 1: Updated OS casing tables This mentions of $UpCase, the file containing upper case conversion table(s). Now consider, I have Windows XP installed on an NTFS partition. Then, I install Windows Vista. Will $upcase on Windows XP partition be upgraded too or I have to reformat a volume from Windows Vista to upgrade $upcase? If it does get upgraded, are there any problems associated with it? If not upgraded, why not? A very good question, that! Thankfully, the answers are: It is something I covered a little bit recently in In Case you have problems that you might think are ǸȦȘȚȲ, where admittedly the issue is smaller since a jump drive is a bit easier to deal with than a full partition, especially the main partition of the Windows install potentially being upgraded. :-) Basically, since case is preserved but not changed, the definition of case changing is not an issue as long as you always ask for items using the proper case, or if nothing else you are willing to live with the file you get when you have more than one available and you don't ask for the right case potentially getting the "wrong" item back.... Just like I showed in the ǸȦȘȚȲ post. :-) Now with that said, there is an interesting side effect that is covered in the following article from the MS knowledge base: 940830: Error message when you run Chkdsk.exe on a Windows XP-based or on a Windows Server 2003-based computer: “Correcting errors in the uppercase file” Basically, if you dual boot between an XP and a Vista partition you will occasionally see chkdsk being run at boot time (you can also request this be done if you request that chkdsk be run and it cannot when you ask due to the drive being locked). During that run, you will get the message Correcting errors in the uppercase file when that run happens on XP at boot time, even if you do not pass the /F flag to "fix" errors. If you do pass the /F flag then the drive will be "fixed" by which I mean the UpCase table in the drive will be updated (or in this case downdated) to the XP table, though there is no problem with files on the drive violating those rules as long as functions dealing with the files preserve case (and you don't try to move or copy files that would conflict on the tables update/downdated!).... The error does not happen when you run in Vista since the updated chkdsk does not treat the situation as an error and thus does not report it as such. There was originally going to be an update to the older versions of chkdsk,exe but that update was not triaged as being important enough (since other than the possibly mildly unclear error message there is really no error here). So in the end whether to do the update is up to you and there is no need to reformat or even change anything.... This post brought to you by ഗ (U+0d17, aka MALAYALAM LETTER GA) # Tanveer Badar on 28 Dec 2007 6:23 PM: Hi, perhaps I should prefix my name with "Not the random reader”. : -) The reason you are seeing comments on old posts is because I always read a blog back to front when I find one that is interesting. I must say that I am having trouble keeping up with the backlog of all those posts. Hopefully, I will catch up with your (exceedingly high) posting rate in the next month and you won’t see any more “some people will start randomly commenting in posts, treating the ones from three years ago no differently than the ones written three days ago". # Michael S. Kaplan on 28 Dec 2007 8:55 PM: I don't mind it all -- it is quite enjoyable. :-) # Tanveer Badar on 29 Dec 2007 4:43 AM: Nor did I. However, as of this post I wanted to clarify things as they seemed horribly misunderstood. :) # Random Reader on 29 Dec 2007 3:37 PM: There is only one me! I've always thought the NTFS $UpCase mechanism was a very smart bit of forethought in the design. Since it is essentially a database, and there is a specific set of conversion semantics that are required for operational consistency, it makes sense to store those semantics in the database itself. Protection from external changes. I don't understand the chkdsk thing, though. What is modifying the $UpCase table in the first place, that requires chkdsk to fix it? Preserving case in requests might actually be harder than it seems. You can pass FILE_FLAG_POSIX_SEMANTICS to things like CreateFile(), or use the Nt* functions directly without passing the case-insensitive flag, but newer versions of Windows have the object manager force case-insensitivity by default, and there's nothing you can do at an API level to override that. (Unless you're in-kernel, like a driver.) If you end up with two directories having the same name that differs only in case, you'll have an amazingly hard time getting into the non-favored one via normal means, even if you preserve the case in your request. (Differs according to $UpCase, not NLS.) It's difficult to see a situation where this would come up in normal usage, but just the idea that chkdsk and something else are making changes to $UpCase raises a red flag for me... # Yuhong Bao on 31 Dec 2007 10:12 PM: "newer versions of Windows have the object manager force case-insensitivity by default, and there's nothing you can do at an API level to override that. (Unless you're in-kernel, like a driver.)" Install Service for Unix and you can change that. # Random Reader on 1 Jan 2008 3:02 PM: Yeah, I probably should have mentioned, it's a simple registry key to change that behavior. There's mention of it in The problem here though is that it's an administrative setting, not a programmatic one. I missed it last time around, but KB940830 says the chkdsk thing happens when you run an earlier chkdsk (XP/2003) on an NTFS volume formatted by a later OS (Vista). It doesn't mention whether Vista's chkdsk does the same thing though. In any case, the problem scenario I was thinking of should only occur if you put conflicting files on the drive using XP rules, $UpCase is changed to use Vista rules, and then try to access them using the new rules -- similar to the post about the experiment with the jump drive. If Vista's chdksk doesn't screw with $UpCase the way XP's does, this would probably never happen. # Michael S. Kaplan on 1 Jan 2008 5:29 PM: The thing you're missing here is that whether one has the case sensitive or case insensitive setting, one has CASE PRESERVATION. And that means if your $UpCase table does not match your OS table and you have "duplicates" thereby, then everything will will work if you ask with the right case. It works, truly. As for the chkdsk thing, Vista does the same thing, it just does it silently (that is the "fix" they decided not to port downlevel).... # Random Reader on 1 Jan 2008 7:54 PM: I don't think we're talking about the same scenario. Consider a situation where XP says "Filename" and "filename" are different, because it does not know about case differences for the letter 'F'. So, under XP, you can create both "Filename" and "filename" in the same directory, perhaps by accident, with no problems. Now Vista comes along and adds a table entry that says 'F' and 'f' are the same if you ignore case. Both files still exist in that directory, but given the default object manager settings, it is impossible for you to access one of those files via normal APIs. Sample program with many assumptions and a horrid lack of error checking: ------------------------------------ #include <stdio.h> #include <windows.h> int main(void) { HANDLE fh; DWORD count; char buffer[32] = {0}; fh = CreateFile("FILENAME.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_POSIX_SEMANTICS, NULL); WriteFile(fh, "UPPERCASE FILE CONTENTS", 23, &count, NULL); CloseHandle(fh); fh = CreateFile("filename.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_POSIX_SEMANTICS, NULL); WriteFile(fh, "lowercase file contents", 23, &count, NULL); CloseHandle(fh); printf("files created\n"); getchar(); printf("opening uppercase filename... "); fh = CreateFile("FILENAME.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); ReadFile(fh, buffer, sizeof(buffer), &count, NULL); printf("got %s\n", buffer); CloseHandle(fh); printf("opening lowercase filename... "); fh = CreateFile("filename.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); ReadFile(fh, buffer, sizeof(buffer), &count, NULL); printf("got %s\n", buffer); CloseHandle(fh); return 0; } ------------------------------------ When I test that on a 2003 box with the registry key set appropriately per KB929110 so I can distinguish case, both files are successfully created. However, it only reads the contents of FILENAME.txt, despite the fact that I explicitly asked for the other file in the second request. That's the problem I'm talking about. IOW, a lookup in case-insensitive mode finds first match, not best match. (On the same box I could just use FILE_FLAG_POSIX_SEMANTICS to access the other file anyway. On a box without the object manager change, and without administrative access to change the setting, I'm SOL.) Since it sounds like Vista and XP will keep changing $UpCase back and forth in a dual-boot situation, this kind of thing could happen by accident (although it still seems rather unlikely). The correct fix, AFAICT, would be to have chkdsk stop messing with the table. OTOH, if the table got corrupted, chkdsk wouldn't be able to help you. Such are the tradeoffs I guess. # Michael S. Kaplan on 1 Jan 2008 8:21 PM: Since it was a bug for .NET to ever set those values and in my opinion is a bug that they ever did (something I will blog about at some point), I have to reject the test as invalid, sorry! :-) Instead, try doing what I did with the jump drive, and delete one of the files after running chkdsk on it (which will update $UpCase). You will see it deleted the correct file, not the first one.... # Random Reader on 1 Jan 2008 9:04 PM: Hehe! That KB was just one I had handy that mentions the key. It's the same one changed by the SFU/SUA installer if you choose the appropriate option. KB817921 might be more appropriate. (I'd love to hear the story behind how the .NET bug happened!) Unfortunately I don't have a Vista machine to run tests on at the moment, so I'll have to come back to this. LarryBrown on 14 Aug 2009 6:35 AM: It annoys me badly when discussion threads get closed because of age or anyone complains about resurrecting an old thread. I can see the logic in that if it's a personal discussion between two friends and it doesn't make sense to talk about it anymore, but in the case of a programming discussion people should continue to add to the thread for all eternity until the topic naturally passes out of relevance to the world. By adding to the thread we continue to impart more and more knowledge to the topic. Regarding this discussion of the $UPCASE file on NTFS, the situation is this: Vista's format tool write the $UPCASE file differently than does the XP and earlier tools, I think Vista is writing it incorrectly, actually. So to the poster that asked "Who is changing the $UPCASE file," there's your answer, the Vista format tool that formatted the disk when Vista was installed. The Vista chkdsk program has been patched so that it takes no action on the problem, that's why running chkdsk in Vista neither reports nor fixes the problem. LarryBrown on 14 Aug 2009 6:36 AM: The XP CHKDSK program, however, both reports and fixes the problem when run on a disk that contains Vista, another way the $UPCASE file could get changed. Apparently Vista runs equally well against the XP style $UPCASE file or the Vista style file, or maybe you guys were discussing the finer points of that above but I just tuned out because I'm not interested right now. If the file is wrong as I suspect, that Vista CHKDSK has been patched to ignore it is either a sign of negligence (M$ didn't bother to investigate the matter but instead just swept it under the rug by commenting out a check in CHKDSK), or malice (M$ intentionally planted this problem in Vista and then paid hush money to a CHKDSK programmer), or it could be good old plain incompetence of a coordinated nature: FORMAT & CHKDSK both incompetent. However there is a problem that hasn't been mentioned, and that is that the incorrect Vista style $UPCASE file breaks PowerQuest's (or Symantec's) Partition Magic (PM) program. Since that program is useful that makes this $UPCASE issue a problem for me. PM will issue an error 4444 if it encounters this problem and will refuse to proceed with its work. The solution is to run the XP CHKDSK program on the Vista partition so that it will fix the $UPCASE file and then PM can proceed. I have to wonder if this bug was planted maliciously by Microsoft to kill this excellent program. They've done it plenty of times before. I hope that no one here will object that the Vista disk management tool has obsoleted Partition Magic. People that say that obviously don't edit many partitions. To put it briefly, a full featured partition management tool offers many many more functions than does the anemic management tool provided by Vista. One quick example is the ability to grow a partition into free space to its left, a very useful function. Partition Magic does that easily in about 2 minutes, Vista can't do that at all. Michael S. Kaplan on 14 Aug 2009 7:56 AM: One of the other reasons to ask for no more updates is when updates get into untruths, conspiracy theories, and other swill that the blog owner feels are beneath the dignity of the topic. Consider yourself warned, Larry Brown! The only change that was made was to the situation leading to an error msg claiming corruption in the case of a known change that chkdsk was unaware of. The Vista change was not wrong; neither is the Win7 change. When one formats USB jump drives in XP and plugs them into Vista or Win7, one gets the warning to update for the same problem; it is not due to the casing table being wrong or hush money or negligence or any other crap like that.... referenced by 2008/01/12 Blitzkrieging the landscape.NET (aka in this case, two) (aka When is obcaseinsensitive not ObCaseInsensitive?) go to newer or older post, or back to index or month or day
http://archives.miloush.net/michkap/archive/2007/12/27/6875879.html
CC-MAIN-2017-39
refinedweb
2,684
65.46
Amendment in Paras 2.20, 2.21 and 2.22 of the Handbook of Procedure (2015-20). 25-10-2017 DGFT Public Notice No. 37/2015-2020 Acceptance of installation certificate under EPCG scheme by the RAs wherein installation certificate is submitted beyond 18 months DGFT Public Notice No. 36/2015-2020 Onetime condonation of time period in respect of obtaining extension in Export Obligation period under EPCG Scheme DGFT Public Notice No. 35/2015-2020 Onetime condonation of time period in respect of obtaining block-wise extension in Export Obligation period under EPCG Scheme 24-10-2017 DGFT Public Notice No. 34/2015-2020 Onetime relaxation for EO extension and clubbing of Advance Authorizations – reg. 23-10-2017 DGFT Public Notice No. 33/2015-2020 The validity period of duty credit scrips 18-10-2017 DGFT Public Notice No. 32/2015-2020 Amendments in Chapter-4 of Hand Book of Procedures 2015-2020, related to clubbing of Advance Authorisations, extension of Export Obligation period and regularization of bonafide default in the cases where Authorisations were issued for import of drugs from unregistered sources with pre import condition. DGFT Public Notice No. 31/2015-2020 Amendments in Chapter-4 of Hand Book of Procedures 2015-2020, related to nominated agencies. DGFT Public Notice No. 30/2015-2020 Amendments in Appendix 4J of Hand Book of Procedures 2015-20 –reg 09-10-2017 DGFT Public Notice No. 29/2015-2020 Amendment in para 5.25 of HBP 2015-20 of the Handbook of Procedures (HBP) of Foreign Trade Policy (FTP) 2015-20 – regarding 29-09-2017 DGFT Public Notice No. 28/2015-2020 Allocation of quantity for export of preferential quota sugar to EU under CXL quota 21-09-2017 DGFT Public Notice No. 27/2015-2020 Amendment to Paragraph 2.72 (b) of the Handbook of Procedures of the Foreign Trade Policy (FTP) 2015-20 20-09-2017 DGFT Public Notice No. 26/2015-2020 Amendment in Hand Book of Procedures 2015-20 14-09-2017 DGFT Public Notice No. 25/2015-2020 Amendments in SION H-331 for export product “Toothbrushes” –reg In Back to top
http://www.dgft.org/Latest_DGFT_Public_Notices.html
CC-MAIN-2019-51
refinedweb
357
57.77
Missing Part of Redux Saga Experience. The thing is that sagas’ work should be coordinated. After some time of struggling with this mess and finally reading the documentation we in DashBouquet came up with a new approach, which has always been there. Describe a full flow in a saga. This is what the documentation implies, you should just read carefully. Let’s see, what it looks like. It looks like a flow, isn’t it? Sure, describing full flow in saga doesn’t mean that there should be only one saga. The point is that everything is handled from one place. Now, let’s take a look at an actual example. Say, in our app a user is able to fill up a job application and send it to the server for further processing. We want to create a saga that will describe full flow of this process. Everything starts on /create_application_page route when a user clicks an “Apply for a job” button and is redirected to the application form. import {take, call, put, select, fork, cancel, race} from 'redux-saga/effects'; import {LOCATION_CHANGE, push} from 'react-router-redux'; import {takeEvery} from "redux-saga"; import * as api from './api'; function* createApplication(data) { yield put(push(`/application_form`)); const { saveApplication } = yield race({ saveApplication: take(SAVE_APPLICATION), cancelApplication: take(CANCEL_APPLICATION), }); if (saveApplication) { const { data } = saveApplication; yield api.saveApplication(data); yield put(push(`/application_saved`)); } else { yield put(push(`/application_cancaled`)); } } function* watchCreateApplication() { const createApplicationTask = takeEvery(CREATE_APPLICATION, createApplication); while (true) { const {payload: {pathname}} = yield take(LOCATION_CHANGE); if (pathname.search(/^\/create_application_page\/?$/) !== -1) { yield cancel(createApplicationTask); break; } } } Here CREATE_APPLICATIONis an action dispatched when a user clicks “Apply for a job”. Then he is redirected to another page with a form. After the user fills up the form and clicks Submit or Cancel, he is redirected further depending on which action was dispatched. And data is sent to the server only if the user clicks Submit. Also the user may change his mind in the middle of filling up the form and just go by another link without clicking “Cancel”. In this case if he later comes back to /create_application_page where the saga is injected asynchronously, it will be injected one more time, and the data on the server will be created twice, while the user intended to do it only once. We certainly don’t want that, so we need to cancel the task on LOCATION_CHANGE dispatched by redux-router, hence checking the pathname in watchCreateApplication. And just to make things a bit more complicated, we assume, that in the middle of filling up the form, the user can call a dialog with another form, in which he can choose, say, a country and a city he is applying from and submit this data to the server. We can do this by simply forking another saga that would be quite similar to createApplication saga: function* chooseLocation() { yield put(showDialog()); const { saveLocation } = yield race({ saveLocation: take(SAVE_LOCATION), cancelLocation: take(CANCEL_LOCATION), }); if (saveLocation) { const { data } = saveLocation; yield api.saveLocation(data); } yield put(closeDialog()); } function* createApplication() { yield put(push(`/application_form`)); const createLocationTask = takeEvery(CREATE_LOCATION, createLocation) ... yield cancel(createLocationTask); } Here we handle the dialog with showDialog and closeDialog sagas. In two words, they should set some value in the store to tell a page, if the dialog has to be shown or hidden at the moment. In more detail it is a subject for another article. It is important not to forget to cancel the forked tasks. If at some point you find an avalanche of requests going to the server when it was supposed to be only one or two, you probably missed this somewhere. It is a quite simple example. A flow may be much more complicated, with any amount of subflows (though it might be a bad idea from UX point of view). But anyway, what this approach gives is that you can build your flow step by step. You can make changes later quite easily and they will not lead to unexpected behavior from other sagas. You can make it more complicated, if you need to, but no matter, how many forks your flow has, you never get lost in it. More tutorials in this series: Using Normalizr to Organize Data in Stores – Practical Guide Usage of Reselect in a React-Redux Application Using Normalizr to Organize Data in Store. Part 2
https://dashbouquet.com/blog/frontend-development/missing-part-of-redux-saga-experience
CC-MAIN-2018-09
refinedweb
723
52.7
Combining multiple forms in Flask-WTForms but validating independently Sam Partington Jan 17 ・5 min read Introduction We have a Flask project coming up at White October which will include a user profile form. This form can be considered as one big form or as multiple smaller forms and can also be submitted as a whole or section-by-section. As part of planning for this work, we did a proof-of-concept around combining multiple subforms together in Flask-WTForms and validating them. Note that this is a slightly different pattern to "nested forms". Nested forms are often used for dynamic repeated elements - like adding multiple addresses to a profile using a single nested address form repeatedly. But our use case was several forms combined together in a non-dynamic way and potentially processed independently. This article also doesn't consider the situation of having multiple separate HTML forms on one page. This document explains the key things you need to know to combine forms together in Flask-WTF, whether you're using AJAX or plain postback. Subforms The first thing to know is how to combine multiple WTForms forms into one. For that, use the FormField field type (aka "field enclosure"). Here's an example: from flask_wtf import FlaskForm import wtforms class AboutYouForm(FlaskForm): first_name = wtforms.StringField( label="First name", validators=[wtforms.validators.DataRequired()] ) last_name = wtforms.StringField(label="Last name") class ContactDetailsForm(FlaskForm): address_1 = wtforms.StringField( label="Address 1", validators=[wtforms.validators.DataRequired()] ) address_2 = wtforms.StringField(label="Address 2") class GiantForm(FlaskForm): about_you = wtforms.FormField(AboutYouForm) contact_details = wtforms.FormField(ContactDetailsForm) As you can see, the third form here is made by combining the first two. You can render these subforms just like any other form field: {{ form.about_you }} (Form rendering is discussed in more detail below.) Validating a subform Once we'd combined our forms, the second thing we wanted to prove was that they could be validated independently. Normally, you'd validate a (whole) form like this: if form.validate_on_submit() # do something ( validate_on_submit returns true if the form has been submitted and is valid.) It turns out that you can validate an individual form field quite easily. For our about_you field (which is a subform), it just looks like this: form.about_you.validate(form) Determining what to validate We added multiple submit buttons to the form so that either individual subforms or the whole thing could be processed. If you give the submit buttons different names, you can easily check which one was pressed and validate and save appropriately (make sure you only save the data you've validated): <input type="submit" name="submit-about-you" value="Just submit About You subform"> <input type="submit" name="submit-whole-form" value="Submit whole form"> And then: if "submit-about-you" in request.form and form.about_you.validate(form): # save About You data here elif "submit-whole-form" in request.form and form.validate(): # save all data here If you have one route method handling both HTTP GET and POST methods, there's no need to explicitly check whether this is a postback before running the above checks - neither button will be in request.form if it's not a POST. Alternative approaches You could alternatively give both submit buttons the same name and differentiate on value. However, this means that changes to the user-facing wording on your buttons (as this is their value property) may break the if-statements in your code, which isn't ideal, hence why different names is our recommended approach. If you want to include your submit buttons in your WTForms form classes themselves rather than hard-coding the HTML, you can check which one was submitted by checking the relevant field's data property - see here for a small worked example of that. Gotcha: Browser-based validation and multiple submit buttons There's one snag you'll hit if you're using multiple submit buttons to validate/save data from just one subform of a larger form. If your form fields have the required property set (which WTForms will do if you use the DataRequired validator, for example), then the browser will stop you submitting the form until all required fields are filled in - it doesn't know that you're only concerned with part of the form (since this partial-submission is implemented server-side). Therefore, assuming that you want to keep using the required property (which you should), you'll need to add some Javascript to dynamically alter the form field properties on submission. This is not a problem if you're using AJAX rather than postbacks for your form submissions; see below how to do that. Rendering subforms in a template The examples in this section use explicit field names. In practice, you'll want to create a field-rendering macro to which you can pass each form field rather than repeating this code for every form field you have. That link also shows how to render a field's label and widget separately, which gives you more control over your markup. As mentioned above, the subforms can be rendered with a single line, just like any other field: {{ form.about_you }} If you want to render fields from your subforms individually, it'll look something like this: <label for="{{ form.about_you.first_name.id }}">{{ form.about_you.first_name.label }}</label> {{ form.about_you.first_name }} As you see, you can't do single-line rendering of form fields and their labels for individual fields within subforms - you have to explicitly render the label. Displaying subform errors For a normal form field, you can display associated errors by iterating over the errors property like this: {% if form.your_field_name.errors %} <ul class=errors> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} In this case, errors is just a list of error strings for the field. For a subform where you're using the FormField field type, however, errors is a dictionary mapping field names to lists of errors. For example: { 'first_name': ['This field is required.'], 'last_name': ['This field is required.'], } Therefore, iterating over it in your template is more complicated. Here's an example which displays errors for all fields in a subform (notice the use of the items method): {% if form.about_you.errors %} <ul class="errors"> {% for error_field, errors in form.about_you.errors.items() %} <li>{{ error_field }}: {{ errors|join(', ') }}</li> {% endfor %} </ul> {% endif %} Doing it with AJAX So far, we've considered the case of validating subforms when data is submitted via a full-page postback. However, you're likely to want to do subform validation using AJAX, asynchronously posting form data back to the Flask application using JavaScript. There's already an excellent article by Anthony Plunkett entitled "Posting a WTForm via AJAX with Flask", which contains almost everything you need to know in order to do this. In this article, therefore, I'll just finish by elaborating on the one problem you'll have if doing this with multiple submit buttons - determining the submit button pressed Determining the submit button pressed When posting data back to the server with JavaScript, you're likely to use a method like jQuery's serialize. However, the data produced by this method doesn't include details of the button clicked to submit the form. There are various ways you can work around this limitation. The approach I found most helpful was to dynamically add a hidden field to the form with the same name and value as the submit button (see here). That way, Python code like if "submit-about-you" in request.form (see above) can remain unchanged whether you're using AJAX or postbacks. a11y and JS - A Seemingly Unconventional Romance I want you to know that JavaScript isn’t the enemy of accessibility. Instead, lack of empathy is. Minor Violations Java code analysis on Duerank Yevhen Krasnokutsky - Feb 8 Django inline formsets with Class-based views and crispy forms Xenia - Feb 13 Creating a Type Checker Magic Function in IPython Sebastian Witowski - Feb 8
https://dev.to/sampart/combining-multiple-forms-in-flask-wtforms-but-validating-independently-cbm
CC-MAIN-2019-09
refinedweb
1,333
53.41
SciChart® the market leader in Fast WPF Charts, WPF 3D Charts, iOS Chart, Android Chart and JavaScript Chart Components Hello, I am evaluating SciChart (for info : v 2.3) for integration into a WPF application. For the application is important that the user can interact with the chart. So I have been trying to get that working with SciChart : with the MouseWheelZoomModifier we can use the mouse wheel to zoom the chart and with ZoomPanModifier we can use the left-mouse button to pan the chart. Excellent ! But then we would like to have the same behavior on the axes : Mouse wheel to zoom an axis and left-mouse button to move it up and down. Until now I found only the XAxisDragModifier to make an axis interactive but that has a quite different behavior. So my question is : How can I get the same zooming and panning behavior on the axes ? thanks in advance for any help, Stefaan Norway Hi Stefaan, I believe that MouseWheelModifier has zoom and pan in X or Y direction when you hold down SHIFT or CTRL while mouse-wheeling. Can you try that? I believe there are some more properties on MouseWheelZoomModifier which can be adjusted to change its behaviour. /// <summary> /// Gets or sets the <see cref="ActionType"/> to perform on mouse-wheel interaction /// </summary> public ActionType ActionType { get { return (ActionType)GetValue(ActionTypeProperty); } set { SetValue(ActionTypeProperty, value); } } where ActionType has values of Zoom, Pan. Try playing with that. If you have to you can also dynamically switch ActionType if the user is holding down CTRL. Alternatively, you can create your own modifier! Our framework allows you to extend or create your own chart interations. Take a look at this forum post for inspiration Andrew
https://www.scichart.com/questions/wpf/same-zooming-and-panning-on-axes-as-on-the-chart
CC-MAIN-2021-39
refinedweb
290
53.61