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 |
|---|---|---|---|---|---|
MySQL for Python version 0.3.5
Python 2.0
I have two Python versions, one compiled with thread
support and the othe without threads. The version
without threads is used in mod_python, because
compatibility issues.
When I try to use "MySQL for Python" from the non
threading version, I receive a runtime error since
"threading.Lock()" fails.
The threading autodetect in the library if fooled since
it only tries to import the module "threading".
Neveretheless, I can have a python version with that
module and NOT threading support.
The patch is fairly simple:
>>>>>
--- MySQLdb.py.old Thu Apr 26 16:42:28 2001
+++ MySQLdb.py Tue Apr 17 16:22:13 2001
@@ -27,6 +27,7 @@
try:
import threading
+ threading.Lock()
_threading = threading
del threading
except:
<<<<<
Andy Dustman
2001-05-09
Logged In: YES
user_id=71372
There's a new MySQLdb tree for 0.9.0. You can specifically
tell it to not use threads by supplying a threads=0
parameter to connect(). If there really is a faux threading
module on systems without threads, I will have to rework it
a little, but threads=0 should still work.
Andy Dustman
2001-05-11
Logged In: YES
user_id=71372
I've taken out all the thread stuff entirely. The only time
it was ever used is when you tried to share a connection
between two threads. You can still use threads, just don't
try to share them between threads unless you use a lock to
make sure they both don't try to use the connection
simultaneously. | http://sourceforge.net/p/mysql-python/patches/1/ | CC-MAIN-2015-40 | refinedweb | 259 | 73.78 |
Data structures are an important part of programming and coding interviews. These skills show your ability to think complexly, solve ambiguous problems, and recognize coding patterns.
Programmers use data structures to organize data, so the more efficient your data structures are, the better your programs will be.
Today, we will take a deep dive into one of the most popular data structures out there: trees.
Today, we will cover:
Data structures are used to store and organize data. We can use algorithms to manipulate and use our data structures. Different types of data are organized more efficiently by using different data structures.
Trees are non-linear data structures. They are often used to represent hierarchical data. For a real-world example, a hierarchical company structure uses a tree to organize.
Trees are a collection of nodes (vertices), and they are linked with edges (pointers), representing the hierarchical connections between the nodes. A node contains data of any type, but all the nodes must be of the same data type. Trees are similar to graphs, but a cycle cannot exist in a tree. What are the different components of a tree?
Root: The root of a tree is a node that has no incoming link (i.e. no parent node). Think of this as a starting point of your tree.
Children: The child of a tree is a node with one incoming link from a node above it (i.e. a parent node). If two children nodes share the same parent, they are called siblings.
Parent: The parent node has an outgoing link connecting it to one or more child nodes.
Leaf: A leaf has a parent node but has no outgoing link to a child node. Think of this as an endpoint of your tree.
Subtree: A subtree is a smaller tree held within a larger tree. The root of that tree can be any node from the bigger tree.
Depth: The depth of a node is the number of edges between that node and the root. Think of this as how many steps there are between your node and the tree’s starting point.
Height: The height of a node is the number of edges in the longest path from a node to a leaf node. Think of this as how many steps there are between your node and the tree’s endpoint. The height of a tree is the height of its root node.
Degree: The degree of a node refers to the number of sub-trees.
Trees can be applied to many things. The hierarchical structure gives a tree unique properties for storing, manipulating, and accessing data. Trees form some of the most basic organization of computers. We can use a tree for the following:
But, how does that all look in code? To build a tree in Java, for example, we start with the root node.
Node<String> root = new Node<>("root");
Once we have our root, we can add our first child node using
addChild, which adds a child node and assigns it to a parent node. We refer to this process as insertion (adding nodes) and deletion (removing nodes).
Node<String> node1 = root.addChild(new Node<String>("node 1"));
We continue adding nodes using that same process until we have a complex hierarchical structure. In the next section, let’s look at the different kinds of trees we can use.
There are many types of trees that we can use to organize data differently within a hierarchical structure. The tree we use depends on the problem we are trying to solve. Let’s take a look at the trees we can use in Java. We will be covering:
In N-ary tree, a node can have child nodes from 0-N. For example, if we have a 2-ary tree (also called a Binary Tree), it will have a maximum of 0-2 child nodes.
Note: The balance factor of a node is the height difference between the left and right subtrees.
A balanced tree is a tree with almost all leaf nodes at the same level, and it is most commonly applied to sub-trees, meaning that all sub-trees must be balanced. In other words, we must make the tree height balanced, where the difference between the height of the right and left subtrees do not exceed one. Here is a visual representation of a balanced tree.
There are three main types of binary trees based on their structures.
A complete binary tree exists when every level, excluding the last, is filled and all nodes at the last level are as far left as they can be. Here is a visual representation of a complete binary tree.
A full binary tree (sometimes called proper binary tree) exits when every node, excluding the leaves, has two children. Every level must be filled, and the nodes are as far left as possible. Look at this diagram to understand how a full binary tree looks.
A perfect binary tree should be both full and complete. All interior nodes should have two children, and all leaves must have the same depth. Look at this diagram to understand how a perfect binary tree looks.
Note: You can also have a skewed binary tree, where all the nodes are shifted to the left or right, but it is best practice to avoid this type of tree in Java, as it is far more complex to search for a node.
A Binary Search Tree is a binary tree in which every node has a key and an associated value. This allows for quick lookup and edits (additions or removals), hence the name “search”. A Binary Search Tree has strict conditions based on its
node value. It’s important to note that every Binary Search Tree is a binary tree, but not every binary tree is a Binary Search Tree.
What makes them different? In a Binary Search Tree, the left subtree of a subtree must contain nodes with fewer keys than a node’s key, while the right subtree will contain nodes with keys greater than that node’s key. Take a look at this visual to understand this condition.
In this example, the node Y is a parent node with two child nodes. All nodes in subtree 1 must have a value less than node Y, and subtree 2 must have a greater value than node Y.
AVL trees are a special type of Binary Search tree that are self-balanced by checking the balance factor of every node. The balance factor should either be +1, 0, or -1. The maximum height difference between the left and right sub-trees can only be one.
If this difference becomes more than one, we must re-balance our tree to make it valid using rotation techniques. These are most common for applications where searching is the most important operation. Look at this visual to see a valid AVL tree.
A red-black tree is another type of self-balancing Binary Search Tree, but it has some additional properties to AVL trees. The nodes are colored either red or black to help re-balance a tree after insertion or deletion. They save you time with balancing. So, how do we color our nodes?
A 2-3 tree is very different from what we’ve learned so far. Unlike a Binary Search Tree, a 2-3 Tree is a self-balancing, ordered, multiway search tree. It is always perfectly balanced, so every leaf node is equidistant from the root. Every node, other than leaf nodes, can be either a 2-Node (a node with a single data element and two children) or a 3-node (a node with two data elements and three children). A 2-3 tree will remain balanced no matter how many insertions or deletions occur.
A 2-3-4 tree is a search tree that can accommodate more keys than a 2-3 tree. It covers the same basics as a 2-3 tree, but adds the following properties:
Learn data structures and algorithms in Java without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments - making learning quick and efficient.
Algorithms for Coding Interviews in Java
To use trees, we can traverse them by visiting/checking every node of a tree. If a tree is “traversed”, this means every node has been visited. There are four ways to traverse a tree. These four processes fall into one of two categories: breadth-first traversal or depth-first traversal.
Inorder: Think of this as moving up the tree, then back down. You traverse the left child and its sub-tree until you reach the root. Then, traverse down the right child and its subtree. This is a depth-first traversal.
Preorder: This of this as starting at the top, moving down, and then over. You start at the root, traverse the left sub-tree, and then move over to the right sub-tree. This is a depth-first traversal.
Postorder: Begin with the left-sub tree and move over to the right sub-tree. Then, move up to visit the root node. This is a depth-first traversal.
Levelorder: Think of this as a sort of zig-zag pattern. This will traverse the nodes by their levels instead of subtrees. First, we visit the root and visit all children of that root, left to right. We then move down to the next level until we reach a node that has no children. This is the left node. This is a breadth-first traversal.
So, what’s the difference between a breadth-first and depth-first traversal? Let’s take a look at the algorithms Depth-First Search (DFS) and Breath-First Search (BFS) to understand this better.
Note: Algorithms are a sequence of instructions for performing certain tasks. We use algorithms with data structures to manipulate our data, in this case, to traverse our data.
Overview: We follow a path from the starting node to the ending node and then start another path until all nodes are visited. This is commonly implemented using stacks, and it requires less memory than BFS. It is best for topographical sorting, such as graph backtracking or cycle detection.
The steps for the
DFS algorithm are as follows:
visitedbefore proceeding, or you will be stuck in an infinite loop.
Overview: We proceed level-by-level to visit all nodes at one level before going to the next. The BFS algorithm is commonly implemented using queues, and it requires more memory than the DFS algorithm. It is best for finding the shortest path between two nodes.
The steps for the
BFS algorithm are as follows:
visitedbefore proceeding, or you will be stuck in an infinite loop.
It’s important to know how to perfom a search in a tree. Searching means we are locating a specific element or node in our data structure. Since data in a Binary Search Tree is ordered, searching is quite easy. Let’s see how it’s done.
nodewith that value or reach a leaf
node, meaning that the value doesn’t exist.
In the below example, we are searching for the value
3 in our tree. Take a look.
Let’s see that in Java code now!
public class BinarySearchTree { … public boolean search(int value) { if (root == null) return false; else return root.search(value); } } public class BSTNode { … public boolean search(int value) { if (value == this.value) return true; else if (value < this.value) { if (left == null) return false; else return left.search(value); } else if (value > this.value) { if (right == null) return false; else return right.search(value); } return false; } }
Congratulations on completing your next step into the world of Java and data structures. However, there are still many interview questions and data structures to practice.
Here are some of the common data structures challenges you should look into to get a better sense of how to use trees:.
Join a community of 500,000 monthly readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips. | https://www.educative.io/blog/data-structures-trees-java | CC-MAIN-2021-31 | refinedweb | 2,025 | 74.08 |
Write PVTK XML PolyData files. More...
#include <vtkXMLPPolyDataWriter.h>
Write PVTK XML PolyData files.
vtkXMLPPolyDataWriter writes the PVTK XML PolyData file format. One poly data input can be written into a parallel file format with any number of pieces spread across files. The standard extension for this writer's file format is "pvtp". This writer uses vtkXMLPolyDataWriter to write the individual piece files.
Definition at line 37 of file vtkXMLPPolyDataWriter.h.
Definition at line 41 of file vtkXMLPPolyPUnstructuredDataWriter.
Reimplemented from vtkXMLPUnstructured.
Get/Set the writer's input.
Get the default file extension for files written by this writer.
Implements vtkXMLWriter.
Fill the input port information objects for this algorithm.
This is invoked by the first call to GetInputPortInformation for each port so subclasses can specify what they can handle.
Reimplemented from vtkAlgorithm.
Implements vtkXMLWriter.
Implements vtkXMLPUnstructuredDataWriter. | https://vtk.org/doc/nightly/html/classvtkXMLPPolyDataWriter.html | CC-MAIN-2021-17 | refinedweb | 136 | 53.47 |
CODECHEF April Cook-off ( Div. 2 ) – Making a Meal in C++
In this C++ tutorial, we are going to discuss the codechef April Cook-off problem “Making a meal”. This problem uses the concept of string and basic mathematics only.
Problem Statement
There are total N strings S1, S2, S3,______Sn. We have to find that total how many times we can form the word “codechef” using the characters of these N strings. If a character appears more than one time it can be used many times. All characters are in lower case English letter.
INPUT
Input consists of test cases and for each test case it consists of an integer N and next N line follows strings.
OUTPUT
Output must consist of the maximum number of times we can form the word “codechef ” using the characters of N strings in each test case.
Algorithm
- Input N strings for each test case.
- Count the occurrence of characters ‘c’ , ‘o’ , ‘d’ , ‘e’ , ‘h’ , ‘f” for each string.
- Now, in each word of “codechef” c needed to be present 2 times, e 2 times and rest characters 1 time only.
- So, in run the while loop till frequency any character does not become zero and use a counter to check how many time you run the while loop also check that character ‘c’ and ‘e’ should be greater than 1 always.
- In while loop decrement count of character ‘c’ and ‘e’ twice while rest character once.
C++ code implementation for making a meal) #define for(i,a,b) for(int i=a;i<b;i++) using namespace std; typedef long long ll; ll i,j; int main() { ll t; cin>>t; while(t--) { ll n; cin>>n; string s; ll c=0,o=0,d=0,e=0,h=0,f=0; for(i,0,n) { cin>>s; for(j,0,s.length()) { if(s[j]=='c') c++; if(s[j]=='o') o++; if(s[j]=='d') d++; if(s[j]=='e') e++; if(s[j]=='h') h++; if(s[j]=='f') f++; } } ll count=0; while(c!=0 && o!=0 && d!=0 && e!=0 && h!=0 && f!=0 && c>1 && e>1) { count++; c=c-2; o--; d--; e=e-2; h--; f--; } cout<<count<<endl; } }
Example
Input
3 6 cplusplus oscar deck fee hat near 5 code hacker chef chaby dumbofe 5 codechef chefcode fehcedoc cceeohfd codechef
OUTPUT
1 2 5
Read more, | https://www.codespeedy.com/making-a-meal-codechef-april-cook-off-div-2/ | CC-MAIN-2019-43 | refinedweb | 403 | 76.86 |
Function pointers are pointers that point to functions instead of data types. They can be used to allow variability in the function that is to be called, at run-time.
returnType (*name)(parameters)
typedef returnType (*name)(parameters)
typedef returnType Name(parameters);
Name *name;
typedef returnType Name(parameters);
typedef Name *NamePtr;
#include <stdio.h> /* increment: take number, increment it by one, and return it */ int increment(int i) { printf("increment %d by 1\n", i); return i + 1; } /* decrement: take number, decrement it by one, and return it */ int decrement(int i) { printf("decrement %d by 1\n", i); return i - 1; } int main(void) { int num = 0; /* declare number to increment */ int (*fp)(int); /* declare a function pointer */ fp = &increment; /* set function pointer to increment function */ num = (*fp)(num); /* increment num */ num = (*fp)(num); /* increment num a second time */ fp = &decrement; /* set function pointer to decrement function */ num = (*fp)(num); /* decrement num */ printf("num is now: %d\n", num); return 0; }
#include <stdio.h> enum Op { ADD = '+', SUB = '-', }; /* add: add a and b, return result */ int add(int a, int b) { return a + b; } /* sub: subtract b from a, return result */ int sub(int a, int b) { return a - b; } /* getmath: return the appropriate math function */ int (*getmath(enum Op op))(int,int) { switch (op) { case ADD: return &add; case SUB: return ⊂ default: return NULL; } } int main(void) { int a, b, c; int (*fp)(int,int); fp = getmath(ADD); a = 1, b = 2; c = (*fp)(a, b); printf("%d + %d = %d\n", a, b, c); return 0; }.
Just like
char and
int, a function is a fundamental feature of C. As such, you can declare a pointer to one: which means that you can pass which function to call to another function to help it do its job. For example, if you had a
graph() function that displayed a graph, you could pass which function to graph into
graph().
// A couple of external definitions to make the example clearer extern unsigned int screenWidth; extern void plotXY(double x, double y); // The graph() function. // Pass in the bounds: the minimum and maximum X and Y that should be plotted. // Also pass in the actual function to plot. void graph(double minX, double minY, double maxX, double maxY, ???? *fn) { // See below for syntax double stepX = (maxX - minX) / screenWidth; for (double x=minX; x<maxX; x+=stepX) { double y = fn(x); // Get y for this x by calling passed-in fn() if (minY<=y && y<maxY) { plotXY(x, y); // Plot calculated point } // if } for } // graph(minX, minY, maxX, maxY, fn)
So the above code will graph whatever function you passed into it - as long as that function meets certain criteria: namely, that you pass a
double in and get a
double out. There are many functions like that -
sin(),
cos(),
tan(),
exp() etc. - but there are many that aren't, such as
graph() itself!
So how do you specify which functions you can pass into
graph() and which ones you can't? The conventional way is by using a syntax that may not be easy to read or understand:
double (*fn)(double); // fn is a pointer-to-function that takes a double and returns one
The problem above is that there are two things trying to be defined at the same time: the structure of the function, and the fact that it's a pointer. So, split the two definitions! But by using
typedef, a better syntax (easier to read & understand) can be achieved.
All C functions are in actuality pointers to a spot in the program memory where some code exists. The main use of a function pointer is to provide a "callback" to other functions (or to simulate classes and objects).
The syntax of a function, as defined further down on this page is:
returnType (*name)(parameters)
A mnemonic for writing a function pointer definition is the following procedure:
returnType name(parameters)
returnType (*name)(parameters)
Just like you can have a pointer to an int, char, float, array/string, struct, etc. - you can have a pointer to a function.
Declaring the pointer takes the return value of the function, the name of the function, and the type of arguments/parameters it receives.
Say you have the following function declared and initialized:
int addInt(int n, int m){ return n+m; }
You can declare and initialize a pointer to this function:
int (*functionPtrAdd)(int, int) = addInt; // or &addInt - the & is optional
If you have a void function it could look like this:
void Print(void){ printf("look ma' - no hands, only pointers!\n"); }
Then declaring the pointer to it would be:
void (*functionPtrPrint)(void) = Print;
Accessing the function itself would require dereferencing the pointer:
sum = (*functionPtrAdd)(2, 3); //will assign 5 to sum (*functionPtrPrint)(); //will print the text in Print function
As seen in more advanced examples in this document, declaring a pointer to a function could get messy if the function is passed more than a few parameters. If you have a few pointers to functions that have identical "structure" (same type of return value, and same type of parameters) it's best to use the typedef command to save you some typing, and to make the code more clear:
typedef int (*ptrInt)(int, int); int Add(int i, int j){ return i+j; } int Multiply(int i, int j){ return i*j; } int main() { ptrInt ptr1 = Add; ptrInt ptr2 = Multiply; printf("%d\n", (*ptr1)(2,3)); //will print 5 printf("%d\n", (*ptr2)(2,3)); //will print 6 return 0; }
You can also create an Array of function-pointers. If all the pointers are of the same "structure":
int (*array[2]) (int x, int y); // can hold 2 function pointers array[0] = Add; array[1] = Multiply;
You can learn more here and here.
It is also possible to define an array of function-pointers of different types, though that would require casting when-ever you want to access the specific function. You can learn more here. | https://sodocumentation.net/c/topic/250/function-pointers | CC-MAIN-2022-21 | refinedweb | 996 | 57.44 |
How do you dynamically set local variable in Python?
(where the variable name is dynamic)
UPDATE: I'm aware this isn't good practice, and the remarks are legit, but this doesn't make it a bad question, just a more theoretical one - I don't see why this justifies downvotes.
Contrary to other answers already posted you cannot modify
locals() directly and expect it to work.
>>> def foo(): lcl = locals() lcl['xyz'] = 42 print(xyz) >>> foo() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> foo() File "<pyshell#5>", line 4, in foo print(xyz) NameError: global name 'xyz' is not defined
Modifying
locals() is undefined. Outside a function when
locals() and
globals() are the same it will work; inside a function is will usually not work.
Use a dictionary, or set an attribute on an object:
d = {} d['xyz'] = 42 print(d['xyz'])
or if you prefer, use a class:
class C: pass obj = C() setattr(obj, 'xyz', 42) print(obj.xyz)
Edit:
Access to variables in namespaces that aren't functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define
__slots__). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn't a dictionary until you call
locals().
In the C implementation of Python
locals() (called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls to
locals() will return the same dictionary, but every call to
locals() will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned from
locals() therefore only last until the next call to
locals() in the same scope.
In IronPython things work a bit differently. Any function that calls
locals() inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables BUT that's only if you explicitly call
locals() under that name. If you bind a different name to the
locals function in IronPython then calling it gives you the local variables for the scope where the name was bound and there's no way to access the function locals through it:
>>> def foo(): ... abc = 123 ... lcl = zzz() ... lcl['abc'] = 456 ... deF = 789 ... print(abc) ... print(zzz()) ... print(lcl) ... >>> zzz =locals >>> foo() 123 {'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456} {'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456} >>>
This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by
locals(). | https://codedump.io/share/IpxeXpE7tP77/1/dynamically-set-local-variable | CC-MAIN-2018-09 | refinedweb | 510 | 51.11 |
Log message:
Update net/powerdns* to 4.1.0.
PowerDNS Authoritative Server 4.1.0
===========================================================
- Improved performance: 400% speedup in some scenarios
- Crypto API: DNSSEC fully configurable via RESTful API
- Improved documentation
- Database related improvements
- Enhanced tooling
- Support for TCP Fast Open
- Support for non-local bind
- Support for Botan 2.x (and removal of support for Botan 1.10)
- Our packages now ship with PKCS #11 support.
- Recursor passthrough removal
Full changelog: … g/4.1.html
PowerDNS Authoritative Server 4.0.5
===========================================================
Fixes
- Fix for missing check on API operations (CVE-2017-15091)
- Bindbackend: do not corrupt data supplied by other backends in
getAllDomains
- API: prevent sending nameservers list and zone-level NS in rrsets
- gpgsql: make statement names actually unique
- Fix remotebackend params
- Fix godbc query logging
- For create-slave-zone, actually add all slaves, and not only first n
times
- Fix a regression in axfr-rectify + test
- When making a netmask from a comboaddress, we neglected to zero the
port
- Fix libatomic detection on ppc64
- Catch DNSName exception in the Zoneparser
- Publish inactive KSK/CSK as CDNSKEY/CDS
- Handle AFSDB record separately due to record structure.
- Treat requestor's payload size lower than 512 as equal to 512
- Correctly purge entries from the caches after a transfer
- Handle a signing pipe worker dying with work still pending
- Ignore SOA-EDIT for PRESIGNED zones.
- Check return value for all getTSIGKey calls.
Improvements
- Fix ldap-strict autoptr feature, including a test
- mydnsbackend: Add getAllDomains
- Stubresolver: Use only recursor setting if given
- LuaWrapper: Allow embedded NULs in strings received from Lua
- sdig: Clarify that the ednssubnet option takes "subnet/mask"
- Tests: Ensure all required tools are available
- PowerDNS sdig does not truncate trailing bits of EDNS Client Subnet
mask
- LuaJIT 2.1: Lua fallback functionality no longer uses Lua namespace
- Add support for Botan 2.x
- Ship ldapbackend schema files in tarball
- Collection of schema changes
- Fix typo in two log messages
- Add help text on autodetecting systemd support
- Use a unique pointer for bind backend's d_of
- Fix some of the issues found by @jpmens
Log message:
Update net/powerdns (and modules) to 3.4.9.
PowerDNS Authoritative Server 3.4.9
===================================
This is a minor bugfix and performance release. Two contributions
by Kees Monshouwer make 3.4.9 fully compatible with the new single
key ECDSA default that is coming in version 4.0.0.
Changes since 3.4.8:
- use OpenSSL for ECDSA signing where available (Kees Monshouwer)
- allow common signing key (Kees Monshouwer)
- Add a disable-syslog setting
- fix SOA caching with multiple backends (Kees Monshouwer)
- whitespace-related zone parsing fixes ticket #3568
- bindbackend: fix, set domain in list() (Kees Monshouwer)
PowerDNS Authoritative Server 3.4.8
===================================
This is a small bugfix release..
Changes since 3.4.7:
-)
PowerDNS Authoritative Server 3.4.7
===================================
This is a security release fixing Security Advisory 2015-03)
Log message:
Bump PKGREVISION for security/openssl ABI bump.
Log message:
Update powerdns to 3.4.6.
This is a security release fixing
Log message:
Change powerdns dependency from polarssl to mbedtls. Streamline bl3 setup
while at it. Bump PKGREVISION (and of the module packages).
Log message:
Update PowerDNS to 3.4.1.
pkgsrc changes:
- SQLite 2.x support no longer exists
- SQLite 3.x support cannot be compiled outside the main package because
of how symbols are distributed, so making it a compile time option
for net/powerdns now.
Too many changes since 2.9.22.5 (over 2 years ago), see the full changelog:
Upgrade notes:
- PowerDNS 3.4 comes with a mandatory database schema upgrade coming from
any previous 3.x release.
- PowerDNS 3.1 introduces native SQLite3 support for storing key material for
DNSSEC in the bindbackend. With this change, support for bind+gsql-setups
('hybrid mode') has been dropped.
- PowerDNS 3.0 introduces full DNSSEC support which requires changes
to database schemas. By default, old non-DNSSEC schema is assumed.
Please see the docs on upgrading for particular steps that need to be taken:
Log message:
Recursive PKGREVISION bump for OpenSSL API version bump.
Log message:
PKGREVISION bumps for the security/openssl 1.0.1d update. | http://pkgsrc.se/net/powerdns-ldap | CC-MAIN-2018-47 | refinedweb | 689 | 55.74 |
Single file deployment concept in ASP.NET with WebAPI
Deployment contained in single file using WebAPI
As much as this sound new to you, it actually isn't.
If you worked on any Windows From application in .NET you had an option to embedded files in your form like images, icons and even sounds and videos. This made deployment a lot easier because you only have to deploy one .exe file.
In ASP.NET this functionality was provided with WebResource.axd.
- Add the image to your project.
- In the solution explorer, click the file, and in the property window, change build action to "embedded resource."
- Add the following to your AssemblyInfo.cs file:
"image/gif")]Important note here... the "MyNameSpaces" comes from the default namespace indicated in the project properties. The "Resources" comes from the fact that I happened to put the image file in the "Resources" folder I made.
- In your control rendering code, you'll need the following to produce a usable URL for the image:
Page.ClientScript.GetWebResourceUrl(typeof(MyNameSpaces.MyControl), "MyNameSpaces.Resources.MyImage.gif")
- Notice I used the same naming convention here.
- Compile away.
This should produce a URL in your rendered control that looks something like:
With new version of .NET framework WebAPI is introduced and one of it's roles is to provide different content for actions implemented in them using HTTP not only for transport as SOAP does, but for data storing as well. Providing embedded resource to a web page from WebAPI is pretty similar to WebResource.axd approach but it is a bit easier and URL of resources are a lot more SEO friendly then form mentioned above.
Single fiel deployment using WebAPI I implemented in Umbraco plugin I worked on (). The following sample code is derived from this project.
To embed file inside DLL is the same for any approach you go with
- Add the image to your project.
- In the solution explorer, click the file, and in the property window, change build action to "embedded resource."
- Compile
After compilation file is embedded inside DLL. Now, all we have to do is to pull it out.
Code for pulling out the resources for project mentioned above can be found at
For example purposes I will use the following method
public HttpResponseMessage GetEmbededGif(string id) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); MemoryStream ms = new MemoryStream(); Common.GetResourceBitmap(id).Save(ms, ImageFormat.Gif); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(ms.ToArray()); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif"); return result; }
Now to load image on the page you will have to set src attribute to something like this /api/resources/GetEmbededGif/image.gif
I used this approach for Umbraco package, because for every new update I do, users can just download compiled DLL and replace the old one with the new one. In some of the releases I added some files, so it would be more or less a nightmare for some who uses it to read manual and copy all the files at the right location, or even have to set read permissions for it.
People like it simple, so copy/paste approach is the best solution for deployment of things like plugins and extensions.
References
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage. | https://dejanstojanovic.net/aspnet/2014/september/single-file-deployment-concept-in-aspnet-with-webapi/ | CC-MAIN-2019-22 | refinedweb | 579 | 55.44 |
What are references?
References are just aliases to the variable names i.e. an alternative name to our original variable name.
For example,
int &ref = var;
Now ref is a reference (alias) of variable var. The variable var can be called by both names now, var and ref.
Let’s look at a code snippet,
int var = 4; int &ref = var; //ref is now a reference to var var++; //var now has value 5 ref++; //var now has value 6 (ref acts just like var) cout << var; //prints 6 cout << ref; //prints 6
This shows us that ref is just another name of var.
Some important points to note:
When a reference variable is created, memory is not set aside for another variable. It is just an alias name for the original variable.
Memory address of reference variable and original variable is same (point 1 only)
int var = 4; int &ref = var; int *ptr1,*ptr2; ptr1 = &var; ptr2 = &ref; cout << ptr1 << endl; cout << ptr2 << endl; // both cout statements print the same thing only
When (&) operator used on right side of equal to (=) works as address-of-operator and when used on left side works as reference operator.
References should always be initialized.
int &ref1 = var; //OK! int &ref2; //NOT OK!
References cannot be reinitialized.
int var1 = 2,var2 = 4; int &ref = var1; //OK! ref = var2; //NOT OK!
Calling Functions with References
#include <iostream> using namespace std; void swap(int &a, int &b) //function to swap two numbers { int tmp; tmp = a; a = b; b = tmp; } int main() { int p = 3,q = 4; cout << p << “ ” << q << endl; //before swapping swap(p,q); cout << p << “ ” << q << endl; //after swapping return 0; }
In the above function ‘a’ and ‘b’ are aliases (references) to ‘p’ and ‘q’ respectively. So this means values of ‘a’ and ‘b’ are not copied to ‘p’ and ‘q’ rather any changes made to the latter reflect to the former. That’s why it is called call by reference.
Output of the above program is
3 4 4 3
Values are swapped!
Note: Calling functions with pointers also give us the same results, these are two different methods of achieving the same result.
Returning references from functions
double& maxEle(double &x, double &y) { if (x > y) return x; else return y; }
The above function accepts two references and returns a reference, not a value but a reference. It returns the reference of ‘x’ or ‘y’ depending on which is greater. | https://boostlog.io/@sophia91/references-in-c-5a9e593fe922f1008c7efa98 | CC-MAIN-2019-30 | refinedweb | 410 | 70.02 |
Unlike the other resource formats, where the resource identifier is the same as the value listed in the *.rc file, string resources are packaged in "bundles". There is a rather terse description of this in Knowledge Base article Q196774. Today we're going to expand that terse description into actual code.:
- You can't pass a language ID. If your resources are multilingual, you can't load strings from a nondefault language.
- You can't query the length of a resource string..
Exercise: Discuss how the /n flag to rc.exe affects these functions.
It would be nicer to return a std::wstring from AllocStringFromResource(), so you don’t have to use delete[] at all.
The VC6 resource compiler doesn’t like strings with more than 256 characters, and will truncate those that are and give you a warning. This can be annoying if you’re doing verbose UI labels, such as a wizard page.
Is this a restriction of the way Win32 expects resource strings to be stored, or is rc.exe just dim?
(Great blog by the way… I’ve just read through your archive and have fallen into at least half the traps you warn about!)
Doesn’t AllocStringFromResourceEx suffer from the integer overflow problems you’ve been talking about recently?
Windows CE’s LoadString() resource API has a nice "underdocumented" feature to use resource strings without allocating extra memory or copying strings. According to Douglas Boling’s book "Programming Microsoft Windows CE", if you pass a NULL lpBuffer parameter to LoadString(), the API will return a read-only pointer to the string. Since the resource strings are not null-terminated, the string length is stored in the word preceeding the start of the resource string.
The book also says you can request that resource strings be stored as null-terminated strings if you invoke the resource compiler with the -r command line switch. I don’t know if that feature is Windows CE specific.
One of my favorite tricks for loading strings is to use the little-known CString (MFC or WTL) constructor trick:
CString str ((LPCTSTR) IDS_SOME_STRING);
Then you can make a macro to do that on the fly:
#define _S(id) (CString(LPCTSTR(id)))
and use it inline, such as:
MessageBox ( _S(IDS_BAD_ERROR), _S(IDS_MSGBOX_TITLE), MB_ICONERROR );
Of course, the _S definition above is only for release mode. In debug mode, it’s a real function that does a LoadString and asserts if the string can’t be loaded.
The Old New Thing talks about format of string resources (Windows)….
Since the EXE is always mapped into memory, if they designed the format so that strings are always terminated with a zero, can’t you can get read-only pointers to the strings without the need to allocate memory ?
Dan: No, it doesn’t. Because the size is coming from a short (0 – 65535), that gets cast to a UINT (0 – 2^32-1), and then has 1 added. There’s no way to overflow the allocator because 2 * 65536 < 2^32 – 1.
BY, you would think so, but maybe Microsoft wanted to save the "wasted" space of the null-terminator character? I bet 90% of the time, resource strings are used without modification. Microsoft should have optimized this common case with an API that just returned an easy to use, zero-copy, read-only pointer to the null-terminated resource string.
runtime – remember that when these APIs were designed and written, they had to work on machines with 4 MB of RAM (the lowest Win95 would run in). That’s four MEGAbytes. Lots of null bytes hanging around can add up if there are a lot of strings in the string table.
Sure, now we don’t give it a second thought when a .NET app requires a 20MB download and uses 40MB of memory (that’s what SharpReader is at right now on my system). In 1993/94/95, things were a *lot* different.
Frederick: There was a discussion of std::wstring in previous blog comments:
I wrote these functions as if they were part of the Platform SDK. This means no language-specific constructs, and certainly no compiler-specific constructs. (std::wstring is not guaranteed to be compatible from one compiler to the next or even from one compiler VERSION to the next. The contract for std::wstring is at the source code level, not the ABI.)
B.Y.: Try solving the exercise.
runtime/Mike Dunn: I actually have a discussion of the historical basis for resource formats scheduled for a future entry. It’s even weirder than you think.
new is a language specific construct. And a non-throwing new is a compiler-specific construct (or a standards compliant compiler with exceptions disabled via a flag).
Using /n it looks like the string length gets reported 1 WCHAR longer than it actually is.
Note: there’s a bug in the for loop in FindStringResourceEx(), the condition should be "i < (uId & 15)"
Raymond, I noticed that FindStringResourceEx() returns a pointer to the block of memory occupied by the resource, but you call UnlockResource() and FreeResource(), which presumably might free that memory. Is this safe?
OTOH, the docs on LockResource() say: "The pointer returned by LockResource is valid until the module containing the resource is unloaded." That implies that UnlockResource/FreeResource can’t free the memory because it would break LockResource(). So who’s right?
As for the exercise, adding /n doesn’t break your functions, it just makes them allocate one extra WCHAR. When the strings are 0-terminated, the lengths are increased as well, so the code to walk the strings and find a particular one still works.
The code assumes string table entries are not 0-terminated. They become 0-terminated with /n, so the string returned by AllocStringFromResourceEx() has two 0 chars at the end. Mostly harmless.
Yeah, I broke my own rule with new[]; I should have used LocalAlloc.
Good catch on the precedence bug.
UnlockResource and FreeResource are NOPs on Win32. More information to come in that promised future blog entry.
How is the landId used?
I couldn’t find a good reference to that
on my MSDN CD via FindResourceEx?
Like the documentation says, it specifies the language of the resource you want to access. You can use the LANGUAGE directive in the *.rc file to provide resources in multiple languages.
The best solution might be to introduce a new function ReleaseStringFromResource that would take the pointer from AllocStringFromResourceEx and free it properly, with delete[] or whatever.
That way, you also reserve the right to change the allocation mechanism without breaking backwards compatibility.
UnlockResource is a total no-op in the current SDK headers – it’s a macro which evaluates the argument, then discards the result.
LockResource is a slightly more substantial no-op, because it’s implemented as a function. However, the implementation is basically:
PVOID LockResource(HGLOBAL hGlob)
{
return (PVOID) hGlob;
}
(dumpbin /disasm is your friend…)
I have a question about the MAKELANGID macro (actually about langids in general). What is the difference between (LANG_NEUTRAL, SUBLANG_NEUTRAL) and (LANG_NEUTRAL, SUBLANG_DEFAULT)? Will the first map to the second if there are resources present in the user’s default language? Is there an algorithm for falling back from the user’s language to other languges in the resource file? I guess I’m just not sure how all this stuff is really handled and would like to know more (trying to do internationalization the right way if at all possible). Even a pointer to a resource would help greatly in clearing up the confusion in my head over how NEUTRAL,NEUTRAL contrasts with NEUTRAL,DEFAULT. Thanks for the great blog.
Go Pats!!!
Lonnie: I’m going to have to defer on your question. I am not an internationalization expert and I wouldn’t want to give the wrong answer.
Lonnie:
(LANG_NEUTRAL, SUBLANG_NEUTRAL) = Language Neutral
(LANG_NEUTRAL, SUBLANG_DEFAULT) = User’s Default Language
A language neutral string is different from one in a user’s default language.
You can mark a resource as Language Neutral by using "LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL" in the resource file.
I’d imagine you’d want to make a distinction between Language Neutral and the Default Language of your application tho. For example, you might want to default to American English if you don’t have resources for the user’s prefered language, but you might want to check the system’s default language first. You’d want to use Language for resources that are truly Language Neutral (so, probably never, as I’d doubt such a thing exists)
[The MSDN reference for MAKELANGID is:]
Examples of language-neutral resources would be most icons and bitmaps. These are things that don’t change regardless of the language. (Of course you have to make sure your icon/bitmap doesn’t contain locale-sensitive imagery.)
Raymond Chen: "Examples of language-neutral resources would be most icons and bitmaps. These are things that don’t change regardless of the language."
I’d have to disagree here. Although you cannot translate images in the same way as text resources, there are still potential language specific facets. Just think about bitmaps with text on them. With this being an exception that is easily perceived there are also less obvious nuances: a green coloured UI element would signal a successful operation to those living in western civilizations — if your product ships to asian countries you would rather change this colour to red.
.f
p.s.: Thanks a lot for sharing your experience. I stumbled across your blog today, almost by accident, and I like it already :)
True, bitmaps with text and culturally-dependnet images would need to be localized. But I ruled that out in my parenthetical.
It’s a good idea to avoid locale-sensitive bitmaps because professional translators tend not also to be accomplished graphic artists.
Don’t get me wrong, I wasn’t going to challange you in any way. I merely meant to illustrate that it isn’t always as easy as it may appear to decide whether a resource is language-dependent. I would agree with you, that locale-dependent images are generally a bad idea, unless you have tool-support to track those as well as good reasons to go for that approach in the first place.
I just didn’t want anyone reading this thread take it as a fact that images are generally locale-independent. With that said, I also have a not so obvious string resource that is in fact language-independent: let’s say you are writing an image processing application and need to support CMY color space — if you translate Cyan-Magenta-Yellow into local names, you will run into major trouble when it comes to printing your work.
Anyway, I’m not an expert in this field either. But with all those bits and pieces I picked up along the way the only thing I can say is this: localization is a beast to master.
.f
Agreed. Designing your code to be localizable is a lot of work and contains many pitfalls.
Commenting on this entry has been closed.
Um eine WIN32-Applikation in mehreren Sprachversionen zu lokalisieren,
gibt es neben den lokalisierten Forms auch die String tables, die sich in den Programmresourcen befinden.
Wenn man sein Programm also mehrsprachig gestalten will, sind alle hardcoi
The SZ (a.k.a. Steffen) asked in the suggestion box:
What is the prefered way to select the "most…
No really, you can’t.
Serdar asked: Hi, Is it possible to call GetLocaleInfo in a different language? What I’m trying to do
PingBack from | https://blogs.msdn.microsoft.com/oldnewthing/20040130-00/?p=40813 | CC-MAIN-2017-47 | refinedweb | 1,941 | 62.88 |
!
Now *that's* an obscure reference in the title!
Timothy Fries,
[sarcasm] I just looooove how I have to set the title in the code behind. It's so pretty [/sarcasm].
I know there's other (hokey) ways to get around that, but I truly wish we had proper x:Static support in Silverlight. (btw this goes for Silverlight too).
mORTEN,
Agreed – x:Static sure would be nice.
Very nice and detailed explanation! Thank you. Haven't thought of using the source code to localize the toggleSwitch. I just used svn to check it out. This way the toolkit will stay up to date automatically.
Beave,
Cool idea – you'll get merges and conflict resolution for free that way!
"… building applications that can be easily translated to other languages [is] easy …"
Really? :o)
search.cpan.org/…/TPJ13.pod
"It is more complicated than you think."
– The Eighth Networking Truth, from RFC 1925
RichardDeeming,
Okay, so maybe I exaggerated a little.
Though if you want to split hairs for a moment, I said only that building applications which *could* be translated was easy – I didn't say that the translation *itself* would be easy, too!
Thanks for the article – that's great stuff!
Hey, I have localised the date picker in the suggested method. And it works brilliantly! Thank you :).
The hitch I face now is that, im need to render charts in my app. For that I use a 3rd party tool called visiblox.…/visiblox-for-wp7-basic-charts-selection-and-zooming
Now for visiblox to work need both the toolkit dll and the visibox dll. But when i try to run i get the error called
"Error HRESULT E_FAIL has been returned from a call to a COM component."
Somehow i figured that its the toolkit reference. So i remove the project toolkit reference from my project and add the the other toolkit,dll we get under there .NET tab in the Add Reference dialog box. Now the project runs fine. But i dont get the localisation. So what is the difference between the dll tht we get by building the toolkit project and the other dll? There should be some difference right, else it would have worked.
Alfa,
My guess is that something about the Visiblox assembly is conflicting with the Toolkit one. I've never used the Visiblox stuff, so I don't know off the top of my head what it would be. However, it looks like you posted this question to StackOverflow as well (stackoverflow.com/…/graphing-tools-for-windows-phone-visiblox-error) and someone there seems to think the Visiblox assemblies reference a conflicting version of the Toolkit assemblies? If so, that could explain this problem. If not, you might look at whether there are any conflicting assembly names, XML namespace prefixes, or class names – any of those feel like they could lead to problems like this.
Hope this helps! | https://blogs.msdn.microsoft.com/delay/2010/12/20/and-shed-say-can-you-see-what-im-saying-how-to-localize-a-windows-phone-7-application-that-uses-the-windows-phone-toolkit-into-different-languages/ | CC-MAIN-2016-07 | refinedweb | 486 | 75.61 |
XML Questions Answered
XML.com receives dozens of questions each week about XML, submitted via the FAQ submission form at. In this column we'll be addressing some of the most interesting (read: useful, provocative, outright bizarre) of those questions.
HTML to XML?
Q: How do I convert my existing HTML documents into XML?
A: The most straightforward solution is to use Dave Raggett's popular program, HTML Tidy (or plain old "Tidy"), available from the W3C web site at.,
<?xml version="1.0"?>, and a
<!DOCTYPE...>
<p> and
<.
"Markup"? Say what?
Q: What exactly do you mean by "markup"? Can you please explain using a simple example?
A: Markup is all the text in an XML, HTML, or SGML document other than what you might normally think of as the document's content. Pieces of markup punctuate the content, as it were -- add meaning or structure to what the document otherwise says. For example, consider an XML document whose content includes nominally just a single sentence: "Bolivia exports tin to Curaçao."
In marked-up form, this document might look like the following:
<?xml version="1.0"?> <!DOCTYPE para> <!-- What does Bolivia export, and whither? --> <para xml:Bolivia exports tin to Curaçao.</para>
All text beyond that of our original simple
sentence (or in place of, in the
case of "
ç") is markup. Here, the markup declares that the document
conforms to the XML 1.0 Recommendation, and that its actual content
will be contained wholly within the scope of an element named
"para"; provides a human-readable comment; marks the starting point
of the document content; declares that, unless otherwise stated, the
language of this document is English; provides a "portable"
reference to a special character, ç, which might not
otherwise be understood the same way by all XML processing
software, in all environments; and marks the conclusion of the
document content.
The Dark Side
Q: Are there any weaknesses of XML?
A: Oh, yes. There are any number of reasons why you might not choose XML over some other data representation format. (Interestingly, some of these "weaknesses" are a result of intentional design decisions. In other words, as certain software vendors are wont to claim, "That's not a bug. That's a feature.") Here are a handful of them:
XML markup can be incredibly verbose, depending on the vocabulary in question. For instance, what HTML refers to as the
pelement might show up in an XML counterpart as
paraor
paragraph. (Things can get even worse if the element and attribute names include namespace prefixes.) This can make the markup much more accessible to human readers; unfortunately, it also can make the actual content much harder to read and even (if the markup is done "by hand") much harder to mark up in the first place. Then there's the bandwidth question: How much of your wire are you willing to dedicate to carrying markup, as opposed to true content?
XML is platform-neutral. On the face of it, this is laudable. It also diminishes how much performance can be wrung out of a true-blue XML application (since you can't take advantage of platform-specific tricks like compression and other binary formats). Furthermore, fully supporting any Unicode encoding probably adds all kinds of cruft to an application that may be used seldom, if ever, in a given installation of XML processing software.
All the pieces aren't yet in place to do whatever you want with XML--certainly not in a fully standards-compliant form, anyhow. We've got XSLT for transforming the structure of XML documents, but XSL itself--the formatting component, what most people think of when they hear the word "stylesheet"--still hasn't been finalized. We've got XPath for telling us how to get around within an XML document, but we're still waiting for a final XLink to tell us how to get to a document in the first place. DTDs enable us to do some rudimentary sorts of validity checking; but it will take the still-unfinished XSchema to bring XML onto anything like a par with the built-in type checking familiar to database developers. The list goes on... and every day, it seems, a new version of a new standard is announced. (If you're looking for software to support it all, well, you've got a long wait ahead of you!)
And last but certainly not least:
- Many people's expectations are too high, not just for XML but for any heavily-marketed technology du jour. If your boss has read that XML (or whatever) will cure world hunger, it will do you no good to know otherwise. And, needless to say, the world's hungry will be just as underfed as ever. | http://www.xml.com/pub/a/2000/07/26/qanda/index.html | crawl-003 | refinedweb | 797 | 61.56 |
*usr_06.txt* For Vim version 7.4. Last change: 2009 Oct 28 VIM USER MANUAL - by Bram Moolenaar Using syntax highlighting Black and white text is boring. With colors your file comes to life. This not only looks nice, it also speeds up your work. Change the colors used for the different sorts of text. Print your text, with the colors you see on the screen. |06.1| Switching it on |06.2| No or wrong colors? |06.3| Different colors |06.4| With colors or without colors |06.5| Printing with colors |06.6| Further reading Next chapter: |usr_07.txt| Editing more than one file Previous chapter: |usr_05.txt| Set your settings Table of contents: |usr_toc.txt| ============================================================================== *06.1* Switching it on It all starts with one simple command: :syntax enable That should work in most situations to get color in your files. Vim will automagically detect the type of file and load the right syntax highlighting. Suddenly comments are blue, keywords brown and strings red. This makes it easy to overview the file. After a while you will find that black&white text slows you down! If you always want to use syntax highlighting, put the ":syntax enable" command in your |vimrc| file. If you want syntax highlighting only when the terminal supports colors, you can put this in your |vimrc| file: if &t_Co > 1 syntax enable endif If you want syntax highlighting only in the GUI version, put the ":syntax enable" command in your |gvimrc| file. ============================================================================== *06.2* No or wrong colors? There can be a number of reasons why you don't see colors: - Your terminal does not support colors. Vim will use bold, italic and underlined text, but this doesn't look very nice. You probably will want to try to get a terminal with colors. For Unix, I recommend the xterm from the XFree86 project: |xfree-xterm|. - Your terminal does support colors, but Vim doesn't know this. Make sure your $TERM setting is correct. For example, when using an xterm that supports colors: setenv TERM xterm-color or (depending on your shell): TERM=xterm-color; export TERM The terminal name must match the terminal you are using. If it still doesn't work, have a look at |xterm-color|, which shows a few ways to make Vim display colors (not only for an xterm). - The file type is not recognized. Vim doesn't know all file types, and sometimes it's near to impossible to tell what language a file uses. Try this command: :set filetype If the result is "filetype=" then the problem is indeed that Vim doesn't know what type of file this is. You can set the type manually: :set filetype=fortran To see which types are available, look in the directory $VIMRUNTIME/syntax. For the GUI you can use the Syntax menu. Setting the filetype can also be done with a |modeline|, so that the file will be highlighted each time you edit it. For example, this line can be used in a Makefile (put it near the start or end of the file): # vim: syntax=make You might know how to detect the file type yourself. Often the file name extension (after the dot) can be used. See |new-filetype| for how to tell Vim to detect that file type. - There is no highlighting for your file type. You could try using a similar file type by manually setting it as mentioned above. If that isn't good enough, you can write your own syntax file, see |mysyntaxfile|. Or the colors could be wrong: - The colored text is very hard to read. Vim guesses the background color that you are using. If it is black (or another dark color) it will use light colors for text. If it is white (or another light color) it will use dark colors for text. If Vim guessed wrong the text will be hard to read. To solve this, set the 'background' option. For a dark background: :set background=dark And for a light background: :set background=light Make sure you put this _before_ the ":syntax enable" command, otherwise the colors will already have been set. You could do ":syntax reset" after setting 'background' to make Vim set the default colors again. - The colors are wrong when scrolling bottom to top. Vim doesn't read the whole file to parse the text. It starts parsing wherever you are viewing the file. That saves a lot of time, but sometimes the colors are wrong. A simple fix is hitting CTRL-L. Or scroll back a bit and then forward again. For a real fix, see |:syn-sync|. Some syntax files have a way to make it look further back, see the help for the specific syntax file. For example, |tex.vim| for the TeX syntax. ============================================================================== *06.3* Different colors *:syn-default-override* If you don't like the default colors, you can select another color scheme. In the GUI use the Edit/Color Scheme menu. You can also type the command: :colorscheme evening "evening" is the name of the color scheme. There are several others you might want to try out. Look in the directory $VIMRUNTIME/colors. When you found the color scheme that you like, add the ":colorscheme" command to your |vimrc| file. You could also write your own color scheme. This is how you do it: 1. Select a color scheme that comes close. Copy this file to your own Vim directory. For Unix, this should work: !mkdir ~/.vim/colors !cp $VIMRUNTIME/colors/morning.vim ~/.vim/colors/mine.vim This is done from Vim, because it knows the value of $VIMRUNTIME. 2. Edit the color scheme file. These entries are useful: term attributes in a B&W terminal cterm attributes in a color terminal ctermfg foreground color in a color terminal ctermbg background color in a color terminal gui attributes in the GUI guifg foreground color in the GUI guibg background color in the GUI For example, to make comments green: :highlight Comment ctermfg=green guifg=green Attributes you can use for "cterm" and "gui" are "bold" and "underline". If you want both, use "bold,underline". For details see the |:highlight| command. 3. Tell Vim to always use your color scheme. Put this line in your YXXYvimrc|: colorscheme mine If you want to see what the most often used color combinations look like, use this command: :runtime syntax/colortest.vim You will see text in various color combinations. You can check which ones are readable and look nice. ============================================================================== *06.4* With colors or without colors Displaying text in color takes a lot of effort. If you find the displaying too slow, you might want to disable syntax highlighting for a moment: :syntax clear When editing another file (or the same one) the colors will come back. *:syn-off* If you want to stop highlighting completely use: :syntax off This will completely disable syntax highlighting and remove it immediately for all buffers. *:syn-manual* If you want syntax highlighting only for specific files, use this: :syntax manual This will enable the syntax highlighting, but not switch it on automatically when starting to edit a buffer. To switch highlighting on for the current buffer, set the 'syntax' option: :set syntax=ON ============================================================================== *06.5* Printing with colors *syntax-printing* In the MS-Windows version you can print the current file with this command: :hardcopy You will get the usual printer dialog, where you can select the printer and a few settings. If you have a color printer, the paper output should look the same as what you see inside Vim. But when you use a dark background the colors will be adjusted to look good on white paper. There are several options that change the way Vim prints: 'printdevice' 'printheader' 'printfont' 'printoptions' To print only a range of lines, use Visual mode to select the lines and then type the command: v100j:hardcopy "v" starts Visual mode. "100j" moves a hundred lines down, they will be highlighted. Then ":hardcopy" will print those lines. You can use other commands to move in Visual mode, of course. This also works on Unix, if you have a PostScript printer. Otherwise, you will have to do a bit more work. You need to convert the text to HTML first, and then print it from a web browser. Convert the current file to HTML with this command: :TOhtml In case that doesn't work: :source $VIMRUNTIME/syntax/2html.vim You will see it crunching away, this can take quite a while for a large file. Some time later another window shows the HTML code. Now write this somewhere (doesn't matter where, you throw it away later): :write main.c.html Open this file in your favorite browser and print it from there. If all goes well, the output should look exactly as it does in Vim. See |2html.vim| for details. Don't forget to delete the HTML file when you are done with it. Instead of printing, you could also put the HTML file on a web server, and let others look at the colored text. ============================================================================== *06.6* Further reading |usr_44.txt| Your own syntax highlighted. |syntax| All the details. ============================================================================== Next chapter: |usr_07.txt| Editing more than one file Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl: top - main help file | http://fossies.org/linux/misc/vim74html.zip:a/usr_06.html | CC-MAIN-2014-15 | refinedweb | 1,559 | 74.69 |
Netbooks have a small screen size. Following are some tips to help with a smaller viewing area, and a little less mouse usage.
Because of the small screen size, simply reducing the size and number of the toolbars and size of icons will not be sufficient.
Firefox uses "F11" to toggle.
Change the vertical scrolling to scroll up or down a full screen at a time with a change to your about:config entries. Change the value to 1 for mousewheel.withnokey.action
You also have available the Space Bar, Page Up, Page Dn keys to scroll a page at a time. You can use the shift key with the Space Bar to scroll up a page at a time. Smaller scrolling can be done with the arrow keys, or using/modifying other mousewheel configuration settings.
The Home key will take you to the top of the page, and the End key will take you to the bottom of the page.
If scrolling with the keyboard is not working then make sure that you have not enabled caret browsing mode with the F7 toggle [3]. If you are typing numbers instead of some of the above then switch off NumLock key (should have an indicator light).
Placing the cursor above or below the scroller thumb will move up or down one page. Placing the cursor at a position on the scrollbar and holding the left mouse button will move the scroller thumb and the view to the indicated position.
You can test your scrolling by watching the line numbers on the right side
of this test web page.
With the toolbars hidden two very useful Keyboard Shortcuts are "Ctrl+L" to place you into the Location Bar, and "Ctrl+K" to get you into the Search Bar.
Bookmarking with Ctrl+D may save dragging items clear across the screen, or clicking on the bookmark star.
Use of the Tab key (and "Shift+Tab") to move mouse to a link or entry point such as within a Form may save some mouse activity.
The use of Keyword Shortcuts can be a big time saver by working from the location bar to do searching, and to invoke bookmarks and bookmarklets.
If typing.
To make temporary changes to the font-size for a domain during your session use Ctrl++ to increase size, Ctrl+- to decrease size, or Ctrl+0 to restore normal size. The use of the
"Mouse Zoom" and "Image Zoom" extensions are also useful when using an external mouse.
To make permanent changes to your default font-size which will have no effect on pages where the web author chooses fonts and font-size for you is at Tools → Options → Content → (Fonts and Colors). You might also check Accessibility features of Firefox or of your operating system for additional changes.
Use small icons on toolbars: View -> Toolbars -> Customize, then at the bottom choose small icons.
While full screen mode is probably your most useful method of viewing web pages on a netbook there are additional changes that you can make. Some styling suggestions: Eliminate the folder and file icons to fit more folders and bookmarks on the Bookmarks Toolbar. Reduce the minimum width of the tabs to fit more tabs on the tabs bar. Reduce the height of toolbars and the spacing between toolbar buttons.
Some Netbooks may be short of resources or intended for limited usage. You can make styling changes directly into userChrome.css and possibly avoid the need for some extensions such as "Auto Hide", "Stylish" and "Stylish Custom", but you would not be able to turn features on and off through an extension's options and would have to restart Firefox to test changes or to turn them on or off.
The following code can be implemented directly in userChrome.css to Always show the tabs bar even in Full Screen Mode (F11).
@namespace url();
/* Always show the tabs bar -- see */
@-moz-document url(chrome://browser/content/browser.xul) {
#content > tabbox .tabbrowser-strip{visibility: visible !important; } }) | http://kb.mozillazine.org/Netbooks | CC-MAIN-2017-47 | refinedweb | 669 | 69.62 |
when one value matches the value of the variable, the computer continues executing the program from that point. C switch statement is a multiway decisions that tests whether a variable or expression matches one of a number of constant integer values, and branches accordingly.
Syntax of switch statement:
switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}
The condition of a switch statement is a value... Switch statements serves as a simple way to write long if statements when the requirements are met. Often it can be used to process input from a user.
Flowchart :
Some of the points to keep in mind while using switch statement are :
- In C switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value, which is returned by expression, must be an integer value otherwise the compiler will issue an error message.
- The case constant expression must be a constant integer value.
- You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
- When a break statement is executed, it causes an immediate exit from the switch. The control pass to the statement following the closing brace for the switch. Although as mentioned the break statement is not mandatory but it is sound to use this break statement.
- The defaut statement is the default choice of the switch statement if all case statements are not satisfied with the expression. The break after the default statements is not necessary unless you put another case statement below it.
Program to illustrate use of switch statement:
#include <stdio.h> #include<conio.h> main() { int marks=100; switch(marks) { case 100 : { printf( "Excellent\n" ); break; } case 90 : { printf( "Very Good\n" ); break; } case 80 : { printf( "Good" ); break; } default : printf( "Work hard\n" ); } }
Output will be:
Excellent | http://csetips.catchupdates.com/switch-statement/ | CC-MAIN-2017-22 | refinedweb | 341 | 61.46 |
How can I use differential evolution to find the maximum values of the function function f(x) = -x(x+1) from -500 to 500? I need this for a chess program I am making, I have begun researching on Differential Evolution and am still finding it quite difficult to understand, let alone use for a program. Can anyone please help me by introducing me to the algorithm in a simple way and possibly giving some example pseudo-code for such a program?
First, of all, sorry for the late reply.
I bet that you won't know the derivatives of the function that you'll be trying to max, that's why you want to use the Differential Evolution algorithm and not something like the Newton-Raphson method.
I found a great link that explains Differential Evolution in a straightforward manner:.
On the first page, there is a section with an explanation of the algorithm:
Let each generation of points consist of n points, with j terms in each.
Initialize an array with size
j. Add a number
j of distinct random x values from
-500 to 500, the interval you are considering right now. Ideally, you would know around where the maximum value would be, and you would make it more probable for your
x values to be there.
For each j, randomly select two points yj,1 and yj,2 uniformly from the set of points x (m) . Construct a candidate point cj = x (m) j + α(yj,1 − yj,2). Basically the two y values involve picking a random direction and distance, and the candidate is found by adding that random direction and distance (scaled by α) to the current value.
Hmmm... This is a bit more complicated. Iterate through the array you made in the last step. For each
x value, pick two random indexes (
yj1 and
yj2). Construct a candidate
x value with
cx = α(yj1 − yj2), where you choose your
α. You can try experimenting with different values of alpha.
Check to see which one is larger, the candidate value or the x value at
j. If the candidate value is larger, replace it for the
x value at
j.
Do this all until all of the values in the array are more or less similar. Tahdah, any of the values of the array will be the maximum value. Just to reduce randomness (or maybe this is not important....), average them all together.
The more stringent you make the
about method, the better approximations you will get, but the more time it will take.
For example, instead of
Math.abs(a - b) <= alpha /10, I would do
Math.abs(a - b) <= alpha /10000 to get a better approximation.
You will get a good approximation of the value that you want.
Happy coding!
Code I wrote for this response:
public class DifferentialEvolution { public static final double alpha = 0.001; public static double evaluate(double x) { return -x*(x+1); } public static double max(int N) { // N is initial array size. double[] xs = new double[N]; for(int j = 0; j < N; j++) { xs[j] = Math.random()*1000.0 - 500.0; // Number from -500 to 500. } boolean done = false; while(!done) { for(int j = 0; j < N; j++) { double yj1 = xs[(int)(Math.random()*N)]; // This might include xs[j], but that shouldn't be a problem. double yj2 = xs[(int)(Math.random()*N)]; // It will only slow things down a bit. double cj = xs[j] + alpha*(yj1-yj2); if(evaluate(cj) > evaluate(xs[j])) { xs[j] = cj; } } double average = average(xs); // Edited done = true; for(int j = 0; j < N; j++) { // Edited if(!about(xs[j], average)) { // Edited done = false; break; } } } return average(xs); } public static double average(double[] values) { double sum = 0; for(int i = 0; i < values.length; i++) { sum += values[i]; } return sum/values.length; } public static boolean about(double a, double b) { if(Math.abs(a - b) <= alpha /10000) { // This should work. return true; } return false; } public static void main(String[] args) { long t = System.currentTimeMillis(); System.out.println(max(3)); System.out.println("Time (Milliseconds): " + (System.currentTimeMillis() - t)); }
}
If you have any questions after reading this, feel free to ask them in the comments. I'll do my best to help. | https://codedump.io/share/pmiKQ1LjwS1T/1/function-values-using-differential-evolution | CC-MAIN-2017-13 | refinedweb | 711 | 66.23 |
Package: debian-cd Version: 3.0.2 Severity: serious Tags: patch I'm classifying this as serious as this makes the Release file invalid and thus breaks the CD image. I found this bug because debootstrap threw an error during an installation that Packages.gz was invalid. The install did continue, probably because Packages was valid, but the red error screen is still extremely disturbing. I maybe worth fixing this for Etch as well. The problem is in the function md5_files_for_release in tools/make_disc_trees.pl where it recompresses the Packages file, overwriting an existing Packages.gz file. This function is called with a list of files from a 'find'. These files are processed one-by-one, but apparently the order is not fixed. If the order of the files is Packages-Packages.gz, then all is well: first Packages is gzipped again and next the md5sum for the new Packages.gz is determined. If the order of the files is Packages.gz-Packages, then first the md5sum for Packages.gz is determined but after that it gets overwritten by the recompression of Packages (with even a much higher compression rate), which explains the discrepancy of the md5sum and file size between the Packages.gz file and its listing in the Release file. That the order is reversed is shown by how they appear in the Release file: in my case the .gz file is listed above the regular one. The attached patch fixes the issue by splitting out the recompression into a separate function. Cheers, FJP
Index: tools/make_disc_trees.pl =================================================================== --- tools/make_disc_trees.pl (revision 1412) +++ tools/make_disc_trees.pl (working copy) @@ -350,17 +350,23 @@ return ($md5, $st->size); } -sub md5_files_for_release { - my ($md5, $size, $filename); +sub recompress { + # Recompress the Packages and Sources files; workaround for bug + # #402482 + my ($filename); $filename = $File::Find::name; - # Recompress the Packages and Sources files; workaround for bug - # #402482 if ($filename =~ m/\/.*\/(Packages|Sources)$/o) { system("gzip -9c < $_ >$_.gz"); } +} +sub md5_files_for_release { + my ($md5, $size, $filename); + + $filename = $File::Find::name; + if ($filename =~ m/\/.*\/(Packages|Sources|Release)/o) { $filename =~ s/^\.\///g; ($md5, $size) = md5_file($_); @@ -521,6 +527,7 @@ chdir "dists/$codename"; open(RELEASE, ">>Release") || die "Failed to open Release file: $!\n"; print RELEASE "MD5Sum:\n"; + find (\&recompress, "."); find (\&md5_files_for_release, "."); close(RELEASE); chdir("../..");
Attachment:
pgpFxp2IrsQo2.pgp
Description: PGP signature | https://lists.debian.org/debian-cd/2007/05/msg00034.html | CC-MAIN-2020-45 | refinedweb | 382 | 59.8 |
I PattiChati
I.
You would be better served if you posted to Yahoo forums :
Yahoo Mail
yahoo mail - Tech Support Forums - TechIMO.com
The "new improved" Yahoo Mail isn't. In fact, it's vexing, mortifyingly slow, and no longer allows open folders while creating new messages so you can't copy and paste with both items open. Since Yahoo won't permit going back to the old, reliable version. So, I'm seriously considering a switch to Mozilla's Thunderbird v 24.0.1 on my Win7-64 desktop and my wife's Win7-64 laptop. She uses the paid version of Yahoo and I'm on the free version.
Once I get Thunderbird going, does anyone know how I can:
get mail addressed to me at Yahoo forwarded to me in Thunderbird?
import my Yahoo contacts into Thunderbird?
import my Yahoo folders and their contacts into Thunderbird?
I'm not a techie, so I'd greatly appreciate learning how I can go about this. Thanks in advance.
See if any of these will help.
Messenger Help | - SLN3286 - Access Yahoo Mail using Mozilla Thunderbird
Get Your Yahoo! Mail in Mozilla Thunderbird for Free
Jerry
Logfile of Trend Micro HijackThis v BETA Scan saved at PM on Platform Windows XP SP WinNT Boot mode Normal log. Firefox(only mail, browser yahoo, yahoo not read used) load will Please facebook Microsoft Shared Ink KeyboardSurrogate exe C WINDOWS system spoolsv WINDOWS system cisvc exe C WINDOWS System nvsvc exe C Program Files Analog Devices SoundMAX SMAgent exe C Program Files Viewpoint Common ViewpointService exe C Program Files Viewpoint Viewpoint Manager ViewMgr exe C WINDOWS SYSTEM WISPTIS EXE C WINDOWS System tabbtnu exe C WINDOWS Explorer EXE C WINDOWS system ctfmon exe C Program Files Common Files Microsoft Shared Ink TCServer exe C Program Files HPQ Q Menu QICON EXE C Program Files HPQ Q Menu CpqMcSrV exe C Program Files Roxio Easy CD Creator DirectCD DirectCD exe C PROGRA Grisoft AVG avgcc exe C Program Files iTunes iTunesHelper exe C Program Files Google GoogleToolbarNotifier GoogleToolbarNotifier exe C Program Files AIM aim Please read log. Firefox(only browser used) will not load yahoo, yahoo mail, facebook exe C Program Files ScanSoft NaturallySpeaking Program natspeak exe C Program Files MemTurbo MemTurbo exe C Program Files Stardock ObjectDock ObjectDock exe C Program Files Yahoo Widgets YahooWidgetEngine exe C Program Files Common Files AOL Loader aolload exe C Program Files iPod bin iPodService AIM aolsoftware exe C WINDOWS system cidaemon exe C Program Files Mozilla Firefox firefox exe C Documents and Settings ATRC Staff Desktop HiJackThis v exe R - HKCU Please read log. Firefox(only browser used) will not load yahoo, yahoo mail, facebook Software Microsoft Internet Explorer Main Search Bar http websearch drsnsrch com sidese amp id R - HKCU Software Microsoft Internet Explorer Main Please read log. Firefox(only browser used) will not load yahoo, yahoo mail, facebook Search Page http websearch drsnsrch com sidese amp id websearch drsnsrch com sidese amp id R - HKLM Software Microsoft Internet Explorer Main Search Page http websearch drsnsrch com sidese amp id R - HKLM Software Microsoft Internet Explorer Main Start Page http go microsoft com fwlink LinkId R - HKLM Software Microsoft Internet Explorer Search SearchAssistant http websearch drsnsrch com sidese amp id R - HKLM Software Microsoft Internet Explorer Search CustomizeSearch http websearch drsnsrch com sidese amp id R - HKCU Software Microsoft Internet Explorer SearchURL Default websearch shopnav com q cgi q R - HKCU Software Microsoft Internet Explorer Main Start Page bak about blank R - HKCU Software Microsoft Windows CurrentVersion Internet Settings AutoConfigURL R - URLSearchHook AOLTBSearch Class - EA - - DB- F -D CA FB C D - C Program Files AOL AIM Toolbar aoltb dll R - URLSearchHook no name - F C F -AD -F EB- EF -F A C C - no file R - URLSearchHook no name - F F B-B D -EC C-A FC-E BF C - no file R - URLSearchHook no name - C -EAA -BA -D B-BB EB C - no file R - UR... Read more
im not sure the problem with the browser or the connection but im pretty sure there is something wrong with my internet conection i unable to signin my yahoo messenger skype and even cannot load to yahoo mail website but i still yahoo and in mail, cannot login/sign messenger skype yahoo even can surf other website normally i noticed that some of cannot login/sign in yahoo mail, skype and even yahoo messenger the page that required password are unable cannot login/sign in yahoo mail, skype and even yahoo messenger to load the will be an error that ask to check the intrnet conection im using LAN connection i tried to login yahoo mail and signin skype and ym by using my friends pc in my home and i can login singin without any trouble we using the same internet connction i already reformat my laptop cause i thought there is laptop problem but there is still no luck same problem still occur i scaned my lappy with updated antvrus btdefender but no virus detected i also tried unable the firewall in my system but no changed i still face the same problem i realy hope that someone can help me figureout this problem
Try to disable your firewall and your Anti virus.
Good luck:-)
I ve been experiencing an annoying issue when navigating through web browsers such as yahoo google etc When using the search engines I m often re-directed to some random site that looks like it s either mimicking a search engine or selling something If I hit the back button enough and re-click while using Yahoo!/Google browser and Help! My using redirected gets Yahoo!Mail. on the search item a nd time I ll usually get the page I originally wanted However this happens on every search I perform and occurs every time without fail Another issue that may be related occurs when in Yahoo s email service I m often redirected when navitgating in-and-out of email messages I fear my computer is being used in a malicious way and my security compromised None of the anti-virus or spyware tools on my computer have caputerd or identified a problem yet I KNOW one exists Help! My browser gets redirected using Yahoo!/Google and while using Yahoo!Mail. here I have read through a few related posts but it looks like there could be any number of issues causing this so I decided to ask my question directly I would greatly appreciate any assistance anyone can provide me It s truly a service you are providing I m providing the suggested info below Here is the TSG info Tech Support Guy System Info Utility version OS Version Microsoft Windows Home Premium bit Processor Pentium R Dual-Core CPU T GHz Intel Family Model Stepping Processor Count RAM Mb Graphics Card Mobile Intel R Series Express Chipset Family Mb Hard Drives C Total - MB Free - MB Motherboard Dell Inc N J M TJNYM CN C U Antivirus Microsoft Security Essentials Updated and Enabled Here is the HiJackthis logfile Logfile of Trend Micro HijackThis v Scan saved at PM on Platform Windows WinNT MSIE Internet Explorer v Boot mode Normal Running processes C Program Files x Intel Intel R Rapid Storage Technology IAStorIcon exe C Program Files x Dell Webcam Dell Webcam Central WebcamDell exe C Program Files x Roxio Roxio Burn RoxioBurnLauncher exe C Program Files x Dell DataSafe Online DataSafeOnline exe C Program Files x Dell Support Center bin sprtcmd exe C Program Files x Internet Explorer iexplore exe C Program Files x Google Google Toolbar GoogleToolbarUser exe C Program Files x MSN Toolbar Platform mswinext exe C Program Files x Microsoft Search Enhancement Pack SCServer SCServer exe C Program Files x Internet Explorer iexplore exe C Program Files x Internet Explorer iexplore exe C Windows SysWOW Macromed Flash FlashUtil l ActiveX exe C Program Files x Trend Micro HiJackThis HiJackThis exe C Windows SysWOW Dll Search Helper - EBF - F- bff-A F-B E AAC B - C Program Files x Microsoft Search Enhancement Pack Search Helper SEPsearchhelperie dll O - BHO Google Toolbar Helper - AA ED -... Read more
Hi,.
A couple of days ago i noticed that when i log into yahoo.com and enter my username and password the URL automatically goes to us.mg4.mail.yahoo.com. I had entered the proxy address a few times and have read on the web that this is server address. Can someone please let me know if this is normal or should i be concerned because i didn't change any of my yahoo settings. Thanks very much in advance.
Also noticed that when i click the back tab it takes me back to my inbox. This should not happen. Something weird must be going on. Please help.
Mine goes to mg205. I never used any proxies so it looks like a normal Yahoo thing.
My problem is with the latest version of Yahoo Mail. I have recently upgraded to this version and initially messengers for Yahoo and Facebook opened there. But then these are not opening anymore. Whenever i click on the 'New Chat button, i get the message that "Yahoo Messenger is currently loading" or "Yahoo messenger is currently not available".
The biggest problem is that this new version does not allow one to go back to an earlier version. I have another yahoo account also where i luckily did not upgade to the new version. Here yahoo messenger easily opens in Yahoo Mail.
Any solutions?
Shoumitro
Hi and welcome to TSF have you checked with yahoo support to see if it is a known issue Help Central | Help
Been having this issue for a bit now When I go to yahoo com or mail yahoo com I get this screen pictured below Not what you'd normally see Same thing happens whether I'm using IE or Firefox or Can't access mail.yahoo.com...Redirection? yahoo.com When I run an updated Ad-Aware scan it seems to go away for a bit but quickly returns And I'm not visiting any odd sites that would cause this I've run Ad Aware as previously mentioned Spybot Superantispyware Can't access yahoo.com or mail.yahoo.com...Redirection? MalwareByte and used CCleaner I've run Hijackthis and don't see anything odd either I thought I was Can't access yahoo.com or mail.yahoo.com...Redirection? pretty good at removing this on my own but this has me stumped Here's pics Firefox http i photobucket com albums cc m key firefox jpgIE http i photobucket com albums cc mn pikey ie jpgAnd when I click on view -- source in IE on that quot page quot http i photobucket com albums cc mn Can't access yahoo.com or mail.yahoo.com...Redirection? pikey source jpgHere are my logs as required per instructions DDS Ver - - - NTFSx Run by Shawn Oen at on Sun Internet Explorer Microsoft Windows XP Professional GMT - Running Processes C WINDOWS system svchost -k DcomLaunchsvchost exeC WINDOWS System svchost exe -k netsvcsC WINDOWS system svchost exe -k WudfServiceGroupsvchost exesvchost exeC Program Files Lavasoft Ad-Aware aawservice exeC WINDOWS system spoolsv exec program files common files logishrd lvmvfm LVPrcSrv exeC WINDOWS Explorer EXEC Program Files Common Files Apple Mobile Device Support bin AppleMobileDeviceService exeC Program Files Java jre bin jqs exeC Program Files Common Files Nero Nero BackItUp NBService exeC Program Files COMPAQ Easy Access Button Support StartEAK exeC Program Files Analog Devices SoundMAX DrvLsnr exeC Program Files Common Files LogiShrd LComMgr Communications Helper exeC Program Files Adobe Acrobat Distillr Acrotray exeC Program Files iTunes iTunesHelper exeC Program Files Java jre bin jusched exeC WINDOWS system ctfmon exeC Program Files Nokia Nokia PC Suite PCSync exeC Program Files Nokia Nokia PC Suite PCSuite exeC WINDOWS System snmp exeC Program Files Analog Devices SoundMAX SMAgent exeC WINDOWS System svchost exe -k imgsvcC Program Files HP Digital Imaging bin hpqtra exeC Program Files PC Connectivity Solution ServiceLayer exeC Program Files Compaq Easy Access Button Support CPQEADM EXEC Compaq EAKDRV EAUSBKBD EXEC PROGRA Compaq EASYAC BttnServ exeC Program Files iPod bin iPodService exeC Program Files Yahoo Widgets YahooWidgets exeC WINDOWS system wscntfy exeC Program Files HP Digital Imaging bin hpqgalry exeC Program Files PC Connectivity Solution Transports NclUSBSrv exeC Program Files Common Files Nokia MPAPI MPAPI s exeC Program Files Yahoo Widgets YahooWidgets exeC Program Files PC Connectivity Solution Transports NclRSSrv exeC WINDOWS System svchost exe -k HTTPFilterC Program Files Adobe Acrobat Acrobat Acrobat exeC DOCUME SHAWNO LOCALS Temp Adobelm Cleanup C Program Files Common Files Adobe Systems Shared Service Adobelmsvc exeC DOCUME SHAWNO LOCALS Temp Adobelm Cleanup C WINDOWS system HPZipm exeC Program Files Internet Explorer iexplore exeC Documents and Settings Shawn Oen Desktop dds scr Pseudo HJT Report uStart Page hxxp www cnn com BHO AcroIEHlprObj Class e f-c d - d -b d- b d be b - c program files adobe acrobat activex AcroIEHelper dllBHO Java Plug-In SSV Helper bb-d f - c-b eb-d daf d d - c program files java jre bin ssv dllBHO E D - A- EC-A -BA D E E - No FileBHO Windows Live Sign-in Helper d - c - abf- ecc- c - c program files common files microsoft shared windows live WindowsLiveLogin dllBHO AcroIEToolbarHelper Class ae cd -e - f- - ee - c program files adobe acrobat acrobat AcroIEFavClient Adobe... Read more
And here's a copy of my HOST file....# Copyright ?
The title says it all. I can stop it if I click, at the correct moment, on the red X at the side of the browser's address box.
Most infuriating and I have no idea how to stop it doing this.
Can you help please?
My OS is XP SP3 Home with all critical updates. Browser is IE8.
Hi. I was just messing around on my computer and I accidentally made Yahoo Mail my default mail client. I didn't meant to do this. I was just messing around and wasn't watching what I was doing and accidently did that. However, I don't want it to be my default mail client. How do I undo that?
To change it to OE, start it, go to Tools/Options/General and at the bottom click on Make this My Default Email Handler.
John
Hi,
I've just installed Avast! free antivirus on my Windows 7 PC. The installation installed something called the Mail Shield. Is there any point in having this turned on if I only access my emails using Yahoo's webmail service? Does it only scan mail if I use a client such as Windows Live Mail 2011?
Thanks in Advance!
You don't need it if you are using a web based mail like yahoo. You can do a custom install of avast and untick the mail shield.
please help me
what my pop and other outgoing and income servers
Hello
Is it possible to install Yahoo mail as my default mail service using Chrome?
I know ho to do it with Explorer but no luck with Chrome browser
Martin
reading your post., not sure if these may help. take a look at these links:
Google Groups
How to Make Google Chrome Your Default Browser - How-To Geek?
From Sender.
Subject---EMailer.
Hello to everyone!
I have added a signature to my yahoo e-mail that includes my name, my two sites, my actual e-mail and my telephone number. Although I haven't added a Skype number, during the last few months below my telephone number started appearing this:
Tel number
Call
Send SMS
Add to Skype
You'll need Skype Credit Free via Skype
I tried deleting my telephone number from my signature but these words still remain there. Any ideas on how I could delete these Skype details?
Thank you!
I want to print a list of my Mail contacts, including their addresses, so that I can add them to Yahoo Mail. I have done what Help tells me to do but I only get a list of names (e.g. John.............. (None)). I didn't have any trouble doing this in Outlook Express and I am guessing that I'm missing a simple step.
Ideally I would like to simply import my Contacts to Yahoo Mail so that when I'm overseas in a few weeks I can use Yahoo to mail people.
Subject Yahoo E-mail Sends Spam Mail without me knowing it I have an Yahoo Account that a friend told me that it was sending spam mail to him and it was a suprise to me because I did not send spam mail to that person What is going on and how do I cure this problem I use a couple of computers One had Advast free on it and the other has AVG free on E-mail Yahoo knowing without Sends me Spam it. Mail it The other day AVG expired and it took it Yahoo E-mail Sends Spam Mail without me knowing it. off of one computer I try to put Advast on it and it would not allow me to do that What should I do to fix this problem What I have done so far Ran Malware bytes amp found infections on quick scan I have not done a full scan Change password and made a second e mail address to the account and set it to primary I still need more advice on this subject Thank you nbsp
When I click on TOOLS, INTERNET OPTIONS, PROGRAMS I have a chioce of Outlook Express or Hotmail. I want it to be AT&TYahoo Mail. How can I do that?
i have had Google Chrome on several systems with Yahoo Mail set up as home page in the Google Chrome settings. (Home desktop, primarily as a server and storage, work laptop fpr work only, and home laptop for e-mail, internet, and other home apps.)
.
On my home laptop, recently, after opening to Yahoo Mail, as it finishes loading, it then goes to Yahoo UK website.
.
???
I rechecked the Google Chrome settings, and that page is not set there.
I have Google Chrome set up to open only TWO specific pages:
Yahoo Mail and My Yahoo.
Those two open, as specified.
But the Yahoo mail, first tab, after it opens, redirects to yahoo UK.
Check your hosts file located at c:\windows\system32\drivers\etc\ and see if yahoo is listed in there.
If your Yahoo Mail has been hacked first go to http help yahoo com l us yahoo mail Hacked Yahoo Help Yahoo Your Here's -- Has From Mail If Been classic contacts spam- html for help from Yahoo Mail You must do this ASAP in order to have a chance of restoring your messages and saving your Address Book Contacts TO RESTORE YOUR YAHOO MAIL MESSAGES If you use Yahoo Mail Classic click here If you use the All New Yahoo Mail click here TO RESTORE ADDRESS BOOK CONTACTS LIST To restore your Yahoo Address Book fill out this restoration form You must do this within hours in order to have a chance of saving your Address Book TO REPORT If Your Yahoo Mail Has Been Hacked -- Here's Help From Yahoo THE ABUSE TO YAHOO IDENTIFY THE HACKER Go to this page and If Your Yahoo Mail Has Been Hacked -- Here's Help From Yahoo fill out the form http help yahoo com If Your Yahoo Mail Has Been Hacked -- Here's Help From Yahoo l us yahoo mail classic abuse html You will be asked for specific information regarding the hacked email including the HEADER which IDENTIFIES the HACKER The way this works is that the hacked email message itself contains certain information in the Header relating to the hacker's identity The Header contains an Internet Protocol IP address that corresponds to the sender's Internet service provider ISP To located the Header Select and Open the hacked email Look to the very bottom-right corner of the email and select Full Headers You'll then see a long list of technical information most of which will not be easily readable Look for a line that says something like Received from That number is what Yahoo is looking for Copy it to your Clipboard Ctrl C or write it down Then go to a utility such as whois which will tell you the name of the hacker from which the email was sent Provide this information to Yahoo Mail along with the other information requested and Yahoo Mail will respond within hours For additional help Yahoo also has a Hacking Forum at Y-Mail discussion group
Nice info Sue.
Thanks.
For some reason I cant get to my e-mail on IE or Fire fox ive tryed MSN, yahoo and comcast all I get is this page cant be displayed like it cant load any body know why? I can go to other websites just fine I just cant go to any e-mail websites.
NO one knows? Ive tryied going through my security settings but still doesent work and the same message appers when I try to acsses my online banking site. Could it be only secure sites I cant see?
Does anyone know whether it is possible to access Yahoo emails with Windows mail if I have Yahoo classic email and not the premium Yahoo email plus service?
Thanks in advance
Ben
Originally Posted by benplant
Does anyone know whether it is possible to access Yahoo emails with Windows mail if I have Yahoo classic email and not the premium Yahoo email plus service?
Thanks in advance
Ben
yes you can, just sign into yahoo.com mail and go to options in the top right hand corner drop down list > mail options, look in there for pop access and forwarding, click it and find "pop settings" link, this will give you a bare looking page but all the info you need to set it up in windows mail.
ive posted a pic of my regional settings, these may not work for you depending what region you are in, forgive the squiggles, i do not want to divulge my email to everyone.
This morning I tried to sign sign to mail, mail, Cannot in aol yahoo google.com, in on my Home Page to Cannot sign in to aol mail, yahoo mail, google.com, my AOL mail and got the message that it couldn t find the server I then put aol com into the browser and Cannot sign in to aol mail, yahoo mail, google.com, got the AOL home page but it refused to let me get to my email page nbsp Tried my yahoo email and that would work either nbsp It would let me connect to NOAA weather CH a photog website and ebay nbsp I figured it might be a problem with my browser Firefox so I switched to Microsoft Edge and Cannot sign in to aol mail, yahoo mail, google.com, that did exactly the same thing nbsp Some sites would come up and many would not nbsp I have Kaspersky Total Security and updated Firefox last evening before signing off nbsp I have no idea if it has something to do with Kaspersky or settings somewhere that I know nothing about nbsp Has anyone else had this problem nbsp I am running Windows and my internet is through Hughesnet which I ve had a problem with lately nbsp Keep getting DNS server messages nbsp Have no idea what that means nbsp If anyone has had this problem and or knows how to rectify it please let me know nbsp I will just have to keep checking back for answers as I can t get to my email to check for notices of answers nbsp Thank you
Hi to all I am new here We just got a new desktop computer with OS window I was able to set yahoo as my homepage and able to access to my email and installed yahoo messenger My problem is everytime I click quot read mail quot it says that it cannot perform operation because the default mail client is not properly installed So I went to my control panel - internet options - programs to change my default email but there is no way I can choose yahoo mail as default email I tried it many times and still trying to figure how to set my yahoo mail Also every time I click the hyperlink email it says that quot There is no program associated to perform the requested action Please install an email program or if one is already installed create an association in the default programs control panel quot So I tried to make changes of as How client? mail to yahoo set my mail default my default programs but no yahoo mail Is there anybody here with similar case with me Hope you can help Thanks everyone Looking for your help l
Me too. I'm having the same trouble in hyperlink email; tried a lot of things. Two of us need help! VK.
Originally Posted by layman.
Try clicking on as indicated in attachment.
I would like to get my Yahoo mail in/on my XP pc machine. I need to know how to configure the server settings ie; incoming and out going - ports if ness. I get it fine with my iPhone but lack specs to set it up in OE6.
Or is this possible....??
Incoming mail server settings
?POP server: plus.pop.mail.yahoo.com
?Use SSL
?Port: 995
Outgoing mail server (SMTP) settings
?SMTP server: plus.smtp.mail.yahoo.com
?Use SSL
?Port: 465
?Use authentication
?Account Name/Login Name: Your Yahoo! Mail ID (your email address without the "@yahoo.com", for example, ?testing80?)
?Password: Your Yahoo! Mail password
I've tried Tools/Options/Programs /Set Programs/Set Default Programs.
Nothing there for me to make the switch.
I'm using Vista Ultimate
Any suggestions would be appreciated.
My Windows Mail is synced with my Yahoo Mail and when I delete a message in one it is still in the other. Is there any way to change this so that if a delete a message from one it deletes it from the other simultaneously?
Also when I open a message in my Yahoo Mail it will not appear in my Windows Mail. Is there a way to make all e-mails go to both accounts?
Hi, all!
It's very annoying having to open two or more mailers to check e-mails. Is there any means of configuring Windows Mail so that I can download my messages from Yahoo Mail through Windows Mail?
Thanks,
Hi Peter,
as long as you have all the required details such as server address, username/password, there's no reason why you cannot set up Windows Mail to connect to the servers for you:
Hope that helps
Does anyone know what Yahoo is doing playing the "We want to protect your e-mail from nasty people" game ? They want everyone to change their password, give them a mobile phone number and a
couple of other obscure requests.
I just ignore their requests for my mobile phone number (pretty much NOBODY gets that number!). The only time I change my password is when there is a possibility Yahoo and/or my password has been hacked.
My yahoo mail will not open the window to Not Mail Mail To Being Able Compose Yahoo compose a new email When I click it and it opens slowly Yahoo Mail Not Being Able To Compose Mail but I asked a friend in the same state and his email is working Let me set up why I Yahoo Mail Not Being Able To Compose Mail Yahoo Mail Not Being Able To Compose Mail
My yahoo mail will not open the window to compose a new email. When I click it and it opens slowly(20 but I asked a friend in the same state and his email is working.
Let me set up why I...
It now seems to be working ok Maybe it was a Yahoo thing
I have a Dell computer with Windows XP SP2, using SBCglobal.net internet provider who uses Yahoo browser. When I open an e-mail with pictures included, and try to forward it to someone else, the pictures disappear. All I have in the body is text. Also, sometimes when I receive an e-mail with pictures, all I get are white boxes with a red x in the corner. Can anyone solve this for me? I have talked until I'm blue in the face to the brain dead techs at SBCglobal, and they have, as usual, solved nothing. I'm not a total novice, but I am certainly no tech either.
for some reason i can't get me yahoo e-mail to come up on my comp. it will come up on any onher comp. i use , there are no firewalls that i am aware of i have just reinstalled windows xp and all i have downloaded is AVG anti virus the page for my mail will open but i can not open my mail and i was wondering if anyone has had this problem and if anyone can help with this .
I use Yahoo Mail for email purposes but currently unable to log on. When I click on icon which enables me to get connected I receive error message as follows:
quote
RUNDLL
X Error loading c:\program~!\yahoo\common\ymmapi.dll
The specified module could not be found
unquote
Can anyone help / advise how to overcome this problem.
How to remove ymmapi error
i punched in that websearch by mistake but i deleted that and now my mail won't load due to the fact of that mistake and i don't know how to fix it --help??i am currently using the new version-8
Can you be much more specific? I have no idea what you are talking about.
Hi folks,
I bought a PC about 18 months ago. Ever since Yahoo mail would randomly take over my internet connection when it felt like it.
Only certain sites are affected...I have tried removing Yahoo elements from my machine and cookies etc but something is lurking and obviously the manufacturer (HP) must have put it there.
Please help because playing online games, visiting various sites, etc and getting dragged out because yahoo wants to sign you up to an email account is annoying.
Thanks,
Mark
Well I can't send anything from yahoo mail, don't know why, but guess that I need to check smtp and imtp settings to see if correct, but How do I get to them to check and what is the proper terms that I need to type in? Thanks in advance, and if it is something else let me know.
With Yahoo I don't know if you can. If you use the yahoo toolbar on any browser, (didn't mention which browser is giving you trouble) uninstall it using Revo uninstaller, reboot your computer then go back to yahoo and reinstall it. See if it helps. I have been having issues with Yahoo mail myself for the past few days so it may be a Yahoo issue.
i can't log into my yahoo mail on my computer most of the time but once every now and then i can i also can't log into my other e-mail accounts i don't know what's wrong with it so i'ld really appreciate any help Logfile of HijackThis v into yahoo log mail can't Scan saved at PM on Platform Windows XP SP WinNT MSIE Internet Explorer v SP Running processes C WINDOWS System smss exe C WINDOWS system csrss exe C WINDOWS system winlogon exe C can't log into yahoo mail mcafee MCAFEE MssSrv exe C WINDOWS System svchost exe C WINDOWS system wdfmgr exe C WINDOWS System MsPMSPSv exe C WINDOWS System alg exe C WINDOWS Explorer EXE C WINDOWS system hkcmd exe C Program Files Roxio Easy CD Creator AudioCentral RxMon exe C Program Files Common Files Logitech QCDriver LVCOMS EXE C Program Files Java jre bin jusched exe C Program Files Dell Photo AIO Printer dlbxmon exe C PROGRA mcafee com agent mcregwiz exe C WINDOWS system dlbxcoms exe C PROGRA mcafee com agent mcagent exe C Program Files Roxio Easy CD Creator AudioCentral Playlist exe C Program Files McAfee McAfee AntiSpyware MssCli exe C WINDOWS system ctfmon exe C Program Files Webroot Spy Sweeper SpySweeper exe C Program Files Logitech Desktop Messenger Program BackWeb- exe C Program Files Verizon Online SupportCenter bin mpbtn exe C Program Files LimeWire LimeWire LimeWire exe C Program Files BitComet BitComet exe C Program Files Internet Explorer iexplore exe C Program Files Common Files Real Update OB realsched exe C Program Files Windows Media Player wmplayer exe C Documents and Settings Tokunbo Ipaye Desktop HijackThis exe R - HKCU Software Microsoft Internet Explorer Main Search Bar http cgi verizon net bookmarks bmr amp bm ho search R - HKCU Software Microsoft Internet Explorer Main Start Page http www yahoo com R - HKCU Software Microsoft Internet Explorer Main Window Title Microsoft Internet Explorer provided by Verizon Online dll O - Toolbar Yahoo Toolbar - EF BD -C FB- D - F- D F - C Program Files Yahoo Companion Installs cpn ycomp dll O - HKLM Run IgfxTray C WINDOWS system igfxtray exe O - HKLM Run HotKeysCmds C WINDOWS system hkcmd exe O - HKLM Run RoxioEngineUtility quot C Program Files Common Files Roxio Shared System EngUtil exe quot O - HKLM Run RoxioAudioCentral quot C Program Files Roxio Easy CD Creator AudioCentral RxMon exe quot O - HKLM Run LVCOMS C Program Files Common Files Logitech QCDriver LVCOMS EXE O - HKLM Run SunJavaUpdateSched C Program Files Java jre bin jusched exe O - HKLM Run dlbxmon exe quot C Program Files Dell Photo AIO Printer dlbxmon exe quot O - HKLM Run TkBellExe quot C Program Files Common Files Real Update OB realsched exe quot -osboot O - HKLM Run MSConfig C WINDOWS PCHealth HelpCtr Binaries MSConfig exe auto O - HKLM Run McRegWiz C PROGRA mcafee com agent mcregwiz exe autorun O - HKLM Run MCAgentExe c PROGRA mcafee com agent mcagent exe O - HKLM Run MCUpdateExe C PROGRA mcafee com agent mcupdate exe O - HKLM Run AntiSpyware C Program Files McAfee McAfee AntiSpyware MssCli exe O - HKCU Run SFP C Program Files Common Files Verizon Online SFP vzSFPWin EXE s O - HKCU Run ctfmon exe C WINDOWS system ctfmon exe O - HKCU Run SpySweeper quot C Program Files Webroot Spy Sweeper SpySweeper exe quot O - HKCU Run LDM C Program Files Logitech Desktop Messenger Program BackWeb- exe O - Global Startup Logitech Desktop Messenger lnk C Program Files Logitech Desktop Messenger Program LDMConf exe O - Global Startup Microsoft Office lnk C Program Files Microsoft Office Office OSA EXE O - Global Startup Ve... Read more.
Your Hijack this should not be on the desktop.
Please download HijackThis . here. We do not need the original hijackthis.log (unless we ask for it). Do not fix anything in HijackThis since they may be harmless.
Anyway to transfer back to the old Yahoo Classic ?
I have "googled" the issue but most possible solutions are outdated. One older solution was changing the screen resolution which supposedly transfers back to the Classic but this did not work.
I personally have not experienced any issues with the new Yahoo Mail as stated below, but just prefer the Classic format.
Anger explodes at Yahoo Mail redesign disaster: Key functions removed or broken | ZDNet
Not only a lousy 'redesign', also "scanning communications content"....
Yahoo Mail redesign becomes permanent, privacy issues surface | TechHive
And of course they sent an email to all users informing in detail about the scanning & the socalled Ad Interest Manager ...not.
Hi I m not sure if I m infected or not We have a computer running Windows XP service pack There were two to mail Can't yahoo get log-ins on the machine - both were admin accounts I few days ago I decided that was probably not a good thing so I created a new admin Can't get to yahoo mail account and made the existing accounts limited users On the Can't get to yahoo mail st user account when I tried to access yahoo web mail it kept redirecting to a google search results page returning a search on the term quot http quot Yahoo mail worked on the the second user account and on the admin Quickbooks however did not work on any account Last night I reset the second user account back to admin so I could access Quickbooks and bill I left it on the admin setting overnight This morning I woke up and I can t get to yahoo mail on any of the accounts The server connection times out I called yahoo business mail and they ve tested on their end and say there is no issue A Norton scan and a Malwarebytes scan both found nothing I m able to access all other webpages with no problem Is this an infection or something else
I should also mention that I can access the yahoo mail account from other computers in the house - the yahoo folks felt our internet provider was the cause of the problem. But if that was the case, I wouldn't be able to get to it from any computer in our house.
I had to do a system restore, since then Yahoo Home is fine, Inbox will allow me to read but no deleting or moving and the screen looks different, ...a lot. The bar at the very top starts off strange instead of reading Inbox, it reads (1300 unread) Yahoo! Mail...Have I created a monster? How do I fix this?
it sounds like a browser issue, could you tell me your browser name and version?
I haven't been liking my Yahoo lately and when that HeartBleed thingy came out and it was hit hard with Yahoo accounts and I was actually having a lot of problems with my Yahoo and changed my pw many times...I just don't really trust it anymore. And now I notice that it keeps asking me to add this application to mail links...and I tried to google any info on it and I wasn't very successful with it. So maybe someone in here can tell me what this is and what it does etc. etc.
/us-mg5.mail.yahoo.com/neo/launch?
There were more numbers at the end but I wasn't sure if it was part of my account number or what so I didn't add those.
I think it's time I found myself a different email service that was more reliable and SAFE. Any suggestions?
Thanks for any help anyone can offer
Hi Welcome to Seven Forums ... The Link below should be of some help ...
I?
Welcome to Bleeping Computer safisher. If the Yahoo mail site is being redirected to another page, there may be malware or a virus in your OS.Please download and install SUPERAntiSpyware. If you can, run the scan in Safe Mode and allow it to quarantine whatever it finds.
Sorry if this has been discussed, I did a couple of searches and couldn't find it.
I am running Windows 7 Enterprise Edition 64 bit and just updated to IE9. This is on two separate computers and neither of them will let me send an email or add an attachment to an email using yahoo mail through the browser.
I have tried adjusting the user account settings as well as trying to run IE with no add ons. Still nothing.
Any help or ideas?
Do you have these problems in any other browsers? Please try one of the below (both are free):
Firefox
Opera
Does anybody know the procedure to transfer my yahoo account into WML? I moved gmail with no problem but i am having the hardest time moving yahoo over.
The last time I looked Yahoo does not allow POP, except for premium accounts. This information is a bit dated and it may have changed.
I've had a problem for months with my Yahoo. And it doesnt matter what computer I use. It started out as everyone in my contact list being emailed for viagra. Then I noticed when I replied or sent an email I woukd have this at the bottom :
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
-------------------------------------------------------
Sponsored links:
Rock Hard Erections. All New Formula
Attacks the Root Fast
Have you changed your password since this started?
I have three clients that I used their e-mail yahoo hotmail outlook and excite com s I operate Windows Home Premium Vista and broswer is Maxthon com with the newest one available I was reading mail in outlook or hotmail off of MSN and recieve a mail from myself from the yahoo client mail I did not send it and I know probably it took everyname in my address book and sent the message to them What in Help E-Mail Yahoo in can I run on Computer to rid or clean of this virus or malware in my mail client Below is the message I recieved tried to get an address or something I could go and report but nothing showed quot Actions Woody AM From Woody email protected Help in E-Mail in Yahoo This sender is in your contact Help in E-Mail in Yahoo list Sent Wed AM To Hello This message is coming to you with great depression due to my state of discomfort they have done the best they can Our flight leaves in few Hrs from now but we are having problems settling the hotel bills and the hotel manager won t let us leave until we settle the bills which is USD I am contacting you to ask for a short loan which I will refund immediately I get my family back home safely Let me know if you can help Looking forward to positive response Woody quot If I have left something out or you need more information please contact me Thanks for the help Woody nbsp
hi
I ve got 50 addresses I d like to get into yahoo e mail
is there a quick way
or do i have to enter each e mail addres seperately
thanks for advice
Jess
hi! Here I come again with my problems..hehe!
I cant access my Yahoo mail login-page. First I thought it was the problem of the Yahoo server so I didnt worry but right now I tried to login from my roommate's computer (who is using by the way the same internet line) and it worked without any problems! What's wrong then with my computer??
I can access ALL other internet pages without any problems so it seems very strange to me!
Thanks for your help!
Is it that you cannot access the Email page itself (say from My Yahoo page) and do you get an error message or does it just "hang"? or does the Email page not function on you get on it?
Regards,
John
It was working a half hour ago and now it wont allow me to log into my main account.
No matter how many times I try it will not allow me to log in. I f I click the Can't Access My Account doesn't help, it just cycles between three pages and nothing more not matter what I do. And yes I've deleted the cookies and history and it's still doing this. And I've tried three browser and it still won't work
There is NO change password option at all since they never care about thier customers.
Yahoo as usual is of NO help what so ever. I desperately need to figure out what is happening since its connected to how I make money. No e mail, no money.
Hello all..
I have tried to manage this issue with Yahoo..But on all honesty it's like chasing a headless chicken.
I wonder if somebody can help/advise me. The field in which you type in, for your password has disappeared. I have looked into this on 2 different laptops including my main computer, with 4 different types of browsers. Is anybody else experiencing this at all?
Thanks.
Carl
Hi,
Some email services use 2 step entries
First you enter the email account and the enter key
Then the password box appears....
Gmail has gone this way.
I can access all E-Mail folders in Yahoo Mail but when trying to delete or send items am getting an "Error on page" message at bottom left-hand status bar.
Any one have any ideas as to cause/correction.?
Hello guys I am new in here not sure how this works. I am having trouble with Yahoo addrees book,none of the features seem to work.I tried to contact Yahoo but when I click the "Contact us link" I get : "the page cannot be displayed.I tried for a week in different times of the day.does anyone knows how to get to them? Thanks
It probably wouldn't do any good if you could contact them. I sent them a few e-mails once, and never heard back from them.
I just sudeenly stopped getting any e-mails into my yahoo account !! What could have happened !! I checked the bulk and im not getting any there either !!!!
When exiting Yahoo email the website sometimes restarts on its own, I have tried exiting by hitting the red X to close and also the file exit tab, what would cause this to keep restarting? I have run Malwarebytes thinking it might be some malware but found nothing. I am running Windows xp pro sp3.
What do you mean by restarting?
I have a spam email that won't go away. When I delete all spam, it all disappears, but the list on the left shows 1 email still unread. Since I've had this problem, my spam has ballooned to 100+ a day. I run Windows 7, Firefox, and Avast anti-virus. I have defragged, cleared cookies, and run Avast PC clean-up, but no joy. Can you help?
Are you referring to your email on the Yahoo portal or a local client and if so which one is it?
I have a Dell optiplex980 OS7 suddenly I am unable to access my yahoo mail. It comes up with temporary error 15. I rebooted but it made no difference..I clicked on help but couldn't get into it because apparently I kept getting the validation codes wrong even when I chose audio codes. I can get my mail on the Ipad so it is obviously something to do with the PC..It did do some updating during the night..could that be relevant?
Nita
Actually, pretty sure that is a known Yahoo! issue. I'd give it a couple hours and try again. Have you cleared your cookies and cache?
My sister-in-law's Yahoo email account has been hacked. She's not sure if the hack came from malware or not. I've attached her DDS log for your examination.
Hello HKooiWelcome to BleepingComputer ========================If you are still in need of assistance please post a new dds log.
I just mail yahoo downloaded firefox in which i like the faster browsing but need yahoo mail help for some reason i can't log into yahoo mail i keep getting a message but i can log in with another browser thanks in advance Error Your login session has expired Why does my session expire Login sessions expire for two reasons For your security your Yahoo Mail session expires a maximum of twenty-four hours yahoo mail after you have logged in If you have chosen yahoo mail in your Yahoo User Information found be visiting quot My Account quot
I'm able to login at Yahoo mail using Firefox.
See if your settings match mine. Tools/Options/Privacy
WELL NEVER MIND I guess it takes them longer than mins to straighten things out Mysteriously I can now download OR just posting here threatened them to shape up I have the site bookmarked I ll be back I m sure I bit the bullet and bought the Yahoo Plus package -- so I can read e-mails on line and only download those I want in graphic groups so need this capability I have followed their instructions to a T but still can t DL using Outlook OE6 with yahoo plus Can't mail DL Express It keeps telling methe server rejected my password which I know is correct I ve deleted and reinstalled times this new account I have XPPro IE OE I m able to use POP on other accounts so don Can't DL yahoo plus mail with OE6 t see why there s a problem now Does anyone know or have any guidance guesses what I can do I don t mind paying money if its gonna do what its supposed to but if it ain t I don t want Can't DL yahoo plus mail with OE6 to waste my time either Thanks in advance Mia nbsp
I have a friend that has a blackberry, and an ipad. I believe they are the root cause of this. Their yahoo contacts has multiple duplicates. My question is, I know you can export your contacts into an Excel spreadsheet, is there a way to export it, edit the Excel spreadsheet so it doesn't have duplicates and then reupload it. I know you can merge the contacts using Yahoo, but I was wondering if this could be a possible way as well.
Here is a way to remove duplicates on the Blackberry
Hi Guys, dose anybody out there know how to get in touch with Yahoo by email or Phone I cant get through the mist that surrounds demi god thanks Glenn
Their toll free number is 1-866-562-7219
And their corporate number is 1-408-349-3300
I found these through some Google searching. It doesn't seem like most people had so much luck getting through, though.
Best of luck.
Is it just my computer, or has anyone else been having problems with Yahoo mail, getting a lot of "having technical difficulty" message lately.
I am using Win 8.1
Hello.
It does not matter what kind of operating system you use. It only matters about your internet connection and Yahoo's own servers. Whenever you request for a website like Google, your computer (More accurately, your modem or router, and of course, your browser) "requests" for Google's IP, its DNS, and makes coupe of under-the-hood requests like handshaking and cryptography. However, whenever your internet service provider's server (or line) is down, you will be unable to access anything over the internet. The same goes for Google's own servers. If any of those that concern your area are down, the website is most likely down.
As you can see, it hardly matters what operating system you are using. For me, Yahoo US website is up.
When I send an email message from my Yahoo account, I either get this error: 5.7.9 Message not accepted for policy reasons. What can I do about this.
Or I get this one:
550 5.7.1 initiative. e14si8721007wjz.208 - gsmtp
which is something to do with blacklisting I think.
They think you're either spamming (content) or sending too many in one mailing. If it's the latter, break up the list into partials.
Hi from melbourne australia yahoo mail with l would appreciate help Hi some firstly l just want to say that l appreciate anyfree help that Hi l would appreciate some help with yahoo mail l can get l know people on here are volunteers which is something l want to do so thanks And also my computer internet knowledge isn't the greatest so laymans terms preferred when l get some answers Anwyay basically l am having problems sending an email to trend micro in australia the address i'm trying to send is to pccau trendmicro com au and it is a valid address l keep receiving a mailer-daemon error message and l have no idea what to do about it something tells me its got something to do with my anti virus which is trend micro and i've just signed up with yahoo mail recently and its the only email i've sent of in yahoo mail to trend micro and l have no idea if l send more emails if this problem will occur anyway the error message is below actually its the whole email because l don't know what part l should include not include Refer below Sorry we were unable to deliver your message to the following address lt pccau support trendmicro com gt Message expired for domain support trendmicro com --- Below this line is a copy of the message Received from by n bullet mail ukl yahoo com with NNFMP Feb - Received from by t bullet ukl yahoo com with NNFMP Feb - Received from by t bullet sp yahoo com with NNFMP Feb - Received from by omp mail sp yahoo com with NNFMP Feb - X-Yahoo-Newman-Property ymail- X-Yahoo-Newman-Id bm omp mail sp yahoo com Received qmail invoked by uid Feb - DomainKey-Signature a rsa-sha q dns c nofws s s d yahoo com h X-YMail-OSG Received X-Mailer Date From Subject To MIME-Version Content-Type Message-ID b h Nm lViw pCFG aH pbYf fl Jm Oq ccJgYLJRv VRfxNAy VbvchTwKjFK nOLNBd mVtIEknMkMU NLKDnv LUJwZC wh HJmgkxG NknyDoIYzsUe L BD TSAnVKESE F NfhA A Toonl lI ULGvzjvv E X-YMail-OSG HFxJM VM kSP LIqvmMiJ BN CeMjQsCaUp Ex tRK kEbRiZzZN R E M D PmQ-- Received from by web mail sp yahoo com via HTTP Tue Feb MSK X-Mailer YahooMailRC YahooMailWebService Date Tue Feb MSK From Aaron Pekar lt aaronsky poponsky yahoo com gt Subject l hope this message gets through To pccau support trendmicro com MIME-Version Content-Type multipart alternative boundary quot - - quot Message-ID lt qm web mail sp yahoo com gt -- - - Content-Type text plain charset utf- Content-Transfer-Encoding quoted-printable Hi l need help with a few questions Basically i've been surfing the intern et for the Alast hour or so and trendmicro keeps blocking certain web pag es It tells me to go to AINTERNET AND EMAIL CONTROLS and then choose PAR ENTAL CONTROLS and click settings and add Athat particular web site that l can't access in the list but the problem is i've Abeen doing this over a nd over again and its really frustrating also with the message it Asais to copy and paste it into the APPROVE WEBSITES LIST but it won't work l c an't Apaste and copy AAnd on top of all this even when l typed in the ad dress for the website to be approved it Adoesn't work l still can't get i n the website sometimes this works and sometimes Athis doesn't A AMy s econd question is that A regarding the internet security pro services sect ion l just want Ato know that if l perform a TUNE UP where it deletes coo kies and frees up space will this Atune up affect my computer files l mea n is it safe to do this im guessing yes but l just Aneed some clarificat ion AI'd be grateful for an answer because this is really annoying me th e blocked web sites Aproblem and l will be very grateful if l could get some answers clear instructions on how Ato solve this problem A AI'm us ing windows vista business mozilla firefox internet browser and trend mic ro Ainternet security PRO Akeep well AAaron A A AP S l tried sending this message a couple of weeks ago via my optusnet webmail account Abut it wouldn't go through l only hope it works through yahoo mail so mething about Amail delivery subsystem A A A A A A A ... Read more
The error indicates that your connection to your server was terminated; it can be your firewall, or a problem with the server itself, or any server in between To correct it
1. Open Internet explorer
2. Tools
3. Internet options
4. Security tab
5. Then hit default level....if thats not an option, hit custom level and click reset to medium or medium low.
6. Apply and ok and it should work from there!
Hi folks I signed up as Arkieforester but used my Yahoo addy which is part of my problem so couldn't activate my account here I can't log in to Yahoo Mail on this pc I can from any other pc elsewhere in Mail Yahoo Can't log out log to or I CAN log in through Yahoo Messenger on this pc IF I have new mail waiting When I click on quot Go to Yahoo Mail quot there it logs me right in Once in I can't log out of Yahoo Mail but can log out of YM All other mail sites work with Can't log in to Yahoo Mail or log out no problems elsewhere on the Internet The problem began during the last denial of service attack It isn't a Yahoo server problem unless they are blocking my IP and YM is a loophole Before I learned of the DoS I changed my password several times thinking I had been hijacked which prompted them to place a hold on my account Since I can get in elsewhere I'd say that hold is lifted Yahoo is non-responsive except for their auto-generated responses All that is useless since I can no longer answer my secret question there last of my SS number Who would forget that Any help at all would be greatly appreciated I would like to avoid re-formatting my pc over this thinking there is a gremlin lurking in this thing I ran Norton AV and Webroot Spy Sweeper again with nothing found I've tried without unnecessary programs running but always leaving NAV and ZoneAlarm running Here's my Hijack This log Logfile of HijackThis v Scan saved at AM on Platform Windows SE Win x A MSIE Internet Explorer v SP Running processes C WINDOWS SYSTEM KERNEL DLL C WINDOWS SYSTEM MSGSRV EXE C WINDOWS SYSTEM MPREXE EXE C WINDOWS SYSTEM MSGLOOP EXE C WINDOWS SYSTEM MSG EXE C WINDOWS SYSTEM mmtask tsk C PROGRAM FILES NORTON SYSTEMWORKS Can't log in to Yahoo Mail or log out NORTON CLEANSWEEP CSINJECT EXE C PROGRAM FILES NORTON SYSTEMWORKS NORTON UTILITIES NPROTECT EXE C PROGRAM FILES COMMON FILES SYMANTEC SHARED Can't log in to Yahoo Mail or log out SYMTRAY EXE C PROGRAM FILES ROXIO GOBACK GBPOLL EXE C WINDOWS SYSTEM ZONELABS VSMON EXE C WINDOWS SYSTEM MSTASK EXE C WINDOWS EXPLORER EXE C WINDOWS TASKMON EXE C WINDOWS SYSTEM SYSTRAY EXE C PROGRAM FILES NORTON SYSTEMWORKS NORTON ANTIVIRUS NAVAPW EXE C PROGRAM FILES SCANSOFT PAPERPORT FBDIRECT EXE C PROGRAM FILES TEXTBRIDGE CLASSIC BIN INSTANTACCESS EXE C PROGRAM FILES NETROPA ONE-TOUCH MULTIMEDIA KEYBOARD MMKEYBD EXE C WINDOWS SYSTEM HPSYSDRV EXE C WINDOWS RunDLL exe C WINDOWS SYSTEM SPOOL EXE C PROGRAM FILES WEBROOT SPY SWEEPER SPYSWEEPER EXE C PROGRAM FILES NETROPA ONE-TOUCH MULTIMEDIA KEYBOARD KEYBDMGR EXE C PROGRAM FILES ZONE LABS ZONEALARM ZONEALARM EXE C PROGRAM FILES SILICON PRAIRIE SOFTWARE MEMTURBO MEMTURBO EXE C PROGRAM FILES YAHOO MESSENGER YMSGR TRAY EXE C PROGRA NETROPA ONSCRE OSD EXE C PROGRAM FILES ROXIO GOBACK GBTRAY EXE C WINDOWS SYSTEM WMIEXE EXE C PROGRAM FILES MICROSOFT OFFICE OFFICE FINDFAST EXE C PROGRAM FILES NORTON SYSTEMWORKS NORTON CLEANSWEEP CSINSM EXE C PROGRAM FILES VISUALZONE VISUALZONE EXE C PROGRAM FILES ADSGONE ADSGONE EXE C PROGRAM FILES NETROPA ONE-TOUCH MULTIMEDIA KEYBOARD MMUSBKB EXE C Program Files Norton SystemWorks Norton CleanSweep Monwow exe C PROGRAM FILES HIJACKTHIS EXE R - HKCU Software Microsoft Internet Explorer Main Search Bar http www yahoo com search ie html R - HKCU Software Microsoft Internet Explorer Main Search Page http www yahoo com R - HKCU Software Microsoft Internet Explorer Main Start Page http mail yahoo com intl us R - HKCU Software Microsoft Internet Explorer Main Default Page URL http www cfaith com R - HKCU Software Microsoft Internet Explorer Search SearchAssistant http www couldnotfind com search count id R - HKLM Software Microsoft Internet Explorer Main Search Bar http yahoo com R - HKCU Software Microsoft Internet Explorer Main Window Title Microsoft Internet Explorer provided by CFAITH com R - HKCU Software Microsoft Internet Explorer SearchURL Default http search yahoo com search p s R - HKCU Software Microsoft Internet Explorer Main Start Page bak ... Read more
I just ran the CoolWebShredder and uninstalled the Java. Didn't help log in to Yahoo Mail. Here's the new Hijack This log:
Logfile of HijackThis v1.97.1
Scan saved at 10:56:09 AM, on 11/10/03\NORTON SYSTEMWORKS\NORTON CLEANSWEEP\CSINJECT.EXE
C:\WINDOWS\SYSTEM\MSGLOOP.EXE
C:\PROGRAM FILES\NORTON SYSTEMWORKS\NORTON UTILITIES\NPROTECT.EXE
C:\PROGRAM FILES\COMMON FILES\SYMANTEC SHARED\SYMTRAY.EXE
C:\PROGRAM FILES\ROXIO\GOBACK\GBPOLL.EXE
C:\WINDOWS\SYSTEM\ZONELABS\VSMON.EXE
C:\WINDOWS\SYSTEM\MSG32.EXE
C:\WINDOWS\SYSTEM\MSTASK.EXE
C:\WINDOWS\SYSTEM\mmtask.tsk
C:\WINDOWS\EXPLORER.EXE
C:\WINDOWS\TASKMON.EXE
C:\WINDOWS\SYSTEM\SYSTRAY.EXE
C:\PROGRAM FILES\NORTON SYSTEMWORKS\NORTON ANTIVIRUS\NAVAPW32.EXE
C:\PROGRAM FILES\SCANSOFT\PAPERPORT\FBDIRECT.EXE
C:\PROGRAM FILES\TEXTBRIDGE CLASSIC 2.0\BIN\INSTANTACCESS.EXE
C:\PROGRAM FILES\NETROPA\ONE-TOUCH MULTIMEDIA KEYBOARD\MMKEYBD.EXE
C:\WINDOWS\SYSTEM\HPSYSDRV.EXE
C:\WINDOWS\SYSTEM\SPOOL32.EXE
C:\PROGRAM FILES\NETROPA\ONE-TOUCH MULTIMEDIA KEYBOARD\KEYBDMGR.EXE
C:\WINDOWS\RunDLL.exe
C:\PROGRAM FILES\WEBROOT\SPY SWEEPER\SPYSWEEPER.EXE
C:\PROGRA~1\NETROPA\ONSCRE~1\OSD.EXE
C:\WINDOWS\SYSTEM\DDHELP.EXE
C:\PROGRAM FILES\YAHOO!\MESSENGER\YMSGR_TRAY.EXE
C:\PROGRAM FILES\ZONE LABS\ZONEALARM\ZONEALARM.EXE
C:\PROGRAM FILES\SILICON PRAIRIE SOFTWARE\MEMTURBO\MEMTURBO.EXE
C:\PROGRAM FILES\ROXIO\GOBACK\GBTRAY.EXE
C:\PROGRAM FILES\MICROSOFT OFFICE\OFFICE\FINDFAST.EXE
C:\PROGRAM FILES\NORTON SYSTEMWORKS\NORTON CLEANSWEEP\CSINSM32.EXE
C:\PROGRAM FILES\NETROPA\ONE-TOUCH MULTIMEDIA KEYBOARD\MMUSBKB2.EXE
C:\WINDOWS\SYSTEM\WMIEXE.EXE
C:\PROGRAM FILES\VISUALZONE\VISUALZONE.EXE
C:\PROGRAM FILES\ADSGONE\ADSGONE.EXE
C:\Program Files\Norton SystemWorks\Norton CleanSweep\Monwow.exe
C:\WINDOWS\SYSTEM\PSTORES.EXE
C:\PROGRAM FILES\INTERNET EXPLORER\IEXPLORE.EXE
C:\PROGRAM FILESKLM\Software\Microsoft\Internet Explorer\Main,Search Bar =
R1 - HKCU\Software\Microsoft\Internet Explorer\Main,Window Title = Microsoft Internet Explorer provided by CFAITH.com
R1 - HKCU\Software\Microsoft\Internet Explorer\SearchURL,(Default) =
R1 - HKCU\Software\Microsoft\Internet Explorer\Main,Start Page_bak =
O1 - Hosts: 64.97.247.243 mail.cfaith.com
O1 - Hosts: 64.4.45.7 lc3.law13.hotmail.passport.com
O1 - Hosts: 64.4.43.7 lc1.law13.hotmail.passport.com
O1 - Hosts: 65.54.194.120 arc5.msn.com
O1 - Hosts: 65.54.192.248 popup.msn.com
O1 - Hosts: 207.68.178.236 arc7.msn.com
O1 - Hosts: 65.54.229.253 loginnet.passport.com
O1 - Hosts: 64.58.76.117 story.news.yahoo.com
O1 - Hosts: 216.136.232.27 weather.yahoo.com
O1 - Hosts: 209.134.161.165 advice.networkice.com
O1 - Hosts: 216.136.227.14 us.address.mail.yahoo.com
O1 - Hosts: 66.218.71.80
O1 - Hosts: 66.218.66.240 groups.yahoo.com
O1 - Hosts: 209.98.62.65
O1 - Hosts: 216.136.175.34 us.f139.mail.yahoo.com
O1 - Hosts: 66.163.171.128 login.yahoo\MSDXM.OCX
O3 - Toolbar: (no name) - {EF99BD32-C1FB-11D2-892F-0090271D4F88} - (no file)
O4 - HKLM\..\Run: [LoadPowerProfile] Rundll32.exe pow... Read more
before i had my hardrive cleaned my pc which is windows vista, would use yahoo mail as the default to email from any website that i was on. now it does not. all my googling has only told me that you can't set yahoo mail as a default on vista, but i have using this feature for 2 years! it must have been a program pre-installed from the factory. does anyone know which one it might be? i was able to set it for firefox, but i don't like forefox. the vibrating scrolling hurts my eyes. i want to use IE the way i used to.
Hey all,
Even after explaining the definition of Trojan to my gf, she wants to know, is there something specific attacking her yahoo email account, something scans won't find? I told her to change her email password and run a new scan, but also told her I would ask, just for her and domestic tranquility.
thanks
Morgan
p.s. here is the link her email sent to all her email addresses: hxxp://rapidshare.com/files/275226375/install.exe?0,3316944
again, thanks.
First a question. Is she using webmail or an e-mail client? In other words, does she get to her e-mail using IE, Firefox, or some other browser or is she using Outlook, Thunderbird or something else?
The answer to this question is very important.
Please note, that the link added to those e-mails is a malicious link.
Orange Blossom
Im on x p
im using internet explorer
I ve been using yahoo mail for 2 years no problem
in the past 2 days though
i write an email
then try to put a photo file on
the green dots go along then just before they finish
error on page........ appears in the address bar
the green dots disappear
so I cant get attachments onto my yahoo mail
doe s anyone know whats happening
and how I can fix it ?
I think yahoo mail has a restriction on the size of an attachment. Are these pics over 1MB?
dtugg
Not.
How can I transfer e-mails from Yahoo to my flash drive - I would prefer to transfer them in block as sending them individually is long winded!
Hi, I seem to have trouble accessing my yahoo mail account from my home computer, but it always works from my computer at work. The message that appears is:
Unfortunately, we are unable to process your request at this time. We apologize for the inconvenience. Please try again later
Seems like a standard message, but it definately only occurrs on this particular computer!
Any suggestions as to what the problem may be?
I have also recently installed a program called zone alarm. Within 5 mins of installing it there had been 70 intrusions blocked by the firewall. Is this stadard, it seems a little excessive?
Thanks for help.....
delete cookies files then sign in
Tools -> Internet Options -> Delete Cookies....
ZoneAlarm is a good program don't install it.
My yahoo e mail will not let me delete "sent mail" . I have windows 8.1 Thanks for any help.
Could someone tell me how to go back thru my yahoo emails to the first page. There used to be a link , gone. It looks as though i need to scroll page by page. Thank you very much
Hit "Sort by Date" directly over the times/date of the Email.
Is it just my computer, or has anyone else been having problems with Yahoo mail, getting a lot of "having technical difficulty" message lately.
Chances are it's not your computer, it's Yahoo. If you aren't having problems with other sites then the problems lie on Yahoo's side
I cannot reply,compose,forward nor send an e-mail from yahoo. When opening e-mails on yahoo they open excessively slow and the tiny window at bottom never clears. (the one that usually say done) I am using windows XP. Please Help. Thanks
I'm using laptop with Win XP SP3 and IE8 and I can't open Yahoo e-mail from email icon on the main page (yahoo.com), error page displays saying Internet connection problem.
So, I have to type mail.yahoo.com to sign in into account.
But after that I can't sign out from account, the same page as above displays (Internet connection problem).
If I close IE and than attempt to open sign in page it goes directly to my account.
If I clear TempInt files, coockies, etc and restart IE I can open Sign In page, but after that everything is same as above, the same problem appears.
I tried uninstaling IE, reparing OS, but same things again.
I use NOD32 antivirus, and tried cleaning with SuperAntiSpyware, Malwarebytes. The last time I used Malwarebutes everything was blocked and I had to force shutdown.
Can You please help me ?
Please download and run Security Check from HERE, and save it to your Desktop. * Double-click SecurityCheck.exe * Follow the onscreen instructions inside of the black box. * A Notepad document should open automatically called checkup.txt; please post the contents of that document.
I don't know if this is even worth the effort asking but I won't let it beat me! Ok, right now I'm in temporary housing till my new house is ready. Because I don't have a regular ISP yet I'm using Yahoo mail for now. Here's the kicker. I set up an account with yahoo mail, no problem. Now, anyone that sends an email immediately gets an error bounce saying something like "user does not exist". BUT, I can log into webmail with no problem with that address. I'm so confused, I would just dump Yahoo mail if I wasn't so stubborn about problems like this. Any comments?
Tnx,
Dusty
Create a free e-mail account from another provider (maybe outlook.com) and send a test e-mail to your Yahoo e-mail account. That way, you can troubleshoot this issue as if you are one of your friends sending you an e-mail. If you get a bounce, then your new Yahoo account is corrupted on Yahoo's end. Good luck getting that fixed :-(
Is there any way to back up all the email I have on Yahoo Mail?
Have not used this but it could probably be done using Handy Backup. Yahoo Email Backup with Handy Backup
I am getting this error message "sorry bad request your browser sent a request that this server could not understand" when I try to download individual emails.The error does not occur all the time and appears without warning.After the error appears it repeats on every email I try to select but after some time it disappears.
Can anyone give me any help to clear the error?
Thanks
ronswold
Hi runswold,
I'm not sure which browser you're using, but if you're using FireFox, try going to Tools and Clear Private Data and click on that. See if that helps.
Zllio
Yahoo mail is suddenly asking me for my password every five minutes. Is this a glitch in their system?
Where can I find within Yahoo the page to change the time interval to 2 weeks.
Could someone pls help me with this issue please.
I use Firefox and Yahoo email. I've had this issue for a few days and I don't know why. The Icon with the Arrow on New next to Check Mail on your top left doesn't show up any longer. The icons like Bold, Italic...next to Bookman Old Style 12, in the middle, disappears. When I move my mouse (laptop) over the bar, the box without the Word appears. I' including a picture of what happens to my email. Your help in diagnosing this issue is surely appreciated.
Thanks
Yahoo mail problem:no graphic
I was led to this site while searching for yahoo mail tech support. The reply button doesn't work. I can't reply to emails. Any ideas out there? Thank you.
Hello and Welcome to TSF
Try and change your preferences to plain text formatting instead of HTML. Complete instructions for this are at
Also Clear the IE cache. IE> Tools> Internet Options> General>
files (and delete offline content when that dialog pops up).
Hi all.
Can't log in to Yahoo to check my mail. Anyone else got this problem? I've been trying for over an hour.
Cheers,
Ally.
This appears to be a reoccurring issue, that Yahoo has experienced recently.
Try again in an hour or three.
Is it possible to put an icon for Yahoo mail on my Taskbar in IE?
I do not want to use the Yahoo Toolbar.
Also how do I make it my main mail client?
Thanks
jack
It looks like without the Yahoo toolbar, there is a very slim chance of making Yahoo your default mail client on Windows 7, but try this and see if it works. Please BACK UP your system and set a RESTORE POINT before you do so, as you'll have to go into your Registry:
This method is for 32bit Internet Explorer on Windows 7 in its default location and the new Yahoo Mail:
1. Open your registry editor
2. navigate to [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command]
3. Edit the Default setting to: "C:\Program Files (x86)\Internet Explorer\iexplore.exe"
(The registry key type is REG_SZ)
just.
Hello,
I have Windows XP with Internet Explorer 7. I cannot reply to a message in Yahoo e-mail. It says, ?The page cannot be displayed.? I have same problem when forwarding an incoming message or saving a draft message. However, I can compose a new message and send out without any problem. Need help.
Thanks,
BP
Does anyone know the best browser for this bloody awful thing Yahoo has unleashed? AOL hates it, it closes down soon after being used to log in. Google chrome will load it but with exrtreme relucatnace, and terribly slowly. Same with Mozilla.
I was on yahoo Classic until the recent change - never any difficulties, fast as you could wish. But it's omp[ossible to get classic back.
Unless you know something?
Please don 't tell me to use other mailboxes, I have 200 addresses in yahoo category lists, I'll never live long enough to write those down and one by one transfer...............etc. | http://winassist.org/thread/2292797/Yahoo-Mail.php | CC-MAIN-2019-26 | refinedweb | 12,469 | 64.14 |
Sorry to bring this thread back from the dead, but I just tried using
JSONQuery within a Couch view and everything seems to work fine. I'm
using the forked version of JSONQuery from here:
The only gotcha is that JSONQuery expects either a namespace function
or a window object to exist. So, I just create a fake window object.
Here's an example of a working map view with JSONQuery.js included via
a CouchApp macro. You could just as easily copy/paste its contents
directly into a view if you aren't using CouchApp.
var window = {};
// !code JSONQuery.js
JSONQuery = window["JSONQuery"]
function(doc) {
var customers = JSONQuery("$.customers[?purchases > 21]", doc);
for (var i = 0; i < customers.length; i++) {
emit(customers[i].name, customers[i].purchases);
}
} | http://mail-archives.apache.org/mod_mbox/couchdb-user/200909.mbox/%3Cd72c12bb0909071012q5b953865qd50c09cefce82e82@mail.gmail.com%3E | CC-MAIN-2015-11 | refinedweb | 128 | 67.35 |
Writing a Package
Its intents are:
It is organized in the following four parts:
A Common Pattern for All Packages.
Therefore, all packages can be built using egg structures.
This section presents how a namespaced package is organized, released, and distributed to the world through distutils and setuptools.
Writing an egg is done by layering the code in a nested folder that provides a common prefix namespace. For instance, for the Acme company, the common namespace can be acme. The result is a namespaced package.
For example, a package whose code relates to SQL can be called acme.sql. The best way to work with such a package is to create an acme.sql folder that contains the acme and then the sql folder:
setup.py, the Script That Controls Everything
The root folder contains a setup.py script, which defines all metadata as described in the distutils module, combined as arguments in a call to the standard setup function. This function was extended by the third-party library setuptools that provides most of the egg infrastructure.
The boundary between distutils and setuptools is getting fuzzy, and they might merge one day.
Therefore, the minimum content for this file is:
from setuptools import setup
setup(name='acme.sql')
name gives the full name of the egg. From there, the script provides several commands that can be listed with the -help-commands option.
$ python setup.py --help-commands
Standard commands:
build build everything needed to install
...
install install everything from build directory
sdist create a source distribution
register register the distribution
bdist create a built (binary) distribution
Extra commands:
develop install package in 'development mode'
...
test run unit tests after in-place build
alias define a shortcut
bdist_egg create an "egg" distribution
The most important commands are the ones left in the preceding listing. Standard commands are the built-in commands provided by distutils, whereas Extra commands are the ones created by third-party packages such as setuptools or any other package that defines and registers a new command.
sdist
The sdist command is the simplest command available. It creates a release tree where everything needed to run the package is copied. This tree is then archived in one or many archived files (often, it just creates one tar ball). The archive is basically a copy of the source tree.
This command is the easiest way to distribute a package from the target system independently. It creates a dist folder with the archives in it that can be distributed. To be able to use it, an extra argument has to be passed to setup to provide a version number. If you don't give it a version value, it will use version = 0.0.0:
from setuptools import setup
setup(name='acme.sql', version='0.1.1'
This number is useful to upgrade an installation. Every time a package is released, the number is raised so that the target system knows it has changed.
Let's run the sdist command with this extra argument:
$ python setup.py sdist
running sdist
...
creating dist
tar -cf dist/acme.sql-0.1.1.tar acme.sql-0.1.1
gzip -f9 dist/acme.sql-0.1.1.tar
removing 'acme.sql-0.1.1' (and everything under it)
$ ls dist/
acme.sql-0.1.1.tar.gz
Under Windows, the archive will be a ZIP file.
The version is used to mark the name of the archive, which can be distributed and installed on any system having Python. In the sdist distribution, if the package contains C libraries or extensions, the target system is responsible for compiling them. This is very common for Linux-based systems or Mac OS because they commonly provide a compiler. But it is less usual to have it under Windows. That's why a package should always be distributed with a pre-built distribution as well, when it is intended to run under several platforms.
The MANIFEST.in File
When building a distribution with sdist, distutils browse the package directory looking for files to include in the archive.
distutils will include:
Besides, if your package is under Subversion or CVS, sdist will browse folders such as .svn to look for files to include .sdist builds a MANIFEST file that lists all files and includes them into the archive.
Let's say you are not using these version control systems, and need to include more files. Now, you can define a template called MANIFEST.in in the same directory as that of setup.py for the MANIFEST file, where you indicate to sdist which files to include.
This template defines one inclusion or exclusion rule per line, for example:
include HISTORY.txt
include README.txt
include CHANGES.txt
include CONTRIBUTORS.txt
include LICENSE
recursive-include *.txt *.py
The full list of commands is available at.
build and bdist
To be able to distribute a pre-built distribution, distutils provide the build command, which compiles the package in four steps:
Each of these steps is a command that can be called independently. The result of the compilation process is a build folder that contains everything needed for the package to be installed. There's no cross-compiler option yet in the distutils package. This means that the result of the command is always specific to the system it was build on.
Some people have recently proposed patches in the Python tracker to make distutils able to cross-compile the C parts. So this feature might be available in the future.
When some C extensions have to be created, the build process uses the system compiler and the Python header file (Python.h). This include file is available from the time Python was built from the sources. For a packaged distribution, an extra package called python-dev often contains it, and has to be installed as well.
The C compiler used is the system compiler. For Linux-based system or Mac OS X, this would be gcc. For Windows, Microsoft Visual C++ can be used (there's a free command-line version available) and the open-source project MinGW as well. This can be configured in distutils.
The build command is used by the bdist command to build a binary distribution. It calls build and all dependent commands, and then creates an archive in the same was as sdist does.
Let's create a binary distribution for acme.sql under Mac OS X:
$ python setup.py bdist
running bdist
running bdist_dumb
running build
...
running install_scripts
tar -cf dist/acme.sql-0.1.1.macosx-10.3-fat.tar .
gzip -f9 acme.sql-0.1.1.macosx-10.3-fat.tar
removing 'build/bdist.macosx-10.3-fat/dumb' (and everything under it)
$ ls dist/
acme.sql-0.1.1.macosx-10.3-fat.tar.gz acme.sql-0.1.1.tar.gz
Notice that the newly created archive's name contains the name of the system and the distribution it was built under (Mac OS X 10.3).
The same command called under Windows will create a specific distribution archive:
C:acme.sql> python.exe setup.py bdist
...
C:acme.sql> dir dist
25/02/2008 08:18 <DIR> .
25/02/2008 08:18 <DIR> ..
25/02/2008 08:24 16 055 acme.sql-0.1.win32.zip
1 File(s) 16 055 bytes
2 Dir(s) 22 239 752 192 bytes free
If a package contains C code, apart from a source distribution, it's important to release as many different binary distributions as possible. At the very least, a Windows binary distribution is important for those who don't have a C compiler installed.
A binary release contains a tree that can be copied directly into the Python tree. It mainly contains a folder that is copied into Python's site-packages folder.
bdist_egg
The bdist_egg command is an extra command provided by setuptools. It basically creates a binary distribution like bdist, but with a tree comparable to the one found in the source distribution. In other words, the archive can be downloaded, uncompressed, and used as it is by adding the folder to the Python search path (sys.path).
These days, this distribution mode should be used instead of the bdist-generated one.
install
The install command installs the package into Python. It will try to build the package if no previous build was made and then inject the result into the Python tree. When a source distribution is provided, it can be uncompressed in a temporary folder and then installed with this command. The install command will also install dependencies that are defined in the install_requires metadata.
This is done by looking at the packages in the Python Package Index (PyPI). For instance, to install pysqlite and SQLAlchemy together with acme.sql, the setup call can be changed to:
from setuptools import setup
setup(name='acme.sql', version='0.1.1',
install_requires=['pysqlite', 'SQLAlchemy'])
When we run the command, both dependencies will be installed.
How to Uninstall a Package
The command to uninstall a previously installed package is missing in setup.py. This feature was proposed earlier too. This is not trivial at all because an installer might change files that are used by other elements of the system.
The best way would be to create a snapshot of all elements that are being changed, and a record of all files and directories created.
A record option exists in install to record all files that have been created in a text file:
$ python setup.py install --record installation.txt
running install
...
writing list of installed files to 'installation.txt'
This will not create any backup on any existing file, so removing the file mentioned might break the system. There are platform-specific solutions to deal with this. For example, distutils allow you to distribute the package as an RPM package. But there's no universal way to handle it as yet.
The simplest way to remove a package at this time is to erase the files created, and then remove any reference in the easy-install.pth file that is located in the sitepackages folder.
develop
setuptools added a useful command to work with the package. The develop command builds and installs the package in place, and then adds a simple link into the Python site-packages folder. This allows the user to work with a local copy of the code, even though it's available within Python's site-packages folder. All packages that are being created are linked with the develop command to the interpreter.
When a package is installed this way, it can be removed specifically with the -u option, unlike the regular install:
$ sudo python setup.py develop
running develop
...
Adding iw.recipe.fss 0.1.3dev-r7606 to easy-install.pth file
Installed /Users/repos/ingeniweb.sourceforge.net/iw.recipe.fss/trunk
Processing dependencies ...
$ sudo python setup.py develop -u
running develop
Removing
...
Removing iw.recipe.fss 0.1.3dev-r7606 from easy-install.pth file
Notice that a package installed with develop will always prevail over other versions of the same package installed.
test
Another useful command is test. It provides a way to run all tests contained in the package. It scans the folder and aggregates the test suites it finds. The test runner tries to collect tests in the package but is quite limited. A good practice is to hook an extended test runner such as zope.testing or Nose that provides more options.
To hook Nose transparently to the test command, the test_suite metadata can be set to 'nose.collector' and Nose added in the test_requires list:
setup(
...
test_suite='nose.collector',
test_requires=['Nose'],
...
)
register and upload
To distribute a package to the world, two commands are available:
The main PyPI server, previously named the Cheeseshop, is located at and contains over 3000 packages from the community. It is a default server used by the distutils package, and an initial call to the register command will generate a .pypirc file in your home directory.
Since the PyPI server authenticates people, when changes are made to a package, you will be asked to create a user over there. This can also be done at the prompt:
$]:
Now, a .pypirc file will appear in your home directory containing the user and password you have entered. These will be used every time register or upload is called:
[server-index]
username: tarek
password: secret
There is a bug on Windows with Python 2.4 and 2.5. The home directory is not found by distutils unless a HOME environment variable is added. But, this has been fixed in 2.6. To add it, use the technique where we modify the PATH variable. Then add a HOME variable for your user that points to the directory returned by os.path.expanduser('~').
When the download_url metadata or the url is specified, and is a valid URL, the PyPI server will make it available to the users on the project web page as well.
Using the upload command will make the archive directly available at PyPI, so the download_url can be omitted:
Distutils defines a Trove categorization (see PEP 301:) to classify the packages, such as the one defined at Sourceforge. The trove is a static list that can be found at, and that is augmented from time to time with a new entry.
Each line is composed of levels separated by "::":
...
Topic :: Terminals
Topic :: Terminals :: Serial
Topic :: Terminals :: Telnet
Topic :: Terminals :: Terminal Emulators/X Terminals
Topic :: Text Editors Topic :: Text Editors :: Documentation
Topic :: Text Editors :: Emacs
...
A package can be classified in several categories, which can be listed in the classifiers meta-data. A GPL package that deals with low-level Python code (for instance) can use:
Programming Language :: Python
Topic :: Software Development :: Libraries :: Python Modules
License :: OSI Approved :: GNU General Public License (GPL)
Python 2.6 .pypirc Format
The .pypirc file has evolved under Python 2.6, so several users and their passwords can be managed along with several PyPI-like servers. A Python 2.6 configuration file will look somewhat like this:
[distutils]
index-servers =
pypi
alternative-server
alternative-account-on-pypi
[pypi]
username:tarek
password:secret
[alternative-server]
username:tarek
password:secret
repository:
The register and upload commands can pick a server with the help of the -r option, using the repository full URL or the section name:
# upload to
$ python setup.py sdist upload -r alternative-server
# registers with default account (tarek at pypi)
$ python setup.py register
# registers to
$ python setup.py register -r
This feature allows interaction with servers other than PyPI. When dealing with a lot of packages that are not to be published at PyPI, a good practice is to run your own PyPI-like server. The Plone Software Center (see) can be used, for example, to deploy a web server that can interact with distutils upload and register commands.
Creating a New Command
distutils allows you to create new commands, as described in. A new command can be registered with an entry point, which was introduced by setuptools as a simple way to define packages as plug-ins.
An entry point is a named link to a class or a function that is made available through some APIs in setuptools. Any application can scan for all registered packages and use the linked code as a plug-in.
To link the new command, the entry_points metadata can be used in the setup call:
setup(name="my.command",
entry_points="""
[distutils.commands]
my_command = my.command.module.Class
""")
All named links are gathered in named sections. When distutils is loaded, it scans for links that were registered under distutils.commands.
This mechanism is used by numerous Python applications that provide extensibility.
setup.py Usage Summary
There are three main actions to take with setup.py:
Since all the commands can be combined in the same call, some typical usage patterns are:
# register the package with PyPI, creates a source and
# an egg distribution, then upload them
$ python setup.py register sdist bdist_egg upload
# installs it in-place, for development purpose
$ python setup.py develop
# installs it
$ python setup.py install
The alias Command
To make the command line work easily, a new command has been introduced by setuptools called alias. In a file called setup.cfg, it creates an alias for a given combination of commands. For instance, a release command can be created to perform all actions needed to upload a source and a binary distribution to PyPI:
$ python setup.py alias release register sdist bdist_egg upload
running alias
Writing setup.cfg
$ python setup.py release
...
Other Important Metadata
Besides the name and the version of the package being distributed, the most important arguments setup can receive are:
A completed setup.py file for acme.sql would be:
import os
from setuptools import setup, find_packages
version = '0.1.0'
README = os.path.join(os.path.dirname(__file__), 'README.txt')
long_description = open(README).read() + 'nn'
setup(name='acme.sql',
version=version,
description=("A package that deals with SQL, "
"from ACME inc"),
long_description=long_description,
classifiers=[
"Programming Language :: Python",
("Topic :: Software Development :: Libraries ::
"Python Modules"),
],
keywords='acme sql',
author='Tarek',
author_email='tarek@ziade.org',
url='',
license='GPL',
packages=find_packages(),
namespace_packages=['acme'],
install_requires=['pysqlite','SQLAchemy']
)
The two comprehensive guides to keep under your pillow are: The distutils guide at The setuptools guide at | https://www.packtpub.com/books/content/writing-package-python | CC-MAIN-2015-35 | refinedweb | 2,889 | 57.67 |
.
My solution:
#include<iostream> #include<iomanip> #include<fstream> #include<string> using namespace std; int main(int argc, char *argv[]) { ifstream inputFile; ofstream outputFile;. totalCount = strtok(words, "."); // Tokenizes each word and removes period. // Get the name of the file from the user. cout << "Enter the name of the file: "; getline(cin, inFile); // Open the input file. inputFile.open(inFile); // If successfully opened, process the data. if(inputFile) { while(!inputFile.eof()) { lineCount++; // Increment each line. // Read every word in each line. while(getline(inFile, words[100][16])) { // If there is a match, increment the associated count. if(strcmp(words[100][16], counter[100]) == 0) { counter[100]++; totalCount++; // Increment the total number of words; totalCount = strtok(NULL, " "); // Removes the whitespace. // If there is a tie for longest word, get the first or last word found. if(strcmp(inFile, longest) == 0) { longest[16] = ""; } // If there is a tie for shortest word, get the first or last word found. else if(strcmp(inputFile,] << endl;; // Close the output file. outputFile.close(); return 0; }
Right now, my code has a few errors and I'm not sure how to fix them. Is there anything I need to change? | https://www.daniweb.com/programming/software-development/threads/463091/am-i-writing-this-code-correctly-for-this-program | CC-MAIN-2018-43 | refinedweb | 191 | 59.8 |
Practical Graphs on Rails: Chartkick in Practice
Ruby
In a previous article , I covered the basics of Chartkick – a great library to easily render graphs in Rails apps. The article gained some attention so I decided to cover a bit more and show how Chartkick, along with Groupdate, can be used to solve a real-world task.
Just to remind you, Chartkick is a gem that integrates with Rails and provides methods to quickly render graphs based on your data. This gem supports Chart.js, Google Charts, and Highchart adapters. Chartkick comes with out-of-the-box support for Groupdate, which simplifies writing some complex grouping queries.
In this post I will show you how to build an app visualizing click counts by day, month, or year for various items. Users will be able to select the date range with the help of a handy date picker and the resulting graph’s scale will change accordingly.
The source code can be found on GitHub.
The working demo can be found on Heroku.
Preparations
For this demo I will be using Rails 5, but the steps are nearly identical for Rails 3 and 4.
Okay, so the idea is to build an app that hosts a number of “items” – it does not really matter what these items are, but suppose we sell fruits via an online store. Our customer is very interested to see how many clicks each fruit garners, asking us to store that information and visualize it somehow. They want to see how many clicks were done each day for each item with the ability to change the date range to things like “The last six months” or “The last year.”
OK, the task is clear and we’ll dive into the code now.
Create a new Rails app called
Tracker without the default testing suite:
$ rails new Tracker -T
Drop in these gems:
Gemfile
[...] gem 'chartkick' gem 'groupdate' gem 'bootstrap-sass' gem 'pg' [...]
Chartkick is, of course, our main tool for today. groupdate is a nice addition allowing to use advanced queries with ease. bootstrap-sass will be used for styling and pg is the PostgreSQL adapter. Note that Groupdate will not work with SQLite 3!
Install your gems now:
$ bundle install
Don’t forget to create a new Postgres database and configure the app to work with it. You may use this sample config to get started:
config/database.yml
development: adapter: postgresql encoding: unicode database: tracker pool: 5 username: "PG_USER" password: "PG_PASSWORD" host: localhost port: 5432
On top of that, we’ll also need some additional assets:
Highcharts is a great library to build interactive graphs and I am going use it in this demo. Still, you may stick with either Chart.js (which is used by default starting from Chartkick v2) or Google Charts. Bootstrap Datepicker is an add-on for Bootstrap that we are going to use to build the form.
Now hook up all these assets (note that Turbolinks should be placed last):
javascripts/application.js
//= require jquery //= require jquery_ujs //= require datepicker //= require highcharts //= require chartkick //= require turbolinks
stylesheets/application.scss
@import 'bootstrap-sprockets'; @import 'bootstrap'; @import 'datepicker';
Great! Of course, we’ll need data and a place to store them, so let’s proceed to the next section and create models.
The Models
Generate two very simple models:
Item and
ClickTrack
$ rails g model Item title:string $ rails g model ClickTrack item:belongs_to $ rake db:migrate
Item is our product and click track is created every time the item was clicked. We are not going to code this logic but, as you see, it is really simple. Make sure that you’ve set up the one-to-many relation between the models:
models/item.rb
class Item < ApplicationRecord has_many :click_tracks end
models/click_track.rb
class ClickTrack < ApplicationRecord belongs_to :item end
Of course, we need some sample data. I won’t do anything fancy here, but just add two items with a bunch of click tracks that have a random creation date:
db/seeds.rb
%w(apple cherry).each do |item| new_item = Item.create({title: item}) 1000.times do new_item.click_tracks.create!({created_at: rand(3.years.ago..Time.now) }) end end
Load sample data into the database:
$ rails db:seed # use rake for Rails < 5
Once again, don’t forget that starting from Rails version 5 all commands live under the
rails namespace:
$ rails db:migrate # use rake for Rails < 5
The Routes and the Main Page
Let’s also set up the basic routes and prepare the home page of our app. As long as the click tracks are directly related to items and do not make much sense on their own, I want the
click_tracks resource to be nested:
config/routes.rb
[...] resources :items, only: [:index] do resources :click_tracks, only: [:index] end root 'items#index' [...]
Create two controllers:
items_controller.rb
class ItemsController < ApplicationController def index @items = Item.all end end
click_tracks_controller.rb
class ClickTracksController < ApplicationController def index @item = Item.find_by(id: params[:item_id]) end end
They are really basic so nothing to comment here. Now the view for the root page:
views/items/index.html.erb
<h1>Items</h1> <ul><%= render @items %></ul>
And the corresponding partial
views/items/_item.html.erb
<li> <%= item.title %> <%= link_to 'View clicks', item_click_tracks_path(item), class: 'btn btn-primary' %> </li>
As long as we have the nested routes, we have to use the
item_click_tracks_path helper, not the
click_tracks_path. You may read more here about nested resources.
Lastly, let’s also wrap the whole page’s content into the
div equipped with the Bootstrap’s class:
views/layouts/application.html.erb
[...] <body> <div class="container"> <%= yield %> </div> </body> [...]
Building the Form
Great, the first step is done and we are ready to build the main feature now. Speaking of the form, it definitely has to contain two inputs: one for the start date and another one for the end date. Having them in place, the user may choose the time period for which to to display click tracks. These inputs will be powered by Bootstrap’s styling and the Datepicker plug-in:
views/click_tracks/index.html.erb
<h1>Click tracking</h1> <div id="event_period" class="row"> <%= form_tag api_item_click_tracks_path(@item), remote: true do %> <div class="col-sm-1"> <label for="start_date">Start date</label> </div> <div class="col-sm-3"> <div class="input-group"> <input type="text" class="actual_range form-control datepicker" id="start_date" name="start_date"> <div class="input-group-addon"> <span class="glyphicon glyphicon-th"></span> </div> </div> </div> <div class="col-sm-1 col-sm-offset-1"> <label for="end_date">End date</label> </div> <div class="col-sm-3"> <div class="input-group"> <input type="text" class="actual_range form-control datepicker" id="end_date" name="end_date"> <div class="input-group-addon"> <span class="glyphicon glyphicon-th"></span> </div> </div> </div> <div class="col-sm-2"> <%= submit_tag 'Show!', class: 'btn btn-primary' %> </div> <% end %> </div>
This code is pretty long, but very simple. We add the form that should be submitted asynchronously to the
api_item_click_tracks_path (this route does not exist yet). Inside the form there are two inputs with the ids of
#start_date and
#end_date.
To make them a bit prettier I am using the
.input-group-addon class that adds a small icon next to each
input. Lastly, there is a submit button to, well, submit the form.
Now we need the routes:
config/routes.rb
[...] namespace :api do resources :items, only: [] do resources :click_tracks, only: [:create] do collection do get 'by_day' end end end end [...]
We namespace these routes under
api. The corresponding actions will be coded in the next steps.
To take advantage of the Datepicker plug-in, place the following code in your view (of course, you can also place it in a separate CoffeeScript file):
views/click_tracks/index.html.erb
[...] <script data-turbolinks-track> $(document).ready(function() { $('#event_period').datepicker({ inputs: $('.actual_range'), startDate: '-3y', endDate: '0d', todayBtn: 'linked', todayHighlight: 'true', format: 'yyyy-mm-dd' }); }); </script> [...]
We equip the whole form with this new functionality and provide the actual inputs using the
inputs option. Also, the
startDate is set to 3 years ago (because, as you remember, click tracks’ creation dates were defined as
rand(3.years.ago..Time.now)) and the
endDate to
0d meaning that it should contain today’s date. Then, display the “Today” button, highlight today’s date, and provide the date format. Great!
You can boot the server and observe the result now. Note that when the drop-down is open, you may click on the month or the year to select another one.
Displaying the Graph
Okay, it is high time for today’s star to emerge. Let’s display the graph in a separate partial (so we can re-use the markup later):
views/click_tracks/index.html.erb
[...] <%= render 'graph' %>
views/click_tracks/_graph.html.erb
<div id="graph"> <%= stat_by(@start_date, @end_date) %> </div>
stat_by is a helper method (we are going to create it soon) that accepts start and end dates. When the page is loaded, these dates are not set, so we have to take care of such a scenario ourselves.
helpers/click_tracks_helper.rb
module ClickTracksHelper def stat_by(start_date, end_date) start_date ||= 1.month.ago end_date ||= Time.current end end
Here we use the so-called “nil guards” (
||=) to set the default values. Let’s display the chart relying on Chartkick’s asynchronous loading feature:
helpers/click_tracks_helper.rb
module ClickTracksHelper def stat_by(start_date, end_date) start_date ||= 1.month.ago end_date ||= Time.current line_chart by_day_api_item_click_tracks_path(@item, start_date: start_date, end_date: end_date), basic_opts('Click count', start_date, end_date) end end
So, instead of loading the chart during the page load, it is done in the background which is, of course, better in terms of user experience. In order for this to work, you need to set up an action in your app that presents the properly formatted data and hook up jQuery or Zepto.js. In this case we use the
by_day_api_item_click_tracks_path that was already set up but the action is not coded – it will be in the next step.
The
basic_opts method, as the name implies, prepares some options (including the library-specific ones) for the graph:
helpers/click_tracks_helper.rb
private def basic_opts(title, start_date, end_date) { discrete: true, library: { title: {text: title, x: -20}, subtitle: {text: "from #{l(start_date, format: :medium)} to #{l(end_date, format: :medium)}", x: -20}, yAxis: { title: { text: 'Count' } }, tooltip: { valueSuffix: 'click(s)' }, credits: { enabled: false } } } end
The
l method is an alias for the
localize that formats the timestamp. There is no format called
:medium by default so let’s add one:
config/locales/en.yml
en: time: formats: medium: '%d %B %Y'
Once again, notice that when using the other graph adapters, options will be differnt. Refer to your adapter’s docs for more details.
Controller Actions
The front end is ready and now it’s time to take care of the back end. As long as we’ve namespaced our routes under
api, the new controller files has to be placed inside the api folder:
controllers/api/click_tracks_controller.rb
class Api::ClickTracksController < Api::BaseController end
Note, however, that
Api::ClickTracksController inherits from
Api::BaseController, as will all
Api::* controllers. For example, in my production app I have two somewhat similar controllers that share these methods.
controllers/api/base_controller.rb
class Api::BaseController < ApplicationController end
What do we want to happen inside the
Api::BaseController? It is going to host two callbacks: one to load the necessary data (the item and its click tracks) and another one to format the received dates (because the user may enter them by hand or not provide any date at all.)
Data loading is not a problem for us:
controllers/api/base_controller.rb
[...] before_action :load_data private def load_data @item = Item.includes(:click_tracks).find_by(id: params[:item_id]) @click_tracks = @item.click_tracks end [...]
As for formatting the dates, the method is going to be a bit more complex:
controllers/api/base_controller.rb
[...] before_action :load_data before_action :format_dates private def format_dates @start_date = params[:start_date].nil? || params[:start_date].empty? ? 1.month.ago.midnight : params[:start_date].to_datetime.midnight @end_date = params[:end_date].nil? || params[:end_date].empty? ? Time.current.at_end_of_day : params[:end_date].to_datetime.at_end_of_day @start_date, @end_date = @end_date, @start_date if @end_date < @start_date end [...]
If one of the dates is empty, we populate is with a default value. Note the usage of the pretty self-explantory
midnight and
at_end_of_day methods. If the date is not empty, convert it to datetime (because initially it is a string). Lastly, we swap the date if the end date comes after the start date.
Now code the
create action that fires when we submit the form. Of course, it responds with Javascript as the form submission is done via AJAX:
controllers/api/click_tracks_controller.rb
[...] def create respond_to do |format| format.js end end [...]
The actual Javascript is simple: just replace the old chart with a new one. That’s where the partial created earlier comes in handy:
views/api/click_tracks/create.js.erb
$('#graph').replaceWith('<%= j render 'click_tracks/graph' %>');
The last step is to code an action that prepares data for our graph. As you recall, we have the following routes:
config/routes.rb
[...] namespace :api do resources :items, only: [] do resources :click_tracks, only: [:create] do collection do get 'by_day' end end end end [...]
Therefore, the action should be called
by_day. We want it to render JSON containing information about how many clicks happened on each day.
controllers/api/click_tracks_controller.rb
[...] def by_day clicks = @click_tracks.group_by_day('created_at', format: '%d %b', range: @start_date..@end_date).count render json: [{name: 'Click count', data: clicks}].chart_json end [...]
group_by_day is a method introduced by the groupdate gem that groups click tracks by creation date. The
count method, as you’ve probably guessed, counts how many clicks happened on each day. As a result, the
click variable is going to contain an object like
{'07 Jun': 10, '08 Jun': 4} (the keys’ formatting is controlled by the
:format option).
chart_json is a special Chartkick method to prepare the JSON to be visualized.
Suppose, however, that a user chooses 2 years as the time range: with the current method’s implementation we are going to display more than 700 days in one graph which is not really helpful. Instead, let’s check the range and do dynamic grouping based on it.
First of all, add two more methods to the
BaseController:
controllers/api/base_controller.rb
[...] private def by_year? @end_date - (1.year + 2.days) > @start_date end def by_month? @end_date - (3.month + 2.days) > @start_date end [...]
These methods simply check the length of the selected period – we’ll use them now in the
by_day method:
controllers/api/click_tracks_controller.rb
[...] def by_day opts = ['created_at', {range: @start_date..@end_date, format: '%d %b'}] method_name = :group_by_day if by_year? opts[1].merge!({format: '%Y'}) method_name = :group_by_year elsif by_month? opts[1].merge!({format: '%b %Y'}) method_name = :group_by_month end clicks = @click_tracks.send(method_name, *opts).count render json: [{name: 'Click count', data: clicks}].chart_json end [...]
Here we prepare an array of the arguments that will be passed to one of the groupdate methods (
group_by_day,
group_by_month or
group_by_year). Next, set the default method to call and do some checks. If the range is greater than a month, update the formatting options so that only a year or a month and a year are being displayed, then dynamically call the method.
*opts will take an array and convert it to the list of arguments. With this code in place, you can easily define your own conditions and grouping rules.
Now the job is done and you may observe the final result!
Conclusion
In this article we continued the discussion of Chartkick and Groupdate and used them in practice. To make the user experience a bit more pleasant, we’ve also utilized Bootstrap’s Datepicker plug-in. The code listed here can be further extended. For example, if you wish to visualize the display count for each item, that’s easy to do as well.
If you have any other questions left, don’t hesitate to contact me – I’m really glad when you send your feedback. As always, thanks.
New books out now!
🤓 Ok. When did a code editor from Microsoft become kinda cool!?
Popular Books
Visual Studio Code: End-to-End Editing and Debugging Tools for Web Developers
Form Design Patterns
Jump Start Git, 2nd Edition | https://www.sitepoint.com/graphs-on-rails-chartkick-in-practice/ | CC-MAIN-2020-24 | refinedweb | 2,700 | 64.91 |
/* Updating of data structures for redisplay.
Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 97, 1998 <signal.h>
#include <config "frame.h"
#include "window.h"
#include "commands.h"
#include "disptab.h"
#include "indent.h"
#include "intervals.h"
#include "blockinput.h"
#include "process.h"
#include "keyboardndef PENDING_OUTPUT_COUNT
#define PENDING_OUTPUT_COUNT(FILE) ((FILE)->_ptr - (FILE)->_base)
#endif
#endif /* not __GNU_LIBRARY__ */
/* Structure to pass dimensions around. Used for character bounding
boxes, glyph matrix dimensions and alike. */
struct dim
{
int width;
int height;
};
/* Function prototypes. */));
static void swap_glyphs_in_rows P_ ((struct glyph_row *, struct glyph_row *));
static void swap_glyph_pointers P_ ((struct glyph_row *, struct glyph_row *));
static int glyph_row_slice_p P_ ((struct glyph_row *, struct glyph_row *)); void update_window_line P_ ((struct window *, int));
static void update_marginal_area P_ ((struct window *, int, int));
static void update_text_area P_ ((struct window *, int));
static void make_current P_ ((struct glyph_matrix *, struct glyph_matrix *,
int));
static void mirror_make_current P_ ((struct window *, int));
void check_window_matrix_pointers P_ ((struct window *));;
/* The currently selected frame. In a single-frame version, this
variable always holds the address of the_only_frame. */
struct frame . */
#if GLYPH_DEBUG top_line_changed_p = 0;
int top_line_p = 0;
int left = -1, right = -1;
int window_x, window_y, window_width, window_height;
/* See if W had a top line that has disappeared now, or vice versa. */
if (w)
{
top_line_p = WINDOW_WANTS_TOP_LINE_P (w);
top_line_changed_p = top_line_p != matrix->top_line_p;
}
matrix->top_line_p = top
&& !top
|| top). | https://emba.gnu.org/emacs/emacs/-/blame/2febf6e0335cb2e6ae5aff51cd1b356e0a8e2629/src/dispnew.c | CC-MAIN-2022-33 | refinedweb | 211 | 60.41 |
A meeting of the foundations
We're back from chilling at Penguicon 2.0 in Novi, Michigan a couple of weeks ago. In this issue, we talk about the meeting between the GNOME and Mozilla foundations on better collaboration, and we show you how to use OS X icons with GNOME or KDE.
GNOME and Mozilla Foundations meet
On April 21st, representatives from GNOME and the Mozilla Foundation met and talked on how they could collaborate better. Brendan Eich from mozilla.org originally had some ideas on how such a synergy could work. While they discussed working together more closely and forming some sort of alliance, it is too early to definitively describe what this kind of collaboration will mean for users. One item on the agenda is the need for innovation and evolution of the Linux/GNOME platform into a cost-effective, standards-compliant, open-source platform.
The web, while it is stagnant currently, is likely to change once Longhorn is released and gains a sizable following. For that reason, Mozilla and the Gecko rendering engine, which is the standard for the GNOME desktop, cannot stagnate; it needs to adapt and support up-and-coming technologies such as XAML. Both foundations would like for the GNOME/Mozilla platform to become a viable competitor on the desktop market, and with Microsoft combining the web and desktop rendering teams into one, Nat Friedman of GNOME believes that the options are:
- Gain market share before Longhorn comes along
- Clone XAML
- Develop something new, cross-platform, and offering a rich web experience as well as a great native integration story, and get?
Both foundations believe that due to the delayed Longhorn release, now is the right time for Linux to establish a push into the desktop market.
Other things discussed where methods to make sure that technology is not worked on in parallel by both groups, and to make sure that technology, as well as code libraries and APIs, can be used portably. Firefox was discussed as well. Work done on that browser by IBM, Sun Microsystems, as well as others, will be merged with the codebase, and Jeff Waugh entertained the idea that Epiphany could serve as the Linux port of Firefox.
For those interested, the detailed minutes of the meeting are available on foundation-list.
A new way to find bugs
Bugs plague all software, no matter whether big or small, open-source or closed. Reporting bugs is a great way to help your favorite software project. However, many users including people that should know better (me), fail to report many bugs they encounter, because the process is often an annoyance.
This is where the Berkeley's Cooperate Bug Isolation Project comes in. The project provides specially-modified RPM packages of software which monitor their operation and report successful operations as well as failures back to the developers. The project provides RPM packages for Red Hat 9, which are available from their page. Check there for yum and Red Carpet information.Currently, these instrumented RPMs are available for Evolution, GAIM, gnumeric and rhythmbox, as well as some older packages for Ximian Desktop 2.
Ensure that you check out the project's Privacy section if you're worried about what data is being collected. In order for the project to be more successful, they need more users. Projects like Rhythmbox have already been able to use this data to fix several critical bugs in their software.
TTT: Tools, Tips and Tweaks ? converting Macintosh icons to PNG for a prettier desktop
I like eye candy, especially in icon form. That's why I was excited to see that The Icon Factory released some Matrix icons to celebrate the release of the Matrix Revolutions DVD. Unfortunately, the only available icon formats were standard Windows icons (.ico) and Mac OS X-specific formats. Neither of these were useful to me, so I set out to convert these icons to a more portable format?? PNG.
I chose to use the standard Macintosh Icons available from the Icon Factory. They turned out to be the easiest format for me to convert and still retain the alpha transparency.
You will need to download and install a few programs in order for this conversion to work. For those of you morally opposed to using close-source software, shame on you for even considering using Macintosh icons on your Linux desktop. Begone with you! (Just kidding, we still love you.)
First, you need to get a trial version of StuffIt for Linux. This is the closed-source software I mentioned above. As far as I know, this is the only package that will extract the Macintosh .bin files under linux. I'd love to be proven wrong, though.
Next, download yourself a copy of icns2png. This handy little tool is the key to success.
I've written a small shell script that will do all of the manual work that goes into successfully converting the Macintosh icons to PNG. You can skip ahead and download the final product or keep reading to see the process in action.
Extracting the .bin/.hqx
The first step in the process is to extract the data to disk so we can work with it. Unstuffing the data is actually a two-step process. The first time we unstuff the file, it deflates into a .data and .info file. I'm not sure what specifically is contained in the .info file, but we can disregard it. The second step will actually extract the icon data to a temporary directory.
tmp="`mktemp -d -t "XXXXXX"`" unstuff -q -d=$tmp $1 cd $tmp sit=`find . -type f -maxdepth 1 -name '*.data' -printf '%f'` unstuff -q -e=unix -m=auto -t=on "$sit" cd $OLDPWD
Fixing the filename
When unstuff extracts the icon files, it leaves a carriage return (\r) embedded within the filename. Whoops. Our next step is to find all of the icon files and strip the control codes from the filename.
find "$tmp" -type f -name '*' -print | while read name ; do if echo "`file "$name"`" | grep 'MacBinary' > /dev/null 2>&1; then newname="`echo $name | tr -d [:cntrl:]`" # Strip control codes from the name if [ ! -f "$newname" ]; then mv "$name" "$newname" fi fi done
Converting to PNG
Now that the filenames are fixed, we can get to our ultimate goal, converting the icons to png. This is a straightfoward process. Just tell icns2png what icon to convert and it will create the PNG . You may see a segmentation fault as you run icns2png. That just means that the file it tried to convert was not a valid icon.
icns2png "$newname" > /dev/null 2>&1
The final step will move the converted PNG to a new directory, based on the name of the archive holding the icons. The naming convention of the icons changes between icon sets, so coming up with a common naming theme is a more complex task. I decided to simply name the new icons numerically to prevent duplicate files from being created.
stone@durin:~/icons/woad_icn$ ls 1.png 11.png 13.png 2.png 4.png 6.png 8.png 10.png 12.png 14.png 3.png 5.png 7.png 9.png
And you're done. All of the OS X Icons have now been converted to PNG. You can download the complete script here. Happy theming!
/dev/random
- As reported by TheInq, SpecOps Labs, a Philippine based company, is claiming to be working on software that'll allow Windows software to be run on Linux. Sound like a rebadged wine to you? That's what we believe as well, but only time will tell.
- Another open source success story. As reported by Computerworld, weather.com has moved to an all open-source backend based on commodity hardware running on Linux and MySQL.
- Daniel Robbins, Chief Gentoo Architect, has put in his resignation from the Gentoo Project.
- Debian Sarge delayed until 2005: due to the ammendment of the Debian Social Contract, changes will have to be made to the distribution and the installer, so that it is highly unlikely for Sarge to be released this year.
- Red Hat 9 reaches its end-of-life for official support/errata from Red Hat, but there'll still be support provided by the Fedora Legacy Project, which will continue to support older Red Hat (and later Fedora) distributions well past their EOL. So even if you still need to run RH9, you'll be able to get security patches from there. | http://arstechnica.com/open-source/news/2004/04/linux-20040429.ars | crawl-002 | refinedweb | 1,419 | 62.98 |
.
You can use Adman65/nettuts for a successful login. Be sure to use bad credentials so you can see how everything works.
What We're Making
Getting Started
We’re going to start by creating a dummy application that has a public and private page. The root url is the public page. There’s a login link on the public page. If the user logs in successfully, they’re redirected to the private page. If not, they’re redirected back to the login form. The private page shows the user name. We’ll use this as the starting point for ajaxifying the site.
The first step is using the rails command to generate a new application, then install and setup up authlogic.
$ cd into-a-directory $ rails unobtrusive-login
Add authlogic.
# /config/environment.rb config.gem 'authlogic'
Now install the gems.
$ sudo gem install gemcutter $ sudo gem tumble $ sudo rake gems:install
Next create a user model and add the required authlogic columns to the migration.
$ ./script/generate model User exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/user.rb create test/unit/user_test.rb create test/fixtures/users.yml create db/migrate create db/migrate/20100102082657_create_users.rb
Now, add the columns to the new migration.
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :login, :null => false t.string :crypted_password, :null => false t.string :password_salt, :null => false t.string :persistence_token, :null => false t.timestamps end end def self.down drop_table :users end end
Migrate the database.
$ rake db:migrate
Include authlogic in the user model.
# /app/models/user.rb class User < ActiveRecord::Base acts_as_authentic end
Now we can create a user. Since this is a demo app, web based functionality for signing up isn’t required. So open up the console and create a user:
$ ./script/console >> me = User.create(:login => 'Adman65', :password => 'nettuts', :password_confirmation => 'nettuts')
Now we have a user in the system, but we have no way to login or logout. We need to create the models, controllers, and views for this. Authlogic has its own class for tracking logins. We can use the generator for that:
# create the user session $ ./script/generate UserSession
Next we need to generate the controller that will login/logout users. You can create sessions just like any other resource in Rails.
# create the session controller $ ./script/generate controller UserSessions
Now set its contents to:
# /app/controllers/user_sessions_controller.rb class UserSessionsController < ApplicationController def new @user_session = UserSession.new end def create @user_session = UserSession.new(params[:user_session]) if @user_session.save flash[:notice] = "Login successful!" redirect_back_or_default user_path else render :action => :new end end end
It looks exactly the same as a controller that was generated via scaffolding. Now create the users controller which has public and private content. Generate a users controller. Inside the controller we’ll use a before filter to limit access to the private areas. The index action is public and show is private.
# create the users controller $ ./script/generate controller users
Update its contents:
# /app/controllers/users_controller.rb class UsersController < ApplicationController before_filter :login_required, :only => :show def index end def show @user = current_user end private def login_required unless current_user flash[:error] = 'You must be logged in to view this page.' redirect_to new_user_session_path end end end
You should notice that current_user is an undefined method at this point. Define these methods in ApplicationController. Open up application_controller.rb and update its contents:
# application controller class ApplicationController < ActionController::Base helper :all # include all helpers, all the time protect_from_forgery # See ActionController::RequestForgeryProtection for details # From authlogic filter_parameter_logging :password, :password_confirmation helper_method :current_user_session, :current_user private def current_user_session @current_user_session ||= UserSession.find end def current_user @current_user ||= current_user_session && current_user_session.user end end
At this point the models and controllers are complete, but views aren’t. We need to create views for a login form and the public and private content. We’ll use the nifty-generators gem to create a basic layout.
$ sudo gem install nifty-generators $ ./script/generate nifty_layout
Time to create the login form. We’re going to use a partial for this because in the future we’ll use the partial to render just the login form in the modal box. Here’s the code to create the login form. It’s exactly the same as if you were creating a blog post or any other model.
# create the login views # /app/views/user_sessions/_form.html.erb <% form_for(@user_session, :url => user_session_path) do |form| %> <%= form.error_messages %> <p> <%= form.label :login %> <%= form.text_field :login %> </p> <p> <%= form.label :password %> <%= form.password_field :password %> </p> <%= form.submit 'Login' %> <% end %>
Render the partial in the new view:
# /app/views/user_sessions/new.html.erb <% title 'Login Please' %> <%= render :partial => 'form' %>
Create some basic pages for the public and private content. The index action shows public content and show displays private content.
# create the dummy public page # /app/views/users/index.html.erb <% title 'Unobtrusive Login' %> <p>Public Facing Content</p> <%= link_to 'Login', new_user_session_path %>
And for the private page:
# create the dummy private page # /app/views/users/show.html.erb <% title 'Welcome' %> <h2>Hello <%=h @user.login %></h2> <%= link_to 'Logout', user_session_path, :method => :delete %>
Delete the file /public/index.html and start the server. You can now log in and logout of the application.
$ ./script/server
Here are some screenshots of the demo application. The first one is the public page.
Now the login form
And the private page
And finally, access denied when you try to visit
The AJAX Login Process
Before continuing, we need to understand how the server and browser are going to work together to complete this process. We know that we’ll need to use some JavaScript for the modal box and the server to validate logins. Let’s be clear on how this is going to work. The user clicks the login link, then a modal box appears with the login form. The user fills in the form and is either redirected to the private page, or the modal box is refreshed with a new login form. The next question is how do you refresh the modal box or tell the browser what to do after the user submits the form? Rails has respond_to blocks. With respond_to, you can tell the controller to render different content if the user requested XML, HTML, JavaScript, YAML etc. So when the user submits the form, the server can return some JavaScript to execute in the browser. We’ll use this render a new form or a redirect. Before diving any deeper, let’s go over the process in order.
- User goes to the public page
- User clicks the login link
- Modal box appears
- User fills in the form
- Form is submitted to the server
- Server returns JavaScript for execution
- Browser executes the JavaScript which either redirects or updates the modal box.
That’s the high level. Here’s the low level implementation.
- User visits the public page
- The public page has some JavaScript that runs when the DOM is ready that attaches JavaScript to the login link. That javscript does an XMLHTTPRequest (XHR from now on) to the server for some JavaScript. The JavaScript sets the modal box’s content to the form HTML. The JavaScript also does something very important. It binds the form’s submit action to an XHR with POST data to the form’s action. This allows the user to keep filling the login form in inside the modal box.
- Modal box now has the form and required JavaScript
- User clicks ‘Login’
- The submit() function is called which does a POST XHR to the form’s action with its data.
- Server either generates the JavaScript for the form or the redirect
- Browser receives the JavaScript and executes it. The browser will either update the modal box, or redirect the user through window.location.
Taking a Peak at the AJAX Ready Controller
Let’s take a look at the new structure for the UserSessions controller.
class UserSessionsController < ApplicationController layout :choose_layout def new @user_session = UserSession.new end def create @user_session = UserSession.new(params[:user_session]) if @user_session.save respond_to do |wants| wants.html { redirect_to user_path(@user_session.user) } wants.js { render :action => :redirect } # JavaScript to do the redirect end else respond_to do |wants| wants.html { render :new } wants.js # defaults to create.js.erb end end end private def choose_layout (request.xhr?) ? nil : 'application' end end
As you can see the structure is different. Inside the if save, else conditional, respond_to is used to render the correct content. want.xx where xx is a content type. By default Prototype and jQuery request text/JavaScript. This corresponds to wants.js. We’re about ready to get started on the AJAX part. We won’t use any plugins except ones for modal boxes. We’ll use Facebox for jQuery and ModalBox for Prototype.
Prototype
Rails has built in support for Prototype. The Rail’s JavaScript helpers are Ruby functions that generate JavaScript that use Prototype. This technique is known as RJS (Ruby JavaScript). One example is remote_form_for which works like the standard for_for adds some JS bound to onsubmit that submits to the form to its action using its method with its data. I won’t use RJS in this article since I want to demonstrate vanilla JS. I think by using pure JS and eliminating the JS helpers the article will be more approachable by less experienced developers. That being said, you could easily accomplish these steps using RJS/Prototype helpers if you choose.
Adding Prototype to the application is very easy. When you use the rails command, it creates the Prototype and scriptaculous files in /public/JavaScripts. Including them is easy. Open up /app/views/layouts/application.erb and add this line inside the head tag:
<%= JavaScript_include_tag :defaults %>
JavaScript_include_tag creates script tags for default files in /public/JavaScripts, most importantly prototype.js, effects.js, and application.js. effects.js is scriptaculous. application.js is a file you can use to keep application specific JS. Now we need a modal box plugin. We’re going to use this. Its a very nice modal box plugin inspired by OSX. The source is hosted on GitHub, so you’ll have to clone and move the files in your project directory. For example:
$ cd code $ git clone git://github.com/okonet/modalbox.git $ cd modalbox # move the files in the correct directories. # move modalbox.css into /public/stylesheets # move modalbox.js into /public/JavaScripts # move spinner.gif into /public/images
Now include the stylesheets and JavaScript in your application.
<%= stylesheet_link_tag ‘application’ %> <%= stylesheet_link_tag ‘modalbox’ %> <%= JavaScript_include_tag :defaults %> <%= JavaScript_include_tag ‘modalbox’%>
Now let’s get our login link to open a modalbox. In order to do this we need to add some JavaScript that runs when the DOM is ready that attaches the modalbox to our link. When the user clicks the login link, the browser will do a GET to /user_sessions/new which contains the login form. The login link uses the #login-link selector. Update the login link to use the new id in /app/views/users/index.html.erb. Modify the link_to function like this:
<%= link_to 'Login', new_user_session_path, :id => 'login-link' %>
That gives us a#login-link. Now for the JavaScript to attach a modalbox. Add this JS in /public/JavaScripts/application.js
document.observe('dom:loaded', function() { $('login-link').observe('click', function(event) { event.stop(); Modalbox.show(this.href, {title: 'Login', width: 500} ); }); })
There’s some simple JS for when the user clicks the link a modal box opens up with the link’s href. Refer to the modalbox documentation if you’d like more customization. Here’s a screenshot:
Notice that inside the modal box looks very similar to our standard page. Rails is using our application layout for all HTML responses. Since our XHR’s want HTML fragments, it make sense to render without layouts. Refer back to the example controller. I introduced a method for determining the layout. Add that to UserSessionsController to disable layout for XHR’s.
class UserSessionsController < ApplicationController layout :choose_layout def new @user_session = UserSession.new end def create @user_session = UserSession.new(params[:user_session]) if @user_session.save flash[:notice] = "Login successful!" redirect_to user_path else render :action => :new end end def destroy current_user_session.destroy flash[:notice] = "Logout successful!" redirect_to root_path end private def choose_layout (request.xhr?) ? nil : 'application' end end
Refresh the page and click the link you should get something like this:
Fill in the form and see what happens. If you fill in the from with bad info, you’re redirected outside the modal box. If you login correctly you’re redirected normally. According the requirements the user should be able to fill out the form over and over again inside the modal box until they login correctly. How can we accomplish this? As described before we need to use AJAX to submit data to the server, then use JavaScript to update the modal box with the form or do a redirection. We know that the modalbox does a GET for HTML. After displaying the initial modalbox, we need to write JS that makes the form submits itself AJAX style. This allows the form to submit itself inside the modal box. Simply adding this code after the modal box is called won’t work because the XHR might not have finished. We need to use Modalbox’s afterLoad callback. Here’s the new code:
document.observe('dom:loaded', function() { $('login-link').observe('click', function(event) { event.stop(); Modalbox.show(this.href, {title: 'Login', width: 500, afterLoad: function() { $('new_user_session').observe('submit', function(event) { event.stop(); this.request(); }) }} ); }); })
Form#request is a convenience method for serializing and submitting the form via an Ajax.Request to the URL of the form’s action attribute—which is exactly what we want. Now you can fill in the form inside the modal without it closing. The client side is now complete. What about the server side? The client is submitting a POST wanting JS back. The server needs to decide to either return JavaScript to update the form or render a redirect. In the UserSessionsController we’ll use respond_to to handle the JS request and a conditional to return the correct JS. Let’s begin by handling the failed login case. The server needs to return JS that updates the form, and tells the new form to submit over ajax. We’ll place this template in /app/views/users_sessions/create.js.erb. Here’s the structure for the new create action:
def create @user_session = UserSession.new(params[:user_session]) if @user_session.save flash[:notice] = "Login successful!" redirect_to user_path else respond_to do |wants| wants.html { render :new } wants.js # create.js.erb end end end
Now let’s fill in create.js.erb:
$('MB_content').update("<%= escape_JavaScript(render :partial => 'form') %>"); Modalbox.resizeToContent(); $('new_user_session').observe('submit', function(event) { event.stop(); this.request(); });
First we update the content to include the new form. Then we resize the modal box. Next we ajaxify the form just as before. Voilla, you can fill in the form as many times as you want.
Next we need to handle the redirection case. Create a new file in /app/views/users_sessions/redirect.js.erb:
window.location=”<%= user_path %>”;
Now, update the create action to handle the redirection process:
def create @user_session = UserSession.new(params[:user_session]) if @user_session.save respond_to do |wants| wants.html do flash[:notice] = "Login successful!" redirect_to user_path end wants.js { render :redirect } end else respond_to do |wants| wants.html { render :new } wants.js # create.js.erb end end end
And that’s it! Now try login with correct credentials and you’re redirected to the private page. For further learning, try to add a spinner and notification telling the user the form is submitting or they’re being redirect. The application still works if the user has JavaScript disabled too.
jQuery
Since I’ve already covered the Prototype process, so I won’t go into the same detail as before. Instead, I will move quickly describing the alternate JavaScript to add to the application. The jQuery vesion will have the exact same structure as the Prototype version. All we need to change is what’s in application.js, create.js.erb, and the JavaScript/css includes.
First thing we need to do is download jQuery and Facebox. Move jQuery into /public/JavaScripts as jquery.js. For facebox move the images into /public/images/, stylesheets into /public/stylesheets, and finally the JS into /public/JavaScripts. Now update /app/views/layouts/application.html.erb to reflect the changes:
<head> <title><%= h(yield(:title) || "Untitled") %></title> <%= stylesheet_link_tag 'facebox' %> <%= stylesheet_link_tag 'application' %> <%= JavaScript_include_tag 'jquery' %> <%= JavaScript_include_tag 'facebox' %> <%= JavaScript_include_tag 'application' %> </head>
Facebox comes with a default stylesheet which assumes you have your images in /facebox. You’ll need to update these selectors in facebox.css like so:
#facebox .b { background:url(/images/b.png); } #facebox .tl { background:url(/images/tl.png); } #facebox .tr { background:url(/images/tr.png); } #facebox .bl { background:url(/images/bl.png); } #facebox .br { background:url(/images/br.png); }
Now we attach facebox to the login link. Open up /public/JavaScripts/application.js and use this:
$(document).ready(function() { $('#login-link').facebox({ loadingImage : '/images/loading.gif', closeImage : '/images/closelabel.gif', }); });
I override the default settings for the images to reflect the new image path. Start the sever and head over to the index page. You should see a nice facebox with the login form:
Next thing we have to do is set the form to submit itself via AJAX. Just like before, we’ll have to use callbacks to execute code after the modal box is ready. We’ll use jQuery’s post method for the XHR request. Facebox has an after reveal hook we can use. application.js:
$(document).ready(function() { $('#login-link').facebox({ loadingImage : '/images/loading.gif', closeImage : '/images/closelabel.gif', }); $(document).bind('reveal.facebox', function() { $('#new_user_session').submit(function() { $.post(this.action, $(this).serialize(), null, "script"); return false; }); }); });
Updating create.js.erb should be easy enough. We have to update the facebox’s contents and re-ajaxify the form. Here’s the code:
$('#facebox .content').html("<%= escape_JavaScript(render :partial => 'form') %>"); $('#new_user_session').submit(function() { $.post(this.action, $(this).serialize(), null, "script"); return false; });
And that’s it! Here’s the final product:
Downloading the Code
You can get the code here. There are branches for each library so you can check out the Prototype or jQuery versions. Any questions, comments, concerns? Thanks again for reading!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
| http://code.tutsplus.com/articles/how-to-build-an-unobtrusive-login-system-in-rails--net-9194 | CC-MAIN-2014-41 | refinedweb | 3,066 | 61.02 |
Recent:
Archives:
A Java programmer's first exposure to threads is usually an applet that uses them to provide animation. In these applets,
the thread simply sleeps for a period of time before updating the next frame or moving text in an animated ticker. Threads,
however, are much more useful than this. Another way to use threads is with the
wait() and
notify() functions that are part of the
Object class.
Every Java object instance and class potentially has a monitor associated with it. I say potentially because if you don't use any of the synchronization functions, the monitor is never actually allocated, but it's waiting there just in case.
A monitor is simply a lock that serializes access to an object or a class. To gain access, a thread first acquires the necessary
monitor, then proceeds. This happens automatically every time you enter a synchronized method. You create a synchronized method
by specifying the keyword
synchronized in the method's declaration.
During the execution of a synchronized method, the thread holds the monitor for that method's object, or if the method is
static, it holds the monitor for that method's class. If another thread is executing the synchronized method, your thread
is blocked until that thread releases the monitor (by either exiting the method or by calling
wait()).
To explicitly gain access to an object's monitor, a thread calls a synchronized method within that object. To temporarily
release the monitor, the thread calls the
wait() function. Because the thread needs to have acquired the object's monitor, calling
wait() is supported only inside a synchronized method. Using
wait() in this way allows the thread to rendezvous with another thread at a particular synchronization point.
A very simple example of
wait() and
notify() is described in the following three classes.
The first class is named
PingPong and consists of a single synchronized method and a state variable. The method is
hit() and the only parameter it takes is the name of the player who will go next.
The algorithm is essentially this:
If it is my turn, note whose turn it is next, then PING, and then notify anyone waiting. otherwise, wait to be notified.
To implement this, however, we add a few more lines:
1 public class PingPong { 2 // state variable identifying whose turn it is. 3 private String whoseTurn = null; 4 5 public synchronized boolean hit(String opponent) { 6 7 String x = Thread.currentThread().getName(); 8 9 if (whoseTurn == null) { 10 whoseTurn = x; 11 return true; 12 } 13 14 if (x.compareTo(whoseTurn) == 0) { 15 System.out.println("PING! ("+x+")"); 16 whoseTurn = opponent; 17 notifyAll(); 18 } else { 19 try { 20 long t1 = System.currentTimeMillis(); 21 wait(2500); 22 if ((System.currentTimeMillis() - t1) > 2500) { 23 System.out.println("****** TIMEOUT! "+x+ 24 " is waiting for "+whoseTurn+" to play."); 25 } 26 } catch (InterruptedException e) { } 27 } 28 return true; // keep playing. 29 } 30 }
In line 3 we declare our state variable,
whoseTurn. This is declared private since the users of the class don't need to know it. Line 5 declares our method and it must have the synchronized keyword or the call to
wait() will fail.
In line 7 we get our own name from the thread object. As you will see later, we set this after the thread is created. This helps in debugging since our thread is named something useful and is a convenient way to identify the players.
Lines 9 through 12 solve the problem of whose turn it is before anyone has gone. The policy implemented is that the first thread to invoke this method will get the honor of going first.
Lines 14 through 17 execute when it is the current thread's turn to go. When executed, the thread updates the state variable
with the next thread's turn. This is done before the notify, as the notify may cause another thread to start running immediately
before it knows it is its turn to run. Then
notifyAll() is called to notify all threads that are waiting on this object that they can run. If you are using only two threads, simply
call
notify() since that call will wake up exactly one thread from the set waiting to run. With two threads, only one thread can be waiting,
so the correct thread will wake up. If you extend this to three or more threads, however, the notify call may not wake up
the correct thread and the system will stop until that thread's wait times out.
Lines 19 through 26 execute when it isn't the current thread's turn to go. Line 21 simply calls
wait() and goes to sleep. However, you will notice that in line 20 the code notes the current time. It does this because when execution
continues after the wait call returns, the reason for continuing could be either the wait timed out or our thread was awakened
with a call to
notify(). The only way to tell the difference is to measure how long the thread was asleep.
This timeout test is performed in line 22. If a timeout occurs, an informative message is printed to the console. In practice this will happen only when the time spent in lines 14 through 17 is greater than 2.5 seconds.
Line 26 is where we catch
InterruptedException, which would be thrown if the thread in the
wait() call stops prematurely.
Really, that is all there is to this part of the code. I did, however, add some additional code (shown below) between lines 8 and 9 to allow a third thread to cause the threads using this class to exit.
8.01 if (whoseTurn.compareTo("DONE") == 0) 8.02 return false; 8.03 8.04 if (opponent.compareTo("DONE") == 0) { 8.05 whoseTurn = opponent; 8.06 notifyAll(); 8.07 return false; 8.08 }
As you can see, this is done by setting the special opponent DONE in the call to
hit(). When the opponent is done, line 8.02 makes sure the code returns the boolean false.
Once we have the class of type
PingPong, any thread with a reference to an instance of class
PingPong can synchronize itself with other threads holding that same reference. To illustrate this, consider the following
Player class designed for use in the instantiation of a couple of threads:
1 public class Player implements Runnable { 2 PingPong myTable; // Table where they play 3 String myOpponent; 4 5 public Player(String opponent, PingPong table) { 6 myTable = table; 7 myOpponent = opponent; 8 } 9 10 public void run() { 11 while (myTable.hit(myOpponent)) 12 ; 13 } 14 }
As you can see, this code is even simpler. All we really need is a class that implements the
Runnable interface. The
Thread class provides a constructor that takes a reference to an object implementing
Runnable.
The two instance variables in this class are the reference holding the
PingPong object and the name of this player's opponent. This latter field is used in the
hit() method to tell the object which player should go next.
There is a single constructor taking a
PingPong object and the name of an opponent. To satisfy the
Runnable interface, there is the method
run in lines 10 through 13.
The run method runs an infinite loop, calling
hit() until it returns false. This method returns true until some thread calls it with the opponent name DONE.
To complete our example, we have an application class that will create a couple of threads using the
Player class and pit them against each other. This is shown below in the
Game class.
1 public class Game { 2 3 public static void main(String args[]) { 4 PingPong table = new PingPong(); 5 Thread alice = new Thread(new Player("bob", table)); 6 Thread bob = new Thread(new Player("alice", table)); 7 8 alice.setName("alice"); 9 bob.setName("bob"); 10 alice.start(); // alice starts playing 11 bob.start(); // bob starts playing 12 try { 13 // Wait 5 seconds 14 Thread.currentThread().sleep(5000); 15 } catch (InterruptedException e) { } 16 17 table.hit("DONE"); // cause the players to quit their threads. 18 try { 19 Thread.currentThread().sleep(100); 20 } catch (InterruptedException e) { } 21 } 22 }
Because we want to execute this class from the command line, it must include a public static method named
main that takes a single argument that is an array of strings. This is the method signature the
java command keys off of when instantiating a class from the command line.
Line 4 is where the code instantiates a copy of our
PingPong class and stores the reference in the local variable
table. Line 5 and line 6 are compound object creations, first creating new
Player objects and then using those objects in the creation of new
Thread objects. At create time, the name of the opponent is specified so Alice's opponent is Bob and Bob's opponent is Alice. These
new threads are named using the
setName method in lines 8 and 9, and then they are started in lines 10 and 11.
After line 11 is executed, there are three user threads running, one named alice, one named bob, and the main thread. On the system console you will start seeing messages of the form:
PING! (alice) PING! (bob) PING! (alice) ...
and so on. The threads alternate which one runs by the state in the
PingPong object. This object forces them to run one after another, however it also ensures that they run as rapidly after one another
as possible since as soon as one is finished, it calls
notifyAll() and the other thread begins to run.
Finally, in lines 12 through 15 you will see that the main thread goes to sleep for five seconds or so, and when it wakes
up, it calls
hit() with the magic bullet name DONE. This will cause the alice and bob threads to exit. Due to a bug in the Windows version of
the Java runtime, the main thread has to wait a bit to let alice and bob exit first, before it can exit. Otherwise it will
never exit (Sun knows about this bug). The short sleep in lines 18 through 20 cover this case and allow our program to exit
normally on all systems. | http://www.javaworld.com/javaworld/jw-04-1996/jw-04-synch.html | crawl-002 | refinedweb | 1,713 | 72.36 |
How to load vue Plugins inside components
Heyhey… im trying to load a vue Plugin (for example vue.scrollTo) which has custom directives inside a component. The normal way of installing Plugins works fine but when i import the plugin inside a component i get the “Failed to resolve directive: scroll-to” error.
What i have tried so far:
import VueScrollTo from 'vue-scrollto’
import VueScrollTo from ‘…/plugins/vue-scrollto’ // this is the file i created with quasar new plugin and used before
also i tried various ways of loading it like:
created() {
VueScrollTo()
},
Any help would be appreciated
I am using it in my project. What i did is simply npm install the package and after, without any import or plugin, i directly call it in my component in a method like :
myMethod() { var VueScrollTo = require('vue-scrollto') var options = { container: '#scrollable-content', easing: 'ease-in-out', cancelable: true, onStart: function (element) { // scrolling started }, onDone: function (element) { // scrolling is done }, onCancel: function () { // scrolling has been interrupted }, x: false, y: true } }
Maybe this is not the best way to do it but i’m only using it in a single component that’s why for my part it’s fine.
Hope it helps
Hey @Sweetyy,
thanks for the response!
What do you mean with directly calling it in your component? where exactly do you place “myMethod()” ? Inside mounted or created?
Also are you able to use the directives after using it like that?
sorry for the double post but i would love to know how i can resolve this isse as im adding more and more libraries… i just added vue isotope and in the Docs they say:
// ES6
import isotope from ‘vueisotope’
…
export default {
components: {
isotope,
}
…
// ES5
var isotope = require(‘vueisotope’)
i tried both but neither works… i have to use the quasar plugin way again… this time with “Vue.component(‘isotope’, isotope)”…
any help would be really appreciated!
myMethod() is placed here :
export default { components: {}, data () { return {} }, methods: { myMethod () {} } }
And i call it with a click for example :).
Hope it helps ! | https://forum.quasar-framework.org/topic/2421/how-to-load-vue-plugins-inside-components | CC-MAIN-2018-34 | refinedweb | 343 | 56.18 |
Hello all,
I have a class named “Interface” in witch I’m creating some buttons.
I want to execute a function when a button is pressed.
The problem is since I want my class to be generic, I can’t write that peace of code inside my class, I need it to be in my main code.
Is there a way, then, to connect a function to a button created inside an object.
The example below show what I would like to achieve :
Interface i; void setup() { size(800, 600); i = new Interface(this); i.connectFunctionToBtn(functionToTrigger); //This is what I would like to write } void draw() { background(20); } void functionToTrigger() { println("Function triggered"); }
Then my class Interface would be something like this :
import controlP5.*; class Interface { ControlP5 cp5; Interface(PApplet p_parent) { cp5 = new ControlP5(p_parent); cp5.addButton("btnTest") .setPosition(10, 10) .setSize(50,20); } // THE FUNCTION TO WRITE void connectFunctionToBtn() { } }
Thank you for your help ! =D | https://discourse.processing.org/t/connect-a-function-to-a-button-created-in-an-object-controlp5/1821 | CC-MAIN-2022-27 | refinedweb | 157 | 61.87 |
Now that Cocoon 1.7.4 is released and JavaONE is coming, I'm going to
dedicate my time in making Cocoon2 a reality. This implies cleaning up
the xml-cocoon2 branch as well as to release its first alpha version.
Yes, alpha. This is not due to program stability issues (Pier is a great
coder and his stuff normally turns out beta directly), but "interfaces
stability".
This means (and I'm going to write this big): IT WILL REMAIN ALPHA UNTIL
WE ARE SURE THE CORE INTERFACES AND NOT GOING TO CHANGE.
For "interfaces" I mean "everything that interface with the outside
world", not only Java Interfaces, but also DTDs (sitemap,
configurations), command line arguments, internal API, hooks to external
API.
Also, since the Apache JServ project has released its latest version of
JServ, the project will be closed down. Tomcat is the future and we all
agree on that.
So I would like to make Cocoon2 depend on Servlet 2.2 (or greater) but
still using Java 1.1 for core classes (but externally distributed
modules might require Java 1.2 in order to work).
Moreover, since the Apache XML Project is approaching the IBM SVG group
for having them joining us on xml.apache.org, the Cocoon project will
_not_ host any code directly involved with rendering or serializing.
These parts will be used from other projects (mainly FOP and TRaX)
------------------- o ---------------------
Ok, so Cocoon2 will have two faces:
- dynamic content generation
- static content generation
the first face is "more or less" already in place, even if some
addictions are needed in its very core. The second face is not yet
present and this is what's missing mostly today.
While Cocoon1 and Stylebook used the same internal framework ideas,
their use was totally different: Stylebook enforced a particular view of
a web site, and its "book" file was similar to the idea that later
become the Cocoon2 sitemap.
I believe that our goal should be to "unify" those two things to allow
Cocoon to handle an entire web site in both its static and dynamic parts
all coming from the same file.
Also, the need for the semantic web I expressed in my latest RT is
reflected in the need to use RDF _inside_ the sitemap, or, in
alternative, provide a way to RDF-ize a sitemap when semantic crawlers
approach the site.
Even if I don't have completely clear ideas on how this will be shaped,
I have some guidelines for functionality that Cocoon2 should be able to
adhere to:
- The sitemap DTD must be easy to use and to understand. Should _not_
require documentation for simple usages and allow "learning by example"
even for complex ones.
- The sitemap must be componentizable. This means that a web application
or a site fragment could be "plugged in" and mounted to a particular URI
without requiring the sitemap to be a single file.
- Every resource has two views: it's original XML one and it's adapted
one. The original view contains the "structure skeleton", while the
adapted view contains the directly digestible information.
-------------------- o -------------------
Ok, since I know I've lost you there, I'll try to express myself with
examples.
Suppose you have a general XML page like this
<page>
<author>Stefano</author>
<para>
<link uri="/dist">
</link>
</para>
</page>
what could your favorite program tell from this page? It's structure.
That's it. It could tell you that there is a <link> element which is
included into <para>. Fancy viewers will allow you to play around with
the tree, just like IE5 does, but is it really useful?
No, it's not. We would like to _know_ something about this page. How to
visualize it. What pages does it link to. Who wrote it. And so on.
If the program _knows_ the DTD, no problem: HTML-aware programs, in
fact, are able to tell you all those things by looking at the right
But if you don't know the tags, what do you do? <link> could tell an
english program something, but <collegamento> or <liaison> would? and
what if I make my <face> tag hyperlink to one of my pictures? Would you
be able to tell?
Also, how do you know that <author> contains the author of the page?
<autore>? <createur>?
Luckily, we have namespaces.
Ok, so we go on and say
<page xmlns:
<author>Stefano</author>
<para>
<link xlink:
</link>
</para>
</page>
Cool, now we know that all elements with attributes that belong to the
"" namespace indicate hyperlinking
capabilities.
the XLink specification indicates _what_ those attributes mean and _how_
these should be interpreted. Being attributes, they can be added to any
DTD and retain their capabilities, since namespaces link their names to
very specific meanings and create that common foundation that allows
programs to _understand_ something about the data being parsed.
Now that we have linking information, this could allow us to "crawl" an
XML site with this simple algorithm:
1) start from /
2) parse all elements searching for attributes in the xlink namespace
3) recurse from 2 until you visited all local links
Ok, now we are able to crawl the site and create a web-like map of all
the site links (think of something like Frontpage site views). What do
we do with all the information we have obtained?
Idea! Let's do a search engine.
Great, so we parse everything and store all the data into a big
XML-capable database, all data, all elements, text, everything. A big
and fancy collection of structured information.
Cool, now what do we do with it?
We search! Brilliant.
Ok, now that I have more structured information, searches will be just
great... no more 10000 pages about the stupid Java programming language
when searching for a place to spend my summer vacation, right?
WRONG!
Yes, you have a bunch of structure information stored into a database,
but you know _nothing_ more about it. Even worse, while HTML had small
associated semantics (<head><title> meant something), here you have
_nothing_.
Hmmm, I hear you say, let's use some extended XPath:
uri()[//author[contains-case-insensitive-text('stefano')]]
should give me the URIs of the documents which contained an <author>
element which contained the text Stefano, case insensitively.
Great, I say, but I also wrote an article for an italian newspaper
hosted on that side and I used an italian DTD. How would you know?
It is evident that what we have it's not enough: we need a way to assign
"metadata" information to elements, but also we need to express
"inheritance" capabilities to create "classes of equivalence" between
elements in different namespaces.
So, for example,
<author>,<autore> extend <dc:author>
where 'dc' is the namespace prefix for the "Dublin Core" which
standardized (on an IETF RFC!) a set of metadata elements for digital
publications.
So let's try something better
<page
xmlns:xlink=""
xmlns:rdf=""
xmlns:
<rdf:description
<md:author>Stefano</md:author>
</rdf:description>
<para>
<link xlink:
</link>
</para>
</page>
where at "" we find an RDFSchema such as
<rdf:RDF xml:lang="en"
xmlns:rdf=""
xmlns:
<rdfs:Class rdf:
<rdfs:comment>The class of people are authors</rdfs:comment>
<rdfs:subClassOf rdf:
</rdfs:Class>
</rdf:RDF
which indicates that the element
is a subclass of.
------------------ o ----------------------
It's impressive, I know, but the usual question remains: what role does
Cocoon play in all this?
Well, I showed above the difference between a "regular" XML file and an
"XML+RDF+XLink" one, which indicates that XML alone is even worse than
HTML.
The problem is: how can I request the "XML+RDF+XLink" view of a
resource?
The semantic web is both human consumable (visually appealing) and
machine consumable (algorithmically appealing), but most programs are
tuned for one or the other. Today, still, no program is able to
understand both at the same time (Mozilla is the one that comes closer,
but still doesn't have RDFSchema capabilities)
So, the serving environment must be able to "recognize" the need for the
requesting agent and send the appropriate request.
Cocoon is the clear pioneer in this field and we much "research" the
best way to make different "views" of the same resource available to
requesting clients. And, at the end, generate a W3C Note about this.
Also, it is evident that Cocoon should be the first to behave as the
"crawler of itself", for example, to generate it's static view, using
RDF and xlink roles to indicate that a resource is dynamic and must not
be statically generated.
I know I've put _lots_ of irons in the fire.
But these days are _so_ exiting and I love being able to do real applied
research on something that is really useful and does show the power of
the new ideas behind the web.
Result of this RT: the Cocoon2 sitemap must be redesigned with these
informations in mind and must be future compatible with both xlink
crawling and metadata addition.
This doesn't mean we have to rewrite what's already there, but we have
to rethink about some of those issues under this new bright semantic
light.
And I really hopes all this excites you guys as much as it excites!
------------------------- --------------------- | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200005.mbox/%3C3925A125.1D727A65@apache.org%3E | CC-MAIN-2015-32 | refinedweb | 1,544 | 59.74 |
Hello all,Hello all,
I am trying to make a controller called Categories have subdirectories such as Fridges, Backpacks etc. Currently my setup works so that when browsing to 'categories/fridges/index', the index page from the fridge view page is shown. I want this page to appear when navigationg to 'categories/fridges'. Currently that page shows: "The action 'show' could not be found for CategoriesController".
I have set up my routing like so:
map.namespace :categories do |categories|
categories.resources :fridges
end
I have also tried matching '/fridges' to 'fridges#index' within the namespace but to no avail.
Is something wrong within my routing, or within the creation of the controllers?
Thanks in advance! | http://www.codingforums.com/ruby-and-ruby-on-rails/225338-subdirectory-controllers.html?s=d6e9589c38ce95ca1ea2345dfbd688ec | CC-MAIN-2016-18 | refinedweb | 115 | 59.3 |
The Story of a Simple and Dangerous OS X Kernel Bug 230
RazvanM writes "At the beginning of this month the Mac OS X 10.5.8 closed a kernel vulnerability that lasted more than 4 years, covering all the 10.4 and (almost all) 10.5 Mac OS X releases. This article presents some twitter-size programs that trigger the bug. The mechanics are so simple that can be easily explained to anybody possessing some minimal knowledge about how operating systems works. Beside being a good educational example this is also a scary proof that very mature code can still be vulnerable in rather unsophisticated ways."
Age is irrelevant, resistance is futile. (Score:5, Insightful)
"Beside being a good educational example this is also a scary proof that very mature code can still be vulnerable in rather unsophisticated ways."
Since when did the age of code become a metric for evaluating its trustworthiness? Code should only be trusted after undergoing in-depth analysis by people with training and experience in information security. Code should also be written with security in mind from the beginning. The story of this kernel bug is simple and goes like this: "I was in a hurry."
Re:Age is irrelevant, resistance is futile. (Score:4, Informative)
A million monkeys with typewriters....
Re:Age is irrelevant, resistance is futile. (Score:5, Insightful)
Well, assuming that the code is actively (and properly) maintained, then that isn't a bad metric. Essentially, it's because any security flaw is the result of a bug. It's just a bug that can be exploited. So, if the code is maintained properly, then bug fixes will be continuous and as such, reduce the number of exploitable bugs.
Good metric, yes. Absolute metric, no.
"""... which is basically one of the tenets of OSS."""
And where did you hear that? Because, I never have and I've been around for a while.
Re:Age is irrelevant, resistance is futile. (Score:4, Insightful)
Essentially, it's because any security flaw is the result of a bug. It's just a bug that can be exploited. So, if the code is maintained properly, then bug fixes will be continuous and as such, reduce the number of exploitable bugs.
It depends on your scope of consideration. Design flaws are not 'bugs' in the traditional sense of the word (i.e., implementation-related). However, if you expand your scope to include design specs then your statement is true. There do exist though exploits of perfectly-implemented but imperfectly-designed code.
Re: (Score:2)
There are also cases where this just isn't true. See malloc [itworld.com].
Re: (Score:2)
"""... which is basically one of the tenets of OSS."""
And where did you hear that? Because, I never have and I've been around for a while.
It's implied, in my opinion. Because OSS stuff rarely gets the benefit of expensive and time consuming security analysis. Mostly because often nobody has the money/time/skill set, or because the code moves so damned fast. Admittedly, this setup appears to work quite nicely (I'm a *nix user myself).
Re:Age is irrelevant, resistance is futile. (Score:5, Funny)
Well... I think that depends a lot on the reason why it's old code. I've met my share of code with the warning "There be dragons!".
Re:Age is irrelevant, resistance is futile. (Score:5, Interesting)
I've met my share of code with the warning "There be dragons!".
The word "fuck" in the comments is a much better metric. If it's more than one for the same function, it's time to pay attention.
Re: (Score:2)
Just look at the WMF [wikipedia.org] bug for an example, which affects everything from Win3.0 up. I've always wondered how much truly old and crufty crap is "brewing in the bowels" of the big three OSes just waiting to fall apart. I'm guessing it isn't as bad a problem in OSX and Linux though as backwards compatibility isn't such a big selling point with them.
After all nobody really expects programs written for 10.0 on OSX or for whatever version Debian was out in 01 to actually work now, but considering the fact that I
Re:Age is irrelevant, resistance is futile. (Score:4, Insightful)
While I'm not particularly sold on this notion myself, it does bear a lot of semblance to the idea that code can be proven "secure" if it stands after a multitude of random attacks, which is basically one of the tenets of OSS.
I'm pretty sure that's not a tenet of OSS. If someone is pushing that as a tenet, then they really need to pay closer attention to history. A history of resilience is a nice metric - but it's not "proof" that code is bug-free rather just that nobody has found a given bug or made it public. People who get caught up in vulnerability counts forget that the real metric is response to a given vulnerability.
One tenet you hear bandied about is "given enough eyeballs, all bugs are shallow." Criticism tends to revolve around whether enough eyeballs have been put to any particular piece of code. Although one could argue that it's not just the number of eyeballs - but whether said eyeballs have the training to look for particular kinds of bugs that might not show up in normal use of the given code. None of that has anything to do with the frequency of attack.
Re: (Score:2)
You're right and it's worth remembering that some bugs will cause incorrect behavior on a cycle that is so long that our Sun will go nova before it shows up.
Re: (Score:2)
Re: (Score:3, Insightful)
In my experience, a code's age/maturity is one of the better indicators of it's INsecurity.
We've learned a LOT about security (and more importantly about writing secure code) over the past 10 years.
10 years ago, nobody knew about arithmetic overflow vulnerabilities or heap overflow vulnerabilities. Now every coder needs to worry about them. And all that old code was written non knowing about those vulnerabilities so it's highly likely to contain issues.
Re: (Score:2)
Re: (Score:2)
But it's not Windows! (Score:3, Funny)
Re: (Score:2)
Dammit, I was going to post that!!
Re:But it's not Windows! (Score:4, Funny)
So was I! But my Mac crashed in the middle of my post so someone else beat me to it while I waited for Windows to boot!
So it took Windows over 10 hours to boot?
Re: (Score:2)
Macs have a history of having far less vulnerabilities than Windows.
But now they're catching up with Microsoft in that, as well as average patch time!
:D
Less vulnerabilities? Yeah, right! (Score:4, Informative)
Macs have a history of having far less vulnerabilities than Windows.
From IBM research: IBM Internet Security Systems X-Force® 2008 Trend & Risk Report [ibm.com]
Look under "most vulnerable operating system". Yes, right at the top, for several years going sits OS X. It actually consistently experiences 3 times the number of vulnerabilities compared to Vista.
You can also do some secunia digging yourself. It shows the same tendency even in the raw data.
OS X may be less exploited but it has far more vulnerabilities. On top of that OS X lacks many of the anti-exploit mechanisms found in both common Linux distros and in Windows Vista.
Vulnerabilities does not have much to do with exploits. A single vulnerability may leads to several independant exploits. Many vulnerabilities will pass unexploited. The difference is incentive. And if pwn2own has showed us anything it certainly confirms this. Macs have consistently been the first to fall, literally within seconds.
Re:Less vulnerabilities? Yeah, right! (Score:5, Informative)
On top of that OS X lacks many of the anti-exploit mechanisms found in both common Linux distros and in Windows Vista.
Not sure about that. OS X has a very advanced sandboxing system, and has since OS X 10.5. This is why the mDNSResponder bug last year was a remote root hole on Linux, Windows, and OS X 10.4 and a DoS on OS X 10.5 and above.
Re:Less vulnerabilities? Yeah, right! (Score:5, Insightful).
Re: (Score:2)
Makes me wonder just what the hell you're doing all day. Feel free not to answer....
Re: (Score:2, Interesting)
In the report (page 40, or rather; page 44. Was it really that hard to refer to a page?) it talks about number of disclosed vulnerabilities. There a re few things wrong with that list:
1) IBM's own OS is at the bottom. As they built the report, one should start questioning that. I'm ignoring "Others.".
2) It's the number of DISCLOSED vulnerabilities. I wouldn't be surprised if most of those fully-closed OSes (really just 1 of them) fixes a lot of stuff they don't disclose
3) It's the NUMBER of vulnerabilities.
Re:Less vulnerabilities? Yeah, right! (Score:4, Insightful)
Re:Less vulnerabilities? Yeah, right! (Score:5, Interesting)
Re:But it's not Windows! (Score:5, Insightful)
You know, at this point there are probably about a thousand times as many people whining about this supposed attitude on the part of Mac users than there are Mac users actually displaying it.
Re:But it's not Windows! (Score:5, Insightful)
They're an easy target because they stress this in their advertising thus bringing it on themselves. Why have pity for them? Their ads are smarmy so getting a little in return is all in good fun. It's ridiculous to think that any computer is perfect, that's why we point and laugh.
Re:But it's not Windows! (Score:5, Funny)
You know, at this point there are probably about a thousand times as many people whining about this supposed attitude on the part of Mac users than there are Mac users actually displaying it.
But that's perfectly in order, isn't it? There have been many more people complaining that Hitler was a bad guy than there has been Hitlers.
(*knock, knock*
- Who's there?
- Godwin.)
Re:But it's not Windows! (Score:5, Funny)
Re:But it's not Windows! (Score:5, Funny)
Re:But it's not Windows! (Score:5, Informative)
Same could be said for Linux! Right? Right? Being open source makes it invulnerable?
No, it being open source means that the vulnerabilities can be fixed quicker than 2+ years.
Linux has had more known vulnerabilities than Windows, but that is because people can see the source and find the vulnerabilities. It has also had more fixed vulnerabilities and currently has less valid vulnerabilities than Windows.
Re: (Score:2, Informative)
Re: (Score:2)
Re: (Score:3, Insightful)
With Windows, there are two groups of people looking for bugs: Microsoft employees who do not want to admit to the bug and who will hide the fix in a service pack who knows how many months later, and those looking to exploit.
In Linux, in addition to those being paid to work on it such as RedHat employees and those hoping to exploit it, you have volunteer kernel hackers and users as well, to whom it is beneficial to release a patch immediately.
Re: (Score:2)
With Windows and OS X, those are the only two choices.
With Linux, there's a third option: Fix it myself.
Now, granted, you're still going to have all kinds of people who go with option #1 and option #2. But if I had the skills to find and debug kernel exploits, for instance, I'd probably want to fix them at least to secure my own systems.
Also worth mentioning -- with Windows and OS X, developers can know about a bug and ignore it, hoping no one notices. This is an obvious example:
To make this disclosure full: I discovered the kernel panic in August 2008. I wrote to Apple but the only reply I got was indicating that they are investigating the problem. In July 2009 I finally spent some time and debug the problem. After I found that it could be used to write arbitrary data in memory I wrote again to Apple. This time they wrote back asking me if I want to be credited in the Security Update. They kept [apple.com] their promise.
:-)
And, looking at that page:
About the security content of Security Update 2009-003.... Last Modified: August 05, 2009
So
Re:But it's not Windows! (Score:5, Informative)
Re: (Score:3, Interesting)
Last numbers I saw said there were 78 people actively working on the Linux kernel, and not all of these full-time
Where did you get that? LWN's development statistics for 2.6.31 [lwn.net] (subscriber-only for the next few days) say that there were 1,146 distinct developers whose patches got accepted into this particular minor release (i.e., over the last three months or so). The stats for 2.6.30 [lwn.net] (publicly viewable) show 1,125. Granted, most of these are probably touching only a tiny portion of the code and might only get a few changesets accepted, but they could still fairly be described as "actively working on the Linux ker
Re: (Score:2)
The parent said:
All of this applies to the Apple kernel as well because it's open source
Doesn't cause panic on 10.3.9 (Score:5, Interesting)
Re: (Score:2)
Sadly I couldn't get my Mac OS X 10.3.9 (PowerPC) machine to panic with the C code.
Try letting it see you use an Android phone while simultaneously unwrapping a new Zune media player...
Sorry, I should probably let my meds kick in before I post in the mornings...
Re:Doesn't cause panic on 10.3.9 (Score:4, Informative)
I read (Score:4, Insightful)
Alright, I read TFA. I read the earlier slashdot article. I even googled around a little bit. What I find is, an obscure little bug, if exploited locally, enables a user to crash his machine. What I don't find is an exploit that makes use of this bug.
Am I missing something?
I suppose that I could accomplish something similar on my current Ubuntu installation. If I thought it made a difference, I could install a few other flavors of Linux and try doing something like that. But, why?
MS astroturfer's posts above are noted. And, I also note that MS bugs are routinely exploited, locally and remotely. The unwarranted superiority complex looks pretty pathetic, doesn't it?
Re:I read (Score:5, Insightful)
Re: (Score:3, Informative)
Citation please? The line between local and remote seems to be pretty concrete and fine to me.
Re: (Score:2)
Indeed, for those having trouble spotting it, it's the line with the flashing green light next to it.
Re: (Score:2)
Re: (Score:2)
Am I missing something?
Possibly. An active exploit might not be available, it may still be in the underground, or we may be dealing with a series of code flaws that resemble the old tenets of CISCO fame - "We're unexploitable, all you can do is cause DoS". It might just be we have to wait for someone to turn around and go "oh really" before an active exploit can be retrieved from a crash.
Re:I read (Score:5, Informative)
followed by an example of actually doing it and proving that it worked (not a particularly malicious example, but it seems enough proof of concept to me).
I don't think you understood (Score:5, Informative)
What are you, a Linux kernel dev?
;)
The bug lets you write arbitrary, user-controlled bytes into kernel space. The first thing that comes to mind is that you could change the current process' priv structure in memory. Now you're root. Or why not use it to hook syscalls, or do really whatever you want? You're in ring0, go nuts.
It's far more than just a DoS.
Re: (Score:2)
OSX is a multi-user OS. This turns any local account compromise, even an unprivileged account (sshd privsep user? nobody?) into a full compromise of the machine.
Local escalations are always scary on a multi-user machine.
Re: (Score:3, Insightful)
Re:I read (Score:4, Insightful)
Yeah, I've read this "market share" argument used as a defense for shoddy MS code time and time again. That just doesn't cut it.
Mac has a presence in the business world. If it were as buggy as MS, crackers would be launching fishing expeditions for vulnerable Macs, so that they could gain access to company networks.
What I asked for were examples of exploits, or reasons why this bug were really dangerous. Posts before yours are attempting to put things into perspective. Please, no more lame defenses of from MS astroturfers - there are enough of those even before you arrive at my question.
Market share, indeed. Remind me that the next time I want a cheap padlock, I should purchase a no-name lock. Since it has no market share, burglars won't try to pick it or break it.
Re:I read (Score:5, Insightful)
Mac has a relatively tiny presence in the business world.
Fixed that for you.
What I asked for were examples of exploits, or reasons why this bug were really dangerous.
And a bunch of people already pointed out that this bug gives you write-access to the kernel's memory. That's bad, privilege escalation bad.
Market share, indeed. Remind me that the next time I want a cheap padlock, I should purchase a no-name lock. Since it has no market share, burglars won't try to pick it or break it.
That's funny, because I recall seeing all sorts of instructions on how you can open MasterLock(TM)(R) and (ALL THAT) combination locks. They were so detailed, they would even specify which serial numbers of which models were vulnerable to which cracking techniques. And yet, I never saw any instructions for opening the Wal-Mart special RandomBrand of padlock.
Market share does matter when it comes to investing time and money into exploiting flaws in a product. To say it is the only factor in operating system security is false, but saying it doesn't matter at all is just as wrong.
Re:I read (Score:5, Insightful)
Market share does matter when it comes to investing time and money into exploiting flaws in a product. To say it is the only factor in operating system security is false, but saying it doesn't matter at all is just as wrong.
No one is saying that it's not a factor. On the other hand, there are countless people who make the reverse mistake and state that Macs don't have exploits solely due to market share.
This is easily debunked by:
1. IIS exploits.
2. Linux exploits (Linux market share is to Macs as Mac market share is to Windows)
3. Mac apps. People still write apps for the Mac, why not viruses?
4. There are plenty of viruses for the classic Mac OS.
5. There are tens of millions of Mac users. Even though Windows has hundreds of millions, tens of millions is still a large and lucrative group to attack.
The key isn't that Mac OS X is flawless or too low of a market share, it's that Windows is so easy to exploit. Design decisions made decades ago are still impacting Windows today. If you look at the typical Mac OS X bug and the typical Windows bug, you'll see that the Mac bugs tend to be very Unix-like in nature, that they are some part of the system can be tricked into crashing by being passed data in a specific way. Many a Windows bug is not due to getting something to crash, but by using some feature in a way that tricks it to allow unwanted things to happen.
Re:I read (Score:4, Insightful)
Some problems with your arguments.
#1 IIS is a web server. That is a juicy target. It's much jucier than a lot more home OSX machines.
#2 Linux is used very often as a server. Once again, a much much jucier target than some OSX desktop.
#3 They do, just much less of them, as with apps. Less written, less looking, less discovered.
#5 Modern *nixes have pretty much all implemented this feature which OSX has neglected to implement. What else haven't they done right as the other *nixes have?
Re:I read (Score:4, Insightful)
2. Linux exploits (Linux market share is to Macs as Mac market share is to Windows)
What are some examples of widely-exploited Linux bugs? (Of course there are isolated exploits, but the same is true for Mac. And of course there are very severe security vulnerabilities all the time, but that doesn't mean they're exploited in practice. And of course Linux machines are compromised on a regular basis, but that might be due to weak passwords and such.)
3. Mac apps. People still write apps for the Mac, why not viruses?
Apps have to compete with each other. If a particular niche is filled on Windows but not Mac, then a new Windows-only app will have to compete with the existing apps. A new Mac app won't, so it will get a much larger slice of a smaller pie. On the other hand, twenty different viruses can recruit your computer into twenty different botnets with no problem, as any Windows user should be able to attest. (How often does a virus scan on an infested computer turn up only one virus?)
Besides, the number of apps for Mac is tiny compared to Windows.
4. There are plenty of viruses for the classic Mac OS.
Such as? I'm not doubting you, but I've never heard that claimed before.
5. There are tens of millions of Mac users. Even though Windows has hundreds of millions, tens of millions is still a large and lucrative group to attack.
It's a matter of cost and benefit. If it's three times the effort to write Windows exploits and you get twenty times the victims, there's just no reason to write viruses for Macs. Hackers are usually motivated by money, pure and simple.
Anyway, I don't have any credentials in hacking. So I'll rely on Charlie Miller, who's a professional hacker (security expert). He demonstrated that he knows something about Mac exploits by cracking a Mac in two minutes flat a while back and winning pwn2own. In an interview, he said [tomshardware.com] (emphasis added):
He's far from a Microsoft shill; he works for a security consulting firm and uses a Mac himself.
Re:I read (Score:4, Insightful)
"... lack of anti-exploitation technologies..."
Uh, you mean like firewalls? Sandboxing? Library Randomization? Protected memory and Execute Disable? Encrypted virtual memory? System heap library checksums? The ability to actually run user accounts as non-admins? FileVault? Disabling root by default? Download screening? Antiphishing technology? Browser page isolation? Minimal outward facing ports and services? Parental Controls?
Those anti-exploitation technologies?
If you read the interview, you would see that he specifically refers to ASLR and the NX bit, at least. OS X apparently only has a very limited version of those, at least compared to Vista (and some Linux builds). Quote [tomshardware.com]:
But hey, if you want to believe lists of features rather than the opinion of a professional security expert who was demonstrably able to hack an OS X machine in two minutes and win a high-profile hacking contest, then go ahead.
"...he works for a security consulting firm and uses a Mac himself."
And not Windows and not Linux. Guess that says it all.
Yes, it does, because he said Mac was safer. Less secure — much easier to hack — but safer, because nobody bothers to hack it. Which is exactly my point. I was responding to the great-grandparent, who claimed Windows is easier to hack than Mac, and that obscurity isn't the major reason Macs are safer. The security expert I cited believes exactly the opposite to be the case, that Macs are easier to hack and obscurity is the major reason they're safer. No one disputes that they're safer.
Re: (Score:2)
How about 7? [slashdot.org] I didn't even have to leave this story to find the link.
A tip for the future - try not to get so worked up that someone may be attacking your precious Linux that you can't even spell 'for'.
Re:I read (Score:5, Insightful)
The bug is really dangerous because it allows userspace to write anywhere to kernelspace. Yes, it's a local-only exploit, so the attack surface isn't that large. Or is it? How many pieces of software do you have running on your system right now that may contain vulnerabilities? It would be trivial for a skilled hacker to find an exploit in some arb application, with the payload being an exploit of this particular issue. So your local-only exploit has a remote entry-point from any other piece of software thats running on your system.
Local-only exploits are only less dangerous than remote exploits if your system has no contact with other systems. When you expose your system to others, all of your local exploits become remote exploits the moment any piece of software that you run has a remote exploit. Recently there have been a number of reports of vulnerabilities in common applications like Firefox, and Adobe doesn't have a particularly great security track record either. Ideally, a vulnerability in one of these applications would only be able to run code as the user, or attack the user's home directory. Except since you can now modify any address in kernel space, you can craft code that tells the kernel your userid actually has root permissions, in which case you now have complete control over the whole system.
Every kernel-level exploit is *really dangerous*. Marketing people will try to play it down by saying that since its local-only, it's not that bad, so that they can carry on making dumb 'im a pc, im a mac' adverts and patting themselves on the back. But all they're doing is lulling their userbase into a false sense of security.
Re: (Score:3, Insightful)
Yeah,:
Re: (Score:2)
"It had NO SECURITY AT ALL!"
MacOS was based on BSD, right? By extension, does BSD have no security at all? Or, are we to assume that Mac stripped out BSD's inherent security? Remember, Unix like operating systems are inherently modeled on security.
This site, among others, suggests that Mac OS users might have been security conscious: [mac.com]
Re: (Score:2)
If you have the ability to alter kernel memory at an arbitrary place, you can accomplish pretty much anythin
Re: (Score:2)
By itself, a local exploit, say, a privilege escalation exploit, is only dangerous if you don't trust your local users.
The real danger of a local exploit is that it allows a remote exploit, which normally can be contained by server process permissions, chroot jails, etc. to become more dangerous - if you can get a remotely-exploitable process to run local exploit code, you can own the box no matter what privilege restrictions the server with the remote attack vector is running with.
In other words, via a loc
Re: (Score:3, Informative)
Yes, you are.
The exploit allows users to choose an arbitrary location in memory -- including kernel space -- and write 8 bytes to it at a time. The 8 bytes are chosen by the terminal program attached to the TTY that the system call is made on. So, if a local program attaches to a TTY in the same way that a terminal does, and then makes this system call, it can load executable code into the kernel (or anywhere else, for that matter).
In other words, it makes it ridiculously simple to ru
Re: (Score:2)
And, I also note that MS bugs are routinely exploited, locally and remotely. The unwarranted superiority complex looks pretty pathetic, doesn't it?
Would you like to cite how you can remotely exploit NT 6? I would be fascinated to hear that. Unless you're just saying that local exploits are distributed and then run locally by users.
So no, it doesn't. NT 6 is the most secure desktop operating system, followed by maybe Red Hat or SuSE linux and somewhere down the line perhaps Mac OS X. That's the security situation we're looking at, like it or not.
Microsoft exploits get huge press-- Microsoft has lots of enterprise customers and needs to be very clear wh
Re: (Score:2)
"NT 6 is the most secure desktop operating system,"
So, what you seem to be saying is, you have faith that over the next several months, as NT6 is adopted by more and more people, we will see an end to Windows exploits.
Ohhhh-kay. Good luck with that. I remember similar expectations when Win9.x was finally dropped in favor of NT.
I will grant that the security model seems to be improved over NT5.x I'll readily admit that security defaults are much improved over NT5.x But, I honestly believe that NT6.x will
Mature code? (Score:5, Insightful)
I'm sorry, but what has MacOSX to do with mature code? Code is mature when it has lasted for _decades_ and no significant bug has been found. MacOSX is just your average kernel. OK, there are _much_ worse around, but that doesn't make OSX any better.
What _really_ is a shame that it took them 4 years to fix it.
More precisely (Score:3)
...no significant bug has been found, but the code has regularly been reviewed.
Re: (Score:2)
Re: (Score:3, Insightful)
Yes precisely, there is very little mature code. That's why you still have buffer overruns and other security critical bugs.
New features don't have to mean that old code will be changed or made more insecure. There are many attempts at making computer systems modular so adding one piece of code will add a lot of new features to unchanged programmes. The oldest concept incorporating it is the UNIX concept where you have lots of small single-purpose programs which you can connect via pipes to serve any more c
Re: (Score:2)
By your definition, there is hardly any mature code out in userland.
Of course not.
Name a nontrivial example of mature code in wide use anywhere today.
Not a single legacy system. Not a few lines of code in a huge application or OS. An actual complete mature application in use today. Name one.
It doesn't take quibbling over the definition of mature for this to be readily apparent. If you're finding bugs in it yourself, if bugs aren't fixed because there are higher priority bugs to fix - it isn't mature!
Re:Mature code? (Score:5, Interesting)
Re: (Score:2)
At the same time, there's been big hunks grafted on recently, not just to the kernel but all the big pieces which were heavily revised, e.g. DPS to DPDF. When you change mature code, it's not mature any more. If they actually made use of the microkernel design of OSX (and used the microkernel as anything other than a HAL, which is literally all it does there) then maybe this situation would be different... but it's not.
Re: (Score:2)
When you change mature code, it's not mature any more.
So by your really interesting way of thinking, Apple shouldn't patch the bug at all because modifying the code would make it not mature and mature (i.e. old) code is always better than immature code. Which is great if you're working on VMS every day, I suppose.
Re: (Score:2)
When you change mature code, it's not mature any more.
So by your really interesting way of thinking, Apple shouldn't patch the bug at all
If this is what you got from my comment, you're stupid. What I said is that you can't call it mature code once someone has been grafting new functionality onto it, especially when they ARE throwing away big chunks of code that you could actually call mature. Bug fixes make code more mature; adding features makes it less so. This should not be a complicated concept. Maturity does not, of course, automatically lend quality; that only happens in responsible hands.
summary (Score:5, Informative)
Despite its relative obviousness, it took me a bit of reading there to figure out what the cause of the bug was, since I was rusty on my Unix system calls, so here's a short summary.
ioctl(2) is essentially a way of specifying system calls for drivers without actually making a system call API, so drivers can register their own calls in a more decentralized way. A call to ioctl(fd, cmd, args,
...) on a special/device file 'fd' gets routed to the driver that owns 'fd', which handles the command. The arguments might be values, or might be pointers to locations in which to return data.
fcntl(2) provides a way to perform operations on open (normal) files, like locking/unlocking them. It has the same parameters as ioctl(), except that there's always a single integer argument.
One way of implementing fcntl is essentially like ioctl -- find who owns the fd, and pass the cmd along to the relevant driver. But, Apple's code did this even for the operations on special devices normally manipulated via ioctl, so you could basically do an ioctl via fcntl. But, this bypasses some of the arg-checking that ioctl does, since fcntl always has one integer argument. So an easy exploit arises: call an ioctl that normally takes one pointer argument to assign something to. ioctl would normally check that the pointer is valid (something the caller is allowed to write to) before writing to it in kernel mode. But you can pass in any memory location at all as an integer via fcntl's argument. Voila, you get data written to arbitrary locations in memory. As an added bonus, some calls let you manipulate what data gets written--- the example exploit uses a "get terminal size" ioctl, so you can vary what gets written by changing your terminal size.
Re: (Score:2)
I understood that the actual writing happened in kernel, not in userland. In kernel you can do some nasty things like write stuff to almost anywhere you like.
Make summaries more informative (Score:5, Insightful)
So then do so in the summary!
Re: (Score:2)
While the concept is simple. The example given really isn't that good to prove it.
1. Including of Uncommon (in terms of everyday use) libraries and headers.
2. The function calls and enumerations/global variables really have horrible names.
So unless you use these uncommon features in your work and even if you do have a good understanding of Operating Systems, that example isn't really that good.
So in really the post is just the guy see how 7337 I am. I found a way to hack a computer in a twitter line.
Oh god (Score:5, Funny)
Ok, I get libraries of congress and olympic-sized swimming pools, but twitter is a new one. Is it used for measuring how long a program is or how pointless it is?
Re: (Score:2)
A twitter-size program is defined as
.00001 football fields or .00002 747s, which of course can be converted to Hiroshima bombs as .00000000001
Re:Oh god (Score:5, Funny)
The comparison was simply to (successfully) annoy those of us who are
/still/ ignoring everything we can about twitter. I briefly considered checking wikipedia to see how small that was, but there were some kids on my lawn.
Re: (Score:2)
if u no abt txt its the same
Re: (Score:2)
My girlfriend asked me what Twitter was the other day (after some news agency mentioned following their Twitter feed, I think). So I told her that it's kind of like a Facebook wall, except that your messages are limited to 140 characters of text. Her response? "That seems kind of useless."
Re: (Score:2)
twitter, Erris, gnutoo, inTheLoo (Score:2)
Who is this twitter you speak off.
A notorious sockpuppet troll on Slashdot [slashdot.org].
Still get the kernel panic on Tiger (Score:5, Interesting)
Even after the recent security update on Tiger, I still get a kernel panic with the Python code supplied in TFA:
import termios, fcntl
fcntl.fcntl(0, termios.TIOCGWINSZ)
Yeah, I'm planning to upgrade to Snow Leopard soon, after having skipped Leopard. But has Tiger already been abandoned to this extent?
Hunt the Link (Score:2)
This article presents some twitter-size programs that trigger the bug.
Out of interest, what's the justification for linking to the article on "programs that trigger the bug" and not in the blindingly obvious place ("This article")?
I ask because it seems to be in-line with some kind of brain-dead in-house Slashdot linking style, and I'm curious to know the reasoning behind it.
Re: (Score:2)
I gave up long ago trying to determine what, if anything, a given link in an article summary had to do with anything. Either determining where to put a link in a sentence is a lot harder than I think,
Love the editing (Score:5, Insightful)
"The mechanics are so simple that can be easily explained to anybody possessing some minimal knowledge about how operating systems works."
"...so simple that it can be easily..."
The choice of "some minimal" is a bit questionable too. "some" or "minimal" alone would have been sufficient to convey the meaning. Together, it sounds almost redundant.
"Beside being a good educational example this is also a scary proof that very mature code can still be vulnerable in rather unsophisticated ways."
"Beside" means "next to". "Besides" means "other than".
Not that it really matters. The mainstream news sites can't seem to compose articulate sentences either. Grammar has really gone to crap and it really bugs me that English based news providers can't be bothered to produce fluent English stories.
Re: (Score:2, Informative)
Re: (Score:2)
or lack thereof:
"The mechanics are so simple that can be easily explained to anybody possessing some minimal knowledge about how operating systems works."
"...so simple that it can be easily..."
Since we're being grammar Nazis:
"...so simple that they can be easily..."
Finder (Score:3, Interesting)
You can find a major privilege escalation hole in Finder quite easily :
Finder isn't setgid but may access any gid!
Re:I'm a Mac (Score:5, Funny)
So this means we can take those idiotic commercials off the air, right?
When there's as much malware for OS X as there is for Windows, sure.
Okay, I'll make it easy. When there is a tenth as much malware for OS X as there is for Windows, sure.
Hmmm, this isn't working. When there's a hundredth as much
... um, no, that doesn't work either.
A thousandth -- no, damn.
You get the idea. Or maybe you don't.
Re: (Score:2, Flamebait) [google.nl] says it all. Now get those ads off the air.
Re:I'm a Mac (Score:5, Insightful)
OMG! A Google search for two words shows up some hits! Most of which appear to say that there are one or two bits of malware for the Mac.
If you watch Apple's ads carefully, they don't claim there is no malware for the Mac. They only imply that it doesn't affect your user experience the same way it does on Windows. I think one of the actual statements goes something like "there aren't hundreds of thousands of viruses." Which is absolutely true.
You may find the commercials annoying (don't you find all commercials annoying?), and they are arguably misleading on other points, but that's not one of them.
Re:4 fscking years (Score:4, Funny)
Oh look, I think it's trying to communicate, perhaps we can find a translator. Does anyone speak yiddiotish?
Re:Hahhah... kernel bug... LOL (Score:5, Informative)
No, XNU plus userland is Darwin. Darwin does not contain a number of proprietary drivers including, unfortunately, the entire sound stack.
For GNU types, XNU is equivalent to Linux, Darwin is equivalent to GNU/Linux, OS X is equivalent to Ubuntu (in terms of bundling nomenclature, I make no claims about feature equivalence). Darwin includes the libc, the loader, the init system (Launhcd), the toolchain and so on. XNU is just the kernel, which incorporates a Mach microkernel used as a hardware-abstraction layer and handles the VM subsystem and thread creation, a BSD subsystem which handles providing a POSIX interface to the Mach stuff and all of the other OS services, and IOKit drivers, which provide access to devices.
Re: (Score:3, Informative)
Given that the bug is in tty handling, I wouldn't be surprised if some of this code dates back to 4BSD or even earlier (take a look at the change log for the firs OpenBSD release to get an idea | https://developers.slashdot.org/story/09/08/30/0424248/the-story-of-a-simple-and-dangerous-os-x-kernel-bug | CC-MAIN-2016-50 | refinedweb | 7,002 | 65.12 |
Log message:
salt salt-docs: updated to 3004
SALT 3004 RELEASE NOTES - CODENAME SILICON
NEW FEATURES
TRANSACTIONAL SYSTEM SUPPORT (MICROOS)
A transactional system, like MicroOS, can present some challenges when the user \
decided to manage it via Salt.
MicroOS provide a read-only rootfs and a tool, transactional-update, that takes \
care of the management of the system (updating, upgrading, installation or \
reboot, among others) in an atomic way.
Atomicity is the main feature of MicroOS, and to guarantee this property, this \
model leverages snapper, zypper, btrfs and overlayfs to create snapshots that \
will be updated independently of the currently running system, and that are \
activated after the reboot. This implies, for example, that some changes made on \
the system are not visible until the next reboot, as those changes are living in \
a different snapshot of the file system.
Salt 3004 (Silicon) support this type of system via two new modules \
(transactional_update and rebootmgr) and a new executor (transactional_update).
The new modules will provide all the low level API for interacting with \
transactional systems, like defining a mantenance window where the system is \
free to reboot and activate the new state, or install new software in a new \
transaction. It will also provide hight level of abstractions that will allows \
us to execute Salt module functions or applying states inside new transactions.
The execution module will help us to treat the transactional system \
transparently (like the traditional ones), using a mechanism that will delegate \
some Salt modules execution into the new transactional_update module.
REMOVED
Removed the deprecated glance state and execution module in favor of the \
glance_image state module and the glanceng execution module.
Removed support for Ubuntu 16.04
Removed the deprecated support for gid_from_name from the user state module
Removed deprecated virt.migrate_non_shared, virt.migrate_non_shared_inc, ssh \
from virt.migrate, and python2/python3 args from salt.utils.thin.gen_min and \
.gen_thin
DEPRECATED
The _ext_nodes alias to the master_tops function was added back in 3004 to \
maintain backwards compatibility with older supported versions. This alias will \
now be removed in 3006. This change will break Master and Minion communication \
compatibility with Salt minions running versions 3003 and lower.
utils/boto3_elasticsearch is no longer needed
Changed "manufacture" grain to "manufacturer" for Solaris on \
SPARC to unify the name across all platforms. The old "manufacture" \
grain is now deprecated and will be removed in Sulfur
Deprecate salt.payload.Serial
CHANGED
Changed nginx.version to return version without nginx/ prefix.
Updated Slack webhook returner to support event returns on salt-master
Parsing Epoch out of version during pkg remove, since yum can't handle that in \
all of the cases.
Add extra onfail req check in the state engine to allow onfail to be used with \
onchanges and other reqs in the same state
Changed the default character set used by utils.pycrypto.secure_password() to \
include symbols and implemented arguments to control the used character set.
FIXED
Set default 'bootstrap_delay' to 0
Fixed issue where multiple args to netapi were not preserved
Handle all repo formats in the aptpkg module.
Do not break master_tops for minion with version lower to 3003 This is going to \
be removed in Salt 3006 (Sulfur)
Reverting changes in 60150. Updating installed and removed functions to return \
changes when test=True.
Handle signals and properly exit, instead of raising exceptions.
Redirect imports of salt.ext.six to six
Surface strerror to user state instead of returning false
Fixing _get_envs() to preserve the order of pillar_roots. _get_envs() returned \
pillar_roots in a non-deterministic order.
Fixes salt-cloud KeyError that occurs when there exists any subnets with no tags \
when profiles use subnetname
Fixes postgres_local_cache by removing duplicate unicode encoding.
Fixing the state aggregation system to properly handle requisities. Fixing pkg \
state to exclude packages from aggregation if the hold attribute is in the \
state.
fix issue that allows case sensitive files to be carried through
Allow GCE Salt Cloud to use previously created IP Addresses.
Fixing rabbitmq.list_user_permissions to ensure we are returning a permission \
list with three elements even when some values are empty.
Periodically restart the fileserver update process to avoid leaks
Fix default value to dictionary for mine_function
Allow user.present to work on Alpine Linux by fixing linux_shadow.info
Ensure that zypper is called with only one --no-refresh parameter
Fixed fileclient cachedir path switching from master to minion due to incorrect \
MasterMinion configuration
Fixed the container detection inside virtual machines
Fix invalid dnf command when obsoletes=True in pkg.update function
Jinja renderer resolves wrong relative paths when importing subdirectories
Fixed bug 55262 where salt.modules.iptables would call cmd.run and receive and \
interpret interspersed stdout and stderr output from subprocesses.
Updated pcs support to handle auth and setup for new syntax supporting version 0.10
Reinstate ignore_cidr option in salt-cloud openstack driver
Fix for network.wolmatch runner displaying 'invalid arguments' error with valid \
arguements
Fixed bug 57490, which prevented package installation for Open Euler and Issabel \
PBX. Both Open Euler and Issabel PBX use Yum for package management, added them \
to yumpkg.py.
Better handling of bad RSA public keys from minions
Fixing various functions in the file state module that use user.info to get \
group information, certain hosts particularly proxy minions do not have the \
user.info function avaiable.
Do not monkey patch yaml loaders: Prevent breaking Ansible filter modules
Fix --subset command line option, and support old 'sub' parameter name in \
cmd_subset for backwards compatibility
When calling salt.utils.http.query with a HEAD method to check for the existence \
of a source ensure that decode_body is False, so the file is not downloaded into \
memory when we don't need the contents.
Update the runas user on freebsd for postgres versions >9.5, since freebsd \
will be removing the package on 2021-05-13.
Fix pip module linked requirements file parsing
Fix incorrect hostname quoting in /etc/sysconfig/networking on Red Hat family OS.
Fix Xen DomU virt detection in grains for long running machines.
add encoding when windows encoding is not defaulting to utf8
Fix "aptpkg.normalize_name" in case the arch is "all" for \
DEB packages
Astra Linux now considered a Debian family distro
Reworking the mysql module and state so that passwordless does not try to use \
unix_socket until unix_socket is set to True.
Fixed the zabbix module to read the connection data from pillar.
Fix crash on "yumpkg" execution module when unexpected output at \
listing patches
Remove return that had left over py2 code from win_path.py
Don't create spicevmc channel for Xen virtual machines
Fix win_servermanager.install so it will reboot when restart=True is passed
Clear the cached network interface grains during minion init and grains refresh
Normalized grain output for LXC containers
Fix typo in 'salt/states/cmd.py' to use "comment" instead of \
"commnd".
add aliyun linux support and set alinux as redhat family
Don't fail updating network without netmask ip attribute
Fixed using reserved keyword 'set' as function argument in modules/ipset.py
Return empty changes when nothing has been done in virt.defined and virt.running \
states
Import salt.utils.azurearm instead of using __utils__ from loader in azure \
cloud. This fixes an issue where __utils__ would become unavailable when we are \
using the ThreadPool in azurearm.
Fix an issue with the LGPO module when the gpt.ini file contains unix style line \
endings (/n). This was happening on a Windows Server 2019 instance created in \
Google Cloud Platform (GCP).
The ansiblegate module now correctly passes keyword arguments to Ansible module calls
Make sure cmdmod._log_cmd handles tuples properly
Updating the add, delete, modify, enable_job, and disable_job functions to \
return appropriate changes.
Apply pre-commit changes to entire codebase.
Fix Hetzner cloud driver does not recognize machines when rolling out a map
Update Windows build deps & DLLs, Use Python 3.8, libsodium.dll 1.0.18, \
OpenSSL dlls to 1.1.1k
Salt api verifies proper log file path when providing '--log-file' from the cli
Detect Mendel Linux as Debian
Fixed compilation of requisite_ins by also checking state type along with name/id
Fix xen._get_vm() to not break silently when a VM and a template on XenServer \
have the same name.
Added missing space for nftables.build_rule when using saddr or daddr.
Add back support to load old entrypoints by iterating instead of type checking
Fixed interrupting salt-call in a pdb session.
Validate we can import map files in states
Update alter_db to return True or False depending on the success of failure of \
the alter. Update grant_exists to only use the full list of available privileges \
when the grant is on the global level, eg. datbase is ".".
Fixed firewalld.list_zones when any "rich rules" is set
IPCMessageSubscriber objects expose their connect method as a corotine so they \
can be wrapped by SyncWrapper.
Allow for Napalm dependency netmiko_mod to load correctly when used by Napalm \
with Cisco IOS
Ensure proper access to the created temporary file when runas is passed to \
cmd.exec_code_all
Fixed an IndexError in pkgng.latest_version when querying an unknown package.
Fixed pkgng.latest_version when querying by origin (e.g. "shells/bash").
Gracefuly handle errors in virt.vm_info
The LGPO Module now uses "Success and Failure" for normal audit \
settings and advanced audit settings
Fixing tests/pytests/unit/utils/scheduler/test_eval.py tests so the sleep \
happens before the status, so the job is given time before we check.
Fixed ValueError exception in state.show_state_usage
Redact the username and password when something goes wrong when using an HTTP \
source and we raise an exception.
Inject the Ansible functions into Salt's ansiblegate module which was broken on \
the 3001 release.
Figure out the available Python version inside containers when executing \
"dockermod.call" function
Handle IPv6 route types such as anycast, multicast, etc when returned from IPv6 \
route table queries
Move the commonly used code that converts a list to a dictionary into \
salt.utils.beacons. Fixing inotify beacon close function to ensure the \
configuration is converted from the provided list format into a dictionary.
Set name of engine subprocesses
Properly discover block devices path in virt.running
Avoid exceptions when handling some exception cases.
Fixed faulty error message in npm.installed state.
Port option reinstated for Junos Proxy (accidentally removed)
Now hosts.rm_host can remove entries from /etc/hosts when this file have inline \
Fixes issue where the full same name is not used when making rights assignments \
with group policy
Fixed zabbix_host.present to not overwrite inventory_mode to "manual" \
everytime inventory is updated.
Allowed zabbix_host.present to do partial updates of inventory, also don't erase \
everything if inventory is missing in state definition.
Fixing the mysql_cache module to handle binary inserting binary data into the \
database. Initially adding tests.
Fixed host_inventory_get to not throw an exception if host does not exist
Check for /dev/kvm to detect KVM hypervisor.
Fixing file.accumulated handling of dependencies when the state_id is used \
instead of {function: state_id} format.
Adding the ability for yumpkg.remove to handle package names with widdcards.
Pass emulator path to get guest capabilities from libvirt
virt.get_disks: properly report qemu-img errors
Make all platforms have psutils. This prevents a minion from starting if an \
instance is all ready running.
Ignore configuration for 'enable_fqdns_grains' for AIX, Solaris and Juniper, \
assume False
Remove check for TIAMAT_BUILD enforcing USE_STATIC_REQUIREMENTS, this is now \
controled by Tiamat v7.10.1 and above
Have the beacon call run through a try...except, catching any errors, logging \
and firing an event that includes the error. Fixing the swapusage beacon to \
ensure value is a string before we attempt to filter out the %.
Refactor loader into logical sub-modules
Clean up references to ZMQDefaultLoop
change dep warn from Silicon to Phosphorus for the cmd,show,system_info and \
add_config functions in the nxos module.
Fix bug 60602 where the hetzner cloud provider isn't recognized correctly
Fix the pwd.getpwnam caching issue on macOS user module
Fixing beacons that can include a value in their configuration that may or may \
not included a percentage. We want to handle the situation where the percentage \
sign is not included and the value is not handled as a string.
Fix RuntimeError in process manager
Ensure all data that is being passed along to LDAP is in an OrderedSet and \
contains bytes.
Update the AWS API version so VMs spun up by salt-cloud where the VPC has it \
enabled to assign ipv6 addresses by default, actually get ipv6 addresses \
assigned by default.
Remove un-needed singletons from tranports
ADDED
Add windows support for file.patch with patch.exe from git for windows optional \
packages
Added ability to pass exclude kwarg to salt.state inside orchestrate.
Added success_stdout and success_stderr arguments to cmd.run, to override \
default return code behavior.
The netbox pillar now been enhanced to add support for querying virtual machines \
(in addition to devices), as well as minion interfaces and associated IP \
addresses.
Add support for transactional systems, like openSUSE MicroOS
Added namespace headers to allow use of namespace from config to communicate \
with Vault Enterprise namespaces
boto3mod unit tests
New decorators allow_one_of() and require_one_of()
Added nosync switch to disable initial raid synchronization
Expanded the documentation for the netbox pillar.
Rocky Linux has been added to the RedHat os_family.
Add "poudriere -i -j jail_name" option to list jail information for \
poudriere
Added the grains.uuid on Windows platform
Add a salt.util.platform check to detect the AArch64 64-bit extension of the ARM \
architecture.
Adding support for Deltaproxy controlled proxy minions into Salt Open.
Added functions to slsutil execution module to test if files exist in the state \
tree Added funtion to slsutil execution module to search for a file by walking \
up the state tree
Allow module_refresh to also refresh available beacons, eg. following a Python \
library being installed and "refresh_modules" being passed as an \
argument in a state.
Add the detect_remote_minions and remote_minions_port options to allow the \
master to detect remote ports for connected minions. This will allow users to \
detect Heist-Salt minions the master is connected to over port 22 by default.
Add the python rpm-vercmp library in the rpm_lowpkg.py module.
Allow a user to use the aptpkg.py module without installing python-apt.
Log message:
sysutils: Replace RMD160 checksums with BLAKE2s checksums
All checksums have been double-checked against existing RMD160 and
SHA512 hashes
Log message:
sysutils: Remove SHA1 hashes for distfiles
Log message:
salt: skip portability checks in 3rd party packaging scripts
Log message:
sysutils/salt: allow no-op SUBST block
A typical case is that PKGMANDIR is man, not share/man. That path does
not occur in the Python files, which would then make the build fail in
SUBST_NOOP_OK=no mode.
Log message:
salt: updated to 2019.2.2
SALT 2019.2.2 RELEASE NOTES
Version 2019.2.2 is a bugfix release for 2019.2.0.
ISSUE 54817: (tomlaredo) [REGRESSION] git.latest displays errors (refs: 54844)
* (garethgreenaway) [master] Fix to git state module when calling \
git.config_get_regexp
52fee6f Merge pull request 54844 from \
garethgreenaway/54817_git_latest_error_calling_git_config_get_regexp
cb1b75a Adding test.
6ba8ff2 When calling git.config_get_regexp to check for filter.lfs. in git \
config, if the option is not available this would result with a return code of 1 \
which would result in an error being logged. Since one possible result is that \
the configuration would not be there, we ignore the return code.
* (frogunder) update 2019.2.2 release notes
d6593c2 Merge pull request 54973 from frogunder/update_releasenotes_2019.2.2
0c01cfb update 2019.2.2 release notes
* (twangboy) Add missing docs for win_wusa state and module (2019.2.1)
7d253bc Merge pull request 54919 from twangboy/update_docs
57ff199 Add docs for win_wusa
ISSUE 54941: (UtahDave) Pillar data is refreshed for EVERY salt command in \
2019.2.1 and 2019.2.2 (refs: 54942)
* (dwoz) Fix for 54941 pillar_refresh regression
2f817bc Merge pull request 54942 from dwoz/fix-54941
cb5d326 Add a test for 54941 using test.ping
348d1c4 Add regression tests for issue 54941
766f3ca Initial commit of a potential fix for 54941
* (bryceml) update version numbers to be correct
f783108 Merge pull request 54897 from bryceml/2019.2.1_fix_docs
e9a2a70 update version numbers to be correct
* (bryceml) 2019.2.1 fix docs
3233663 Merge pull request 54894 from bryceml/2019.2.1_fix_docs
c7b7474 modifying saltconf ads
d48057b add new saltconf ads
* (frogunder) remove in progress from releasenotes 2019.2.2
4b06eca Merge pull request 54858 from frogunder/releasenotes_remove2019.2.2
a697abd remove in progress from releasenotes 2019.2.2
* (frogunder) releasenotes 2019.2.2
aaf2d1c Merge pull request 54854 from frogunder/release_notes_2019.2.2
a41dc59 Update 2019.2.2.rst
9bea043 releasenotes 2019.2.2
* (frogunder) Update man pages for 2019.2.2
10d433f Merge pull request 54852 from frogunder/man_pages_2019.2.2
92bc4b2 Update man pages for 2019.2.2
* (s0undt3ch) Remove debug print
8ca6b20 Merge pull request 54845 from s0undt3ch/hotfix/event-return-fix-2019.2.1
3937890 Remove debug print
ISSUE 54755: (Reiner030) 2019.2.1/2019.2.0 pip failures even when not using pip \
(refs: 54826)
* (dwoz) Fix issue 54755 and add regression tests
9e3914a Merge pull request 54826 from dwoz/issue_54755
0bad9cb Handle locals and globals separatly
bcbe9a2 Only purge pip when needed
d2f98ca Fix issue 54755 and add regression tests
* (frogunder) Add known issues to 2019.2.1 release notes
ba569d0 Merge pull request 54830 from frogunder/update_relasenotes_2019.2.1
8cdb27b Update 2019.2.1.rst
14f955c Add known issues to 2019.2.1 release notes
ISSUE 54521: (Oloremo) [Regression] Failhard, batch and retcodes (refs: 54806)
* (Oloremo) [Regression] Batch with failhard fix
433b6fa Merge pull request 54806 from Oloremo/failhard-batch-fix-2019.2.1
6684793 Merge branch '2019.2.1' into failhard-batch-fix-2019.2.1
3e0e928 Added tests for cli and runner
2416516 Made batch work properly with failhard in cli and runner
ISSUE 54820: (OrangeDog) schedule.present not idempotent when scheduler disabled \
(refs: 54828)
* (garethgreenaway) [2019.2.1] Fix global disabling code in scheduler
ed94aa5 Merge pull request 54828 from \
garethgreenaway/54820_fix_schedule_disabled_job_enabled_bug
be15a28 Rework code that handles individual jobs being disabled and scheduler \
being globally being disabled. Previously disabling the schedule would result in \
individual jobs being disabled when they were run through eval. This change does \
not change schedule items.
* (Akm0d) fix broken salt-cloud openstack query
435b40c Merge pull request 54778 from Akm0d/master_openstack_query_fix
ba4ba2a fixed pylint errors in openstack test
d9a8517 Added openstack tests for openstack --query fix
59214ad Fallback to image id if we don't have an image name
3a42a4d fixed pylint error
0074d18 created unit tests for openstack
4255e3e Merge branch '2019.2.1' of into HEAD
1c2821b Return a configured provider, not a bool
c585550 fix broken salt-cloud openstack query
ISSUE 54762: (margau) 2019.2.1: Breaks Minion-Master Communication (refs: 54784, \
54823, 54807)
* (dhiltonp) ip_bracket can now accept ipv6 addresses with brackets
93b1c4d Merge pull request 54823 from dhiltonp/maybe-bracket
faa1d98 ip_bracket can now accept ipv6 addresses with brackets
ISSUE 54762: (margau) 2019.2.1: Breaks Minion-Master Communication (refs: 54784, \
54823, 54807)
* (dwoz) Fix pip state pip >=10.0 and <=18.0
* (OrlandoArcapix) Fix import of pip modules (refs: 54807)
b61b30d Merge pull request 54807 from dwoz/patch-2
664806b Add unit test for pip state fix
e637658 Revert change to pip version query
42810a2 Fix import of pip modules
ISSUE 54741: (kjkeane) Schedulers Fail to Run (refs: 54799)
* (garethgreenaway) Fix to scheduler when job without a time element is run with \
schedule.run_job
4ee1ff6 Merge pull request 54799 from \
garethgreenaway/54741_run_job_fails_without_time_element
44caa81 Merge branch '54741_run_job_fails_without_time_element' of \
github.com:garethgreenaway/salt into 54741_run_job_fails_without_time_element
3ae4f75 Merge branch '2019.2.1' into 54741_run_job_fails_without_time_element
8afd2d8 Removing extra, unnecessary code.
549cfb8 Fixing test_run_job test to ensure the right data is being asserted. \
Updating unit/test_module_names.py to include \
integration.scheduler.test_run_job.
7d716d6 Fixing lint.
ec68591 If a scheduled job does not contains a time element parameter then \
running that job with schedule.run_job fails with a traceback because \
data['run'] does not exist.
* (Ch3LL) Fix state.show_states when sls file missing in top file
b90c3f2 Merge pull request 54785 from Ch3LL/fix_show_states
96540be Clean up files after state.show_states test
ad265ae Fix state.show_states when sls file missing
ISSUE 54768: (paul-palmer) 2019.2.1 Some Jinja imports not found (refs: 54780)
ISSUE 54765: (awerner) 2019.2.1: Jinja from import broken (refs: 54780)
* (dwoz) Fix masterless jinja imports
b9459e6 Merge pull request 54780 from dwoz/fix-masterless-jinja-imports
5d873cc Merge branch '2019.2.1' into fix-masterless-jinja-imports
e901a83 Add regression tests for jinja import bug
3925bb7 Fix broken jinja imports in masterless salt-call
ISSUE 54776: (javierbertoli) Setting ping_interval in salt-minion's config \
(version 2019.2.1) prevents it from starting (refs: 54777)
* (javierbertoli) Fix minion's remove_periodic_callback()
4c240e5 Merge pull request 54777 from netmanagers/2019.2.1
459c790 Merge branch '2019.2.1' into 2019.2.1
* (bryceml) improve lint job
83f8f5c Merge pull request 54805 from bryceml/2019.2.1_update_lint_salt
ffa4ed6 improve lint job
fa1a767 Merge branch '2019.2.1' into 2019.2.1
ISSUE 54751: (jnmatlock) NXOS_API Proxy Minions Error KeyError: \
'proxy.post_master_init' after upgrading to 2019.2.1 (refs: 54783)
* (garethgreenaway) Ensure metaproxy directory is included in sdist
6b43fbe Merge pull request 54783 from \
garethgreenaway/54751_fixing_missing_metaproxy_directory
67d9938 Merge branch '2019.2.1' into 54751_fixing_missing_metaproxy_directory
a35e609 Adding __init__.py to metaproxy directory so that metaproxy is included \
when running setup.py.
ISSUE 54762: (margau) 2019.2.1: Breaks Minion-Master Communication (refs: 54784, \
54823, 54807)
* (dhiltonp) fix dns_check to return uri-compatible ipv6 addresses, add tests
7912b67 Merge pull request 54784 from dhiltonp/ipv46
042a101 Merge branch '2019.2.1' into ipv46
* (frogunder) Add 2019.2.2 release notes
2f94b44 Merge pull request 54779 from frogunder/releasenotes_2019.2.2
67f564b Add 2019.2.2 release notes
ac6b54f Merge branch '2019.2.1' into ipv46
93ebd09 update mock (py2) from 2.0.0 to 3.0.5
37bcc4c fix dns_check to return uri-compatible ipv6 addresses, add tests
dd86c46 Merge pull request 1 from waynew/pull/54777-callback-typo
a57f7d0 Add tests
c19d0b0 Fix minion's remove_periodic_callback()
* (pizzapanther) Fix returners not loading properly
46bec3c Merge pull request 54731 from pizzapanther/not-so-__new__-and-shiny
bdf24f4 Make sure we tests salt-master's event_return setting
5499518 remove unnecessary import
3f8a382 fix module import
0746aa7 remove __new__ method since it was removed from parent class
* (bryceml) 2019.2.1 ruby
e2b86bf Merge pull request 54706 from bryceml/2019.2.1_ruby
168a6c1 switch to ruby 2.6.3
Log message:
salt: Limit to python27.
There are reports of some modules failing with Python 3.x so best to be more
compatible for now. Bump PKGREVISION.
Log message:
PKGREVISION bump for anything using python without a PYPKGPREFIX.
This is a semi-manual PKGREVISION bump.
Log message:
salt: updated to 2019.2.0
2019.2.0:
- NON-BACKWARD-COMPATIBLE CHANGE TO YAML RENDERER
- ANSIBLE PLAYBOOK STATE AND EXECUTION MODULES
- NETWORK AUTOMATION
- NEW DOCKER PROXY MINION
- GRAINS DICTIONARY PASSED INTO CUSTOM GRAINS
- MORE PRECISE VIRTUAL GRAIN
- CONFIGURABLE MODULE ENVIRONMENT
- “VIRTUAL PACKAGE” SUPPORT DROPPED FOR APT
- MINION STARTUP EVENTS
- FAILHARD CHANGES
- PASS THROUGH OPTIONS TO FILE.SERIALIZE STATE
- FILE.PATCH STATE REWRITTEN
- NEW NO_PROXY MINION CONFIGURATION
- CHANGES TO SLACK ENGINE
- ENHANCEMENTS TO WTMP BEACON
Log message:
salt: updated to 2018.3.3
SALT 2018.3.3
CVE-2018-15751 Remote command execution and incorrect access control when using \
salt-api.
CVE-2018-15750 Directory traversal vulnerability when using salt-api. Allows an \
attacker to determine what files exist on a server when querying /run or \
/events.
Improves timezone detection by using the pytz module.
The tojson filter (from Jinja 2.9 and later) has been ported to Salt, and will \
be used when this filter is not available. This allows older LTS releases such \
as CentOS 7 and Ubuntu 14.04 to use this filter. | https://pkgsrc.se/commits.php?path=sysutils/salt&offset=0 | CC-MAIN-2021-49 | refinedweb | 3,979 | 56.86 |
Recently I needed a smart way to execute functions within a specified time limit. If the function is unable to complete execution within that limit, it should stop processing and return back to the caller. Here I am describing a method for writing timeout functions and the problems we may face. Here we deal with a helper class that can be used to write timeout functions easily without having a deep knowledge of threading. Using this helper class, user can do the following:
Consider the following code,
<small>Code listing : 1</small>
When a .NET application starts, it creates a thread which will be the main thread for that application. When this thread ends, the application will also end. In the above example, DoLongRunningJob is executed from the main thread and this operation blocks the main thread until DoLongRunningJob finishes. Since the main thread is blocked, we will not be able to stop this method when the timeout reaches.
DoLongRunningJob
The remedy to the above mentioned problem is running the DoLongRunningJob in a new thread and joining the main thread to the new thread using a timeout value. The System.Threading.Thread class provides a Join(TimeSpan) method which can accept a timeout value and blocks the calling thread until the thread finishes its operation or a timeout reaches. The following code shows DoLongRunningJob time out after 2 seconds.
System.Threading.Thread
Join(TimeSpan)
<small>Code listing : 2</small>
We started DoLongRunningJob in a new thread and joined the main thread to it with a timeout of two seconds. Join will return to the caller when timeout reaches. But the worker thread will be executing still. To stop the worker thread, we use the Abort function. Output of the above code looks like
Join
Abort
I have created a class called TimeoutProcess which helps to implement the timeout functions more easily. Here is the class diagram
TimeoutProcess
TimeoutProcess has a Start(object,TimeSpan,WaitCallback) method, which starts a new thread and invokes the WaitCallback delegate. It then calls Join on the newly created thread with the specified timeout value. When the specified timeout reaches, Join returns FALSE. Here is the Start method:>
When the time limit reaches, ProcessTimeout calls Abort on the worker thread to stop it immediately. Calling Abort on a thread raises ThreadAbortException at the location where thread is currently executing and attempts to stop the thread. This stops the worker thread and returns the control back to the caller almost immediatly. ThreadAbortException is a special kind of exception which will be re-thrown at the end of the catch block and it will not crash the application like other exceptions.</small>
The Start method in the TimeoutProcess class blocks the calling thread for the specified time or until the process completes. Sometimes we may have to run many processes simultaneously and each with a timeout limit. Since the Start method blocks, we will not be able to run multiple timeout processes simultaneously. To solve this, let us include some non-blocking methods to the TimeoutProcess class.
Note : WaitCallback is a delegate declared in System.Threading namespace.
System.Threading
In the TimeoutProcess class, a new method ( StartAsync(object,TimeSpan,WaitCallback)) is added to start a timeout process and will be returning to the caller immediately. The caller can subscribe to the AsyncProcessCompleted event which will be fired when the process is complete or timed out. The AsyncProcessEventArgs.HasProcessCompleted property can be used to determine the process completion status. This property returns FALSE if the function is timed
public override bool Start(DataCarrier dataCarrier) {
this.IncrementAsyncProcessCount();
return ThreadPool.QueueUserWorkItem(StartAsyncProcess, dataCarrier);
}
void StartAsyncProcess(object state) {
DataCarrier data = state as DataCarrier;
WaitCallback methodToExecute = data.MethodToExecute;
Thread asyncWorker = new Thread(delegate(object obj)
{
base.ExecuteMethod(data.UserState, methodToExecute);
});
asyncWorker.IsBackground = true;
asyncWorker.Start();
bool success = asyncWorker.Join(data.TimeOut);
this.DecrementAsyncProcessCount();
AsyncProcessEventArgs args = new AsyncProcessEventArgs(data.UserState, success);
if (!success)
ProcessTimeout(asyncWorker, args, data.TimeOut);
OnAsyncProcessCompleted(args);
}
You can see this method uses two threads, one for running the async thread and the other for running the process. The first thread, is a thread pool thread, which starts asyncWorker thread and calls Join on it. It then raises the AsyncProcessCompleted event to notify the process completion. The TimeoutProcess.AsyncProcessCount property can be used to get the number of async processes currently executing.
async
asyncWorker
TimeoutProcess.AsyncProcessCount
The following test illustrates the usage of async timeout process.
<small>Code listing : 9</small>
When the timeout reaches, the worker thread will be aborted forcefully. If the method we are executing uses unmanaged code, the thread will be aborted when it reaches the next managed statement. This makes the worker thread to run for more than the time limit. When the timeout reaches, Abort is called on the worker thread and fires the TimeoutProcess.AsyncProcessCompleted event. Sometimes the worker thread will not abort immediatly and will be running in the abort requested state.
TimeoutProcess.AsyncProcessCompleted
In such cases, an overload of TimeoutProcess.StartAsync allows you to specify the grace/excess time needed to wait for a thread to abort. This is possible by calling Join on the thread with a timeout value after calling Abort. Code listing : 10 shows AsyncTimeoutWorker.ProcessTimeout method. Default grace period is 1 sec.
If you look at the ProcessTimeout method listed in Code listing 10, you can see that it calls Abort on the specified thread. This will request the thread to abort immediatly by throwing exception. If your code is executing abort unsafe methods, chances are they're for uncleaned resources such as file handles.
Calling Abort on a thread is safe, when the current location of the thread is known. When Abort is called from a different thread, it is tough to identify the exact location. Since the calling of Abort function is unpredictable, it is always good to keep your cleanup logic in finally blocks. In most cases, the finally block is executed when a thread aborts. It is recommended not to write blocking code in the finally block as it may affect the time to abort.
finally
The other way to cleanup resources is by running the timeout method in a new application domain. If the thread is not aborting after the timeout period, you can unload the application domain manually after calling abort. Unloading an application domain will stop all active threads and release the resources used by them. If the thread is still unable to abort while unloading an application domain, an exception of type CannotUnloadAppDomainException [^] will be thrown.
Here is a sample program which executes the method on a new application domain and unloads it if the thread does not stop after the specified time.
<small>Code listing : 11</small>
The methods described in this article calls Abort on a thread from another thread, which can be considered as a bad practice. Aborting a thread using any safe abort techniques, calling abort from the same thread or using a boolean variable to signal abort, is always a good practice. However, the disadvantage of relying on such kind of methods is that, if the thread is blocked, there is no way to check the abort condition. Consider the following code.
<small>Code listing : 12</small>
In the above code, the while(!timedOut) will not be executed for all the time as ExecuteBlockingCode() blocks this thread. If the thread is blocked due to executing managed statements, Thread.Interrupt can be used which will throw ThreadInterruptedException [^] and continues execution until it blocks next time. This will check the condition (while(!timedOut)). But if thread is blocked because of unmanaged code, interupt won't work. This is the reason for using abort to stop the thread forecefully.
while(!timedOut)
ExecuteBlockingCode()
Thread.Interrupt
Running functions with a timeout limit is helpful when you are not sure about the time required to execute the function. The TimeoutProcess class discussed in this article provides an easy method to run functions within a time limit. This class executes the supplied method in a new thread, so if your method is updating UI, you should take precautions to avoid cross thread communication errors.
When non-blocking timeout methods are executing, there will be resource overhead as it uses two threads to execute the method. Please suggest a better approach if you have any.
That's all with this article. I hope you find this article helpful. I'd appreciate if you rate. | https://www.codeproject.com/articles/31691/timeout-functions?fid=1532377&df=90&mpp=10&sort=position&spc=none&tid=3717412 | CC-MAIN-2017-09 | refinedweb | 1,401 | 56.55 |
Well,()
Broadcast
SCREEN_OFF
public class ReceiverScreen extends BroadcastReceiver {;
}
}
});
}
();
}
}
Phew. This is quite a contended question, with a great deal of commentary behind it.
Let me begin by rephrasing your question a bit. If I understand clearly, you'd like to disable all physical buttons on the device for the duration of your activity. This is inclusive of the power button, which you detect by handling the
ACTION_SCREEN_OFF intent. Your current (successful) workaround for this scenario is to broadcast an
ACTION_SCREEN_ON, kicking the screen back to life when it's turned off, provided the host implements this correctly.
You'd now like to go the extra mile, by rendering this action unnecessary, if (and only if) you are able to catch and handle
ACTION_SCREEN_OFF before it gets sent to the system. Is this possible, and if so, how?
This bears some discussion. The short version, however, is simple: this is not possible, without custom modification to your firmware or the core of the Android operating system, for a limited number of devices.
The Android system, as far as is documented, defines this as a broadcast action. Following the publish-subscribe pattern of message propagation, this message will notify all concerned parties of this action. Because this message is sent by the system, because the message stack is managed by the system, and because the message is also received by the system, your code simply isn't injected in the right place to block the reception of this message.
Furthermore, for some devices, this will be a physical switch that has no programmatic interrupt whatsoever. At best, the Android system can hope to handle for the event when it happens, which is precisely why this broadcast message is something of a special case in the service stack. To the best of my knowledge and based upon the sparse documentation on this scenario, this is why it's not an out-of-the-box, supported feature, before we consider any of the possible vectors for abuse.
Your best recourse is actually a much simpler one, if you have the ability to modify the physical hardware for the device in question: restrict access to, mangle, or otherwise disable the physical power button. In many scenarios this is undesirable, but this works in situations where your Android device is being used, for example, as a point-of-sale or a public service machine. If this is unworkable, placing physical restrictions on access to the power button may be all that's required, handling for the remainder of cases (for example, spot attempts to toggle the screen) by sending
ACTION_SCREEN_ON.
Just remember, this strategy isn't foolproof. Do this competently and document the procedure well, lest you become fodder for the next 2600 exposé.
Best of luck with your application. | https://codedump.io/share/1UBkEzTtr67q/1/override-power-button-just-like-home-button | CC-MAIN-2018-17 | refinedweb | 464 | 50.67 |
quick hint: you really want pulseaudio-alsa. If you dont have a asound.conf you are missing that package.]]>
please mark your thread as solved]]>
Yeah I noticed it just before you posted. Now it works correctly. Thank you for help and sorry about my stupidity. ^^
Btw. I can't understand how the heck it worked properly before the update ...
Yes, I use X.
And yes, I know what's the problem with Pulseaudio - the tip in Arch Wiki didn't help.
Edit: Oh, I only tried that workaround, I didn't try to change user. I'll edit mpd.conf when I come back home.
according to your config, you used that workaround wrongly. it will only work, if you point to the pulse server IP in mpd.conf. So add the server line in your pulse output. (its most likely 127.0.0.1)]]>
Yes, I use X.
And yes, I know what's the problem with Pulseaudio - the tip in Arch Wiki didn't help.
Edit: Oh, I only tried that workaround, I didn't try to change user. I'll edit mpd.conf when I come back home.]]>
*sigh* read the wiki.
In short: you are running mpd as user "mpd" but the pulse daemon belongs to your login user. either change the mpd user to your own user or use a workaround.
in long: … pd_user.29
Do you use X?]]>
After update of Pulseaudio (1.04) I mpd doesn't work - there's no problem with other applications, only with mpd. I can't set volume and mpc says that there are problems with opening audio device:
eregus@arch ~ $ mpc Black River - Street Games [paused] #769/775 0:00/3:45 (0%) volume: n/a repeat: off random: off single: off consume: off ERROR: problems opening audio device
There's my /etc/mpd.conf:
music_directory "/mnt/sda3/music" playlist_directory "/var/lib/mpd/playlists" db_file "/var/lib/mpd/mpd.db" log_file "syslog" pid_file "/run/mpd/mpd.pid" state_file "/var/lib/mpd/mpdstate" user "mpd" auto_update "yes" input { plugin "curl" } audio_output { type "pulse" name "pulse audio" }
I use ALSA + Pulseaudio. My /etc/pulse/default.pa:
.nofail .fail load-module module-device-restore load-module module-stream-restore load-module module-card-restore load-module module-augment-properties load-module module-alsa-sink device=dmix load-module module-alsa-source device=dsnoop .ifexists module-udev-detect.so .else .endif .ifexists module-jackdbus-detect.so .nofail load-module module-jackdbus-detect .fail .endif .ifexists module-bluetooth-policy.so load-module module-bluetooth-policy .endif .ifexists module-bluetooth-discover.so load-module module-bluetooth-discover .endif .ifexists module-esound-protocol-unix.so load-module module-esound-protocol-unix .endif load-module module-native-protocol-unix load-module module-native-protocol-tcp auth-ip-acl=127.0.0.1 .nofail load-module module-console-kit .fail
That's all. I would post /etc/asound.conf, but it seems that from last update it doesn't exist.
Thank you for any help | https://bbs.archlinux.org/extern.php?action=feed&tid=160740&type=atom | CC-MAIN-2016-40 | refinedweb | 500 | 53.98 |
Defining Packages and Namespaces
In Visual Studio Ultimate, a package is a container for the definitions of UML elements such as classes, use cases, and components. A package can also contain other packages.
In UML Model Explorer, all the definitions inside a package are nested underneath the package. The UML model is a kind of package, and forms the root of the tree.
Packages are useful for separating work into different areas. Each package defines a namespace so that names that are defined in different packages do not conflict with each other.
The qualified name property of each element is the qualified name of the package to which it belongs, followed by the element's own name. For example, if your package is called MyPackage, a class within the package will have a qualified name like MyPackage::MyClass. Because every element is contained inside a model, every qualified name begins with the model's name.
A model also defines a namespace, so that the qualified name of every element in a model begins with the name of the model.
Other model elements also define namespaces. For example, an operation belongs to the namespace defined by its parent class, so that its qualified name is like MyModel ::MyPackage ::MyClass ::MyOperation. In the same manner, an action belongs to the namespace defined by its parent activity.
Packages are containers. If you move or delete a package, the classes, packages, and other things defined inside it are also moved or deleted. The same is true of other elements that define namespaces.
You can create a package either on a UML class diagram, or in UML Model Explorer.
To create a package in a UML class diagram
Open a UML class diagram, or create a new one.
Click the Package tool.
Click anywhere on the diagram. A new package shape will appear.
You can click inside an existing package to nest one package in another.
Type a new name for the package.
To create a package in UML Model Explorer
Open UML Model Explorer. On the Architecture menu, point to Windows, and then click the UML Model Explorer.
Right-click a package or a model to which you want to add a new package.
Point to Add and then click Package.
A new package appears in the model.
Type a new name for the package.
If you have created a package in UML Model Explorer, you can display it on a UML class diagram. You can also display a package on more than one UML class diagram.
To show an existing package on a UML Class Diagram
Drag the package from UML Model Explorer onto the class diagram.
There are four ways in which you can place model elements inside a package:
Add a new element to a package in UML Model Explorer.
Add classes and other types to packages in a UML class diagram.
Set the LinkedPackage property of a diagram so that new elements created on the diagram are placed inside the package you specify. Class diagrams, component diagrams, and use-case diagrams can be linked to a package in this manner.
Move elements into or out of a package in UML Model Explorer.
An element in a package appears underneath the package in UML Model Explorer, and its qualified name begins with the qualified name of the package. To see the qualified name of any element, right-click the element and then click Properties. The Qualified Name property appears in the Properties window.
To create an element in a package in UML Model Explorer
Open UML Model Explorer. On the View menu, point to Other Windows, and then click UML Model Explorer.
Right-click a package or a model to which you want to add a new element.
Point to Add, and then click the kind of element that you want to add.
The new element appears underneath the package.
Type a name for the new element.
To create an element in a package on a UML class diagram
Open a class diagram on which the package appears.
Create a new package, if you have not already done this.
To make an existing package appear on a class diagram, you can drag the package from UML Model Explorer onto the class diagram.
Click the tool for a class, interface, or enumeration, or package.
Click the package where you want to put the new element.
The new element appears inside the package.
To create all the elements of a diagram in a specified package
Create the package, if you have not already done this.
Open a component diagram, use case diagram, or UML class diagram.
Open the properties of the diagram. Right-click in a blank part of the diagram and then click Properties.
In the Linked Package property, choose the package that you want to contain the diagram's content.
Create new elements in the diagram. These will be placed into the package.
The Qualified Name of each element will begin with the package's qualified name.
In UML Model Explorer, each element will appear under the package.
You can move one or more elements in or out of a package.
If you move a package, everything inside it moves with it.
To move an element into or out of a package
In UML Model Explorer, drag the element into or out of the tree whose root is the package.
The qualified name of the element will change to show its new owning package or model.
- or -
In a class diagram, drag the element into a package shape.
The qualified name of the element will change to show its new owning package.
You can paste an element into a package. If you paste a group of related elements into a package, the relationships between them will also be pasted.
To paste elements into a package on a UML class diagram
On a UML class diagram, select all the elements that you want to copy. Right-click one of them and then click Copy.
Right-click the package and then click Paste.
You can define an import relationship between packages, using the Import tool.
Import means that the elements defined in the imported package, which are the elements at the arrow end of the relationship, are effectively defined also in the importing package. Any elements whose visibility is defined as Package will be visible also in the importing package.
Avoid creating loops in import relationships.
If you want to refer to an element of one package from another, you must use the element's qualified name.
For example, suppose that package SalesCommon defines type CustomerAddress. In another package RestaurantSales, you want to define a type MealOrder, which has an attribute of type Customer Address. You have two options:
Specify the type of the attribute using the fully qualified name SalesCommon::CustomerAddress. You should do this can only if CustomerAddress has its Visibility property set to Public.
Create an Import relationship from the RestaurantSales package to the SalesCommon package. Then you can use CustomerAddress without using its qualified name.
When you create a new package, a new .uml file is created in the ModelDefinition project folder. The root model, which is also a package, is also stored in a .uml file.
In addition, each diagram is stored in two files, one that represents the diagram's shapes, and a .layout file that records the positions of the shapes. | https://msdn.microsoft.com/en-us/library/dd465144(v=vs.110).aspx | CC-MAIN-2018-05 | refinedweb | 1,235 | 65.83 |
- Write a java program using following details. You are free to make all necessary assumptions. All the assumptions made should be documented.
There are four scientists who need to be ordered according to their smartness (smartest to least smart). There is a text file “smart.txt” in the following format:
Satish ArunRamesh SureshRamesh SatishSuresh Satish
Each line has a pair of nacmes, separated by an arbitrary number of white spaces (’ ’), where the person named by the first element of the pair is smarter than the person named by the second element of the pair. There is no limit to the number of such pairs listed in the file, but the listing would be sufficient to resolve the order of smartness of the four scientists.
Write a java program (ScientistResolver.java) that takes such a file and prints the list of all the distinct scientist names, without duplicates, one per line, ordered according to their smartness, as below.
Usage: java ScientistResolver smart.txt Result: Ramesh Suresh Satish Arun
slution:
import java.io.*; import java.util.*; class ScientistResolver { public static void main(String[] args) throws IOException { //String arr[]=new String[100]; //int s; try { FileReader fr=new FileReader("smart.txt"); BufferedReader br = new BufferedReader(fr); String str; String a[]=new String[100]; int i=0; while((str=br.readLine())!=null) { StringTokenizer st=new StringTokenizer(str," "); while(st.hasMoreTokens()) { String s=st.nextToken(); a=s; System.out.println(a);i++; } for ( i=0;i<a.length; i++ ) { //if(!a.equals(a[i+1])) } //System.out.println(str); //fr.close(); } } catch ( Exception e) { System.out.println(e); } //System.out.println("Hello World!"); } }
i coulnot sort them according to their smartness.how to sort them accoeding to their smartness to get that out put | https://www.daniweb.com/programming/software-development/threads/76181/sorting-members | CC-MAIN-2021-43 | refinedweb | 289 | 59.9 |
/* ** (c) COPYRIGHT MIT 1995. ** Please first read the full copyright statement in the file COPYRIGH. */
The Host class manages what we know about a remote host. This can for example be what type of host it is, and what version it is using. Notice that a host object can be used to describe both a server or a client - all information in the Host object can be shared regardless of whether it is to be used in a server application or a client application.
This module is implemented by HTHost.c, and it is a part of the W3C Sample Code Library.
#ifndef HTHOST_H #define HTHOST_H typedef struct _HTHost HTHost; #define HOST_HASH_SIZE HT_M_HASH_SIZE #include "HTChannl.h" #include "HTReq.h" #include "HTEvent.h" #include "HTProt.h" #include "HTTimer.h"
The Host class contains information about the remote host, for example the type (HTTP/1.0, HTTP/1.1, FTP etc.) along with information on how the connections can be used (if it supports persistent connections, interleaved access etc.)
We keep a cache of information that we know about a remote host. This allows us to be much more detailed in generating requests. Search the host info cache for a host object or create a new one and add it. Examples of host names are
extern HTHost * HTHost_new (char * host, u_short u_port); extern HTHost * HTHost_newWParse(HTRequest * request, char * url, u_short u_port); extern int HTHost_hash (HTHost * host);
The Host Class contains an automatic garbage collection of Host objects so that we don't keep information around that is stale.
Searches the cache of known hosts to see if we already have information about this host. If not then we return NULL.
extern HTHost * HTHost_find (char * host);
Cleanup and delete the host table.
extern void HTHost_deleteAll (void);
You can use this function to see whether a host object is idle or in use. We have several modes describing how and when a host is idle. This is a function of the Transport Object
extern BOOL HTHost_isIdle (HTHost * host);
We keep track of the capabilities of the host in the other end so thatwe may adjust our queries to fit it better
Get the name of the remote host. This is set automatically when a new Host object and can be asked for at any point in time. You can not change the host name but must create a new Host object instead.
extern char * HTHost_name (HTHost * host);
Define the host class of the host at the other end. A class is a generic description of the protocol which is exactly like the access method in a URL, for example "http" etc. The host version is a finer distinction (sub-class) between various versions of the host class, for example HTTP/0.9, HTTP/1.1 etc. The host version is a bit flag that the protocol module can define on its own. That way we don't have to change this module when registering a new protocol module. The host type is a description of whether we can keep the connection persistent or not.
extern char * HTHost_class (HTHost * host); extern void HTHost_setClass (HTHost * host, char * s_class); extern int HTHost_version (HTHost * host); extern void HTHost_setVersion (HTHost * host, int version);
A server can inform a client about the supported methods using the
Public header.
extern HTMethod HTHost_publicMethods (HTHost * me); extern void HTHost_setPublicMethods (HTHost * me, HTMethod methodset); extern void HTHost_appendPublicMethods (HTHost * me, HTMethod methodset);
A server can send its server application name and version in a HTTP response. We pick up this information and add it to the Host object
extern char * HTHost_server (HTHost * host); extern BOOL HTHost_setServer (HTHost * host, const char * server);
A client can send the name of the client application in a HTTP request. We pick up this information and add it to the Host Object
extern char * HTHost_userAgent (HTHost * host); extern BOOL HTHost_setUserAgent (HTHost * host, const char * userAgent);.
You can also check whether a specific range unit is OK. We always say
YES except if we have a specific statement from the server that
it doesn't understand byte ranges - that is - it has sent "none" in a
"Accept-Range" response header
extern char * HTHost_rangeUnits (HTHost * host); extern BOOL HTHost_setRangeUnits (HTHost * host, const char * units); extern BOOL HTHost_isRangeUnitAcceptable (HTHost * host, const char * unit);
This can be used for anything that the application would like to keep tabs on.
extern void HTHost_setContext (HTHost * me, void * context); extern void * HTHost_context (HTHost * me);
Requests are queued in the Host object until we have resources to start them. The request is in the form of a Net object as we may have multiple socket requests per Request object. This is for example the case with FTP which uses two connections.
extern int HTHost_addNet (HTHost * host, HTNet * net); extern BOOL HTHost_deleteNet (HTHost * host, HTNet * net, int status); extern HTList * HTHost_net (HTHost * host);
A Channel object is an abstraction for a transport, like a TCP connection, for example. Each host object can have at most one channel object associated with it.
As a Net Object doesn't necessarily know whether there is a channel up and running and whether that channel can be reused, it must do an explicit connect the the host.
extern int HTHost_connect (HTHost * host, HTNet * net, char * url); extern int HTHost_accept (HTHost * host, HTNet * net, char * url); extern int HTHost_listen (HTHost * host, HTNet * net, char * url);
As soon as we know that a channel is about to close (for example because the server sends us a Connection: close header field) then we register this informtation in the Host object:
extern BOOL HTHost_setCloseNotification (HTHost * host, BOOL mode); extern BOOL HTHost_closeNotification (HTHost * host);
Here you can find an already associated channel with a host object or you can explicitly associate a channel with a host object.
extern BOOL HTHost_setChannel (HTHost * host, HTChannel * channel); extern HTChannel * HTHost_channel (HTHost * host);
When a channel is deleted, it must be unregistered from the host object which is done by this operation:
extern BOOL HTHost_clearChannel (HTHost * host, int status);
The way a channel can be used depends on the transport and what mode the channel is in. The mode (whether we can use persistent connections, pipeline, etc.) may change mode in the middle of a connection If the new mode is lower than the old mode then adjust the pipeline accordingly. That is, if we are going into single mode then move all entries in the pipeline and move the rest to the pending queue. They will get launched at a later point in time.
extern HTTransportMode HTHost_mode (HTHost * host, BOOL * active); extern BOOL HTHost_setMode (HTHost * host, HTTransportMode mode);
There are two ways we can end up with pending requests:
This set of functions handles pending host objects and can start new requests as resources get available. The first function checks the host object for any pending Net objects and return the first of these Net objects.
extern HTNet * HTHost_nextPendingNet (HTHost * host);
The second checks the list of pending host objects waiting for a socket and returns the first of these Host objects.
extern HTHost * HTHost_nextPendingHost (void);
Start the next pending request if any. First we look for pending requests for the same host and then we check for any other pending hosts. If nothing pending then register a close event handler to have something catching the socket if the remote server closes the connection, for example due to timeout.
extern BOOL HTHost_launchPending (HTHost * host);
Controls whether pending requests should be automatically activated. The default is on, but if turned off then no pending requests are launched.
extern void HTHost_enable_PendingReqLaunch (void); extern void HTHost_disable_PendingReqLaunch (void);
We don't want more than (Max open sockets) - 2 connections to be persistent in order to avoid deadlock. You can set the max number of simultaneous open connection in the HTNet manager.
extern BOOL HTHost_setPersistent (HTHost * host, BOOL persistent, HTTransportMode mode); extern BOOL HTHost_isPersistent (HTHost * host);
If the server doesn't close the connection on us then we close it after a while so that we don't unnecessarily take up resources (see also how the timeouts of individual requests can be set). Libwww provides two mechanisms: an active timeout and a passive timeout. The former uses libwww timers and is the preferred mechanism, the latter passively looks at the Host object when a new request is issued in order to determine whether the existing channel can be reused. This is primariliy for non-preemptive requests which in general is deprecated.
By default we have an active timeout of 60 secs and a passive timeout of 120 secs (the latter is longer as this is less reliable). Active timeout s can be accessed using these functions:
extern BOOL HTHost_setActiveTimeout (ms_t timeout); extern ms_t HTHost_activeTimeout (void);
and passive timeouts can be accessed using these functions
extern time_t HTHost_persistTimeout (void); extern BOOL HTHost_setPersistTimeout (time_t timeout);
The following two functions are deprecated:
extern void HTHost_setPersistExpires (HTHost * host, time_t expires); extern time_t HTHost_persistExpires (HTHost * host);
Another way to detect when a connection is about to close is to count the number of requests made. For example, the (current) default bevaior by most Apache servers is to close a TCP connection after 100 requests. I don't quite think it makes sense to control the close of a connection like this but anyway, there we go.
extern void HTHost_setReqsPerConnection (HTHost * host, int reqs); extern int HTHost_reqsPerConnection (HTHost * host); extern void HTHost_setReqsMade (HTHost * host, int reqs); extern int HTHost_reqsMade (HTHost * host);
Which Net object can read and/or write? When doing pipelining, we essentially serialize requests and therefore we must keep track of who can read and who can write.
extern HTNet * HTHost_firstNet (HTHost * host); extern HTNet * HTHost_getReadNet (HTHost * host); extern HTNet * HTHost_getWriteNet (HTHost * host);
extern HTInputStream * HTHost_getInput (HTHost * host, HTTransport * transport, void * param, int mode); extern HTOutputStream * HTHost_getOutput (HTHost * host, HTTransport * tp, void * param, int mode);
Because of the push streams, the streams must keep track of how much data actually was consumed by that stream.
extern int HTHost_read(HTHost * host, HTNet * net); extern BOOL HTHost_setConsumed(HTHost * host, size_t bytes); extern BOOL HTHost_setRemainingRead(HTHost * host, size_t remainaing); extern size_t HTHost_remainingRead (HTHost * host);
When possible, we try to pipeline requests onto the same connection as this saves a lot of time and leads to much higher throughput.
Use these functions to set the max number of requests that can be pipelined at any one time on a single, persistent connection. The higher the number, the more we have to recover if the server closes the connection prematurely. The default is about 50 requests which is enough to fill most links.
extern BOOL HTHost_setMaxPipelinedRequests (int max); extern int HTHost_maxPipelinedRequests (void);
You can query how many Het objects (essentially requests) are outstanding or pending on a host object using these methods:
extern int HTHost_numberOfOutstandingNetObjects (HTHost * host); extern int HTHost_numberOfPendingNetObjects (HTHost * host);
Pipelines normally run by themselves (requests are issued and responses recieved). However, it may be necessry to either prematurely abort a pipeline or to recover a broken pipeline due to communication problems with the server. In case a pipeline is broken then we have to recover it and start again. This is handled automatically by the host object, so you do not have to call this one explicitly.
extern BOOL HTHost_recoverPipe (HTHost * host); extern BOOL HTHost_doRecover (HTHost * host);
Call this function to terminate all requests (pending as well as active) registered with a host object. This is typically the function that handles timeout, abort (user hits the red button, etc). You can also use the HTNet object kill method which in terms call this function.
extern BOOL HTHost_killPipe (HTHost * host);
These functions are used to register and unregister events (read, write, etc.) so that the host object knows about it.
extern int HTHost_register(HTHost * host, HTNet * net, HTEventType type); extern int HTHost_unregister(HTHost * host, HTNet * net, HTEventType type); extern int HTHost_tickleFirstNet(HTHost * host, HTEventType type); extern SockA * HTHost_getSockAddr(HTHost * host);
Events can be assigned a timeout which causes the event to be triggered if the timeout happens before other action is available on the socket. You can assign a global timeout for all host object using the following methods. The default is no timeout.
extern int HTHost_eventTimeout (void); extern void HTHost_setEventTimeout (int millis);
These methods can control how long we want to wait for a flush on a pipelined channel. The default is 30ms which is OK in most situations.
extern BOOL HTHost_setWriteDelay (HTHost * host, ms_t delay); extern ms_t HTHost_writeDelay (HTHost * host); extern int HTHost_findWriteDelay(HTHost * host, ms_t lastFlushTime, int buffSize);
It is also possible to explicitly require a flush using the following method. This can also be set directly in the request object for a single request.
extern int HTHost_forceFlush(HTHost * host);
You can also set the global value so that all new host objects (and therefore all new requests) will inherit this value instead of setting it individually.
extern BOOL HTHost_setDefaultWriteDelay (ms_t delay); extern ms_t HTHost_defaultWriteDelay (void);
We keep track of hosts with multiple IP addresses - socalled multi-homed hosts. This is used for two things: finding the fastest IP address of that host and as a backup if one or more of the hosts are down. This is handled in connection with the DNS manager
extern BOOL HTHost_setHome (HTHost * host, int home); extern int HTHost_home (HTHost * host); extern BOOL HTHost_setRetry (HTHost * host, int retry); extern int HTHost_retry (HTHost * host); extern BOOL HTHost_decreaseRetry (HTHost * host);
A new callback plugged to the activation of a request which allows an application to know when a request has become active.
typedef int HTHost_ActivateRequestCallback (HTRequest * request); extern void HTHost_setActivateRequestCallback (HTHost_ActivateRequestCallback * cbf);
#endif /* HTHOST_H */ | http://www.w3.org/Library/src/HTHost.html | CC-MAIN-2014-15 | refinedweb | 2,258 | 56.69 |
Python SciPy is a library that has Python NumPy and Mathematical algorithms as its building blocks. The Python SciPy library is utilized to a great extent in the field of scientific computations and processing.
Getting Started with Python Scipy
In order to use the different functions offered by the SciPy library, we need to install it. To serve the purpose, we will use
pip command to install the SciPy library.
pip install scipy
In order to use the functions of this library, we will need to import this library using the following statement:
import scipy
Sub-Packages in Python SciPy
There are various sub-modules available in the SciPy library to perform and enhance the efficiency of the scientific calculations.
Some of the popular sub-modules of the SciPy library are listed below:
- special: This sub-module contains the Special functions to perform a specific task.
- constants: Represents constants.
- optimize: This sub-module contains algorithms for optimization.
- integrate: This sub-module contains functions to perform Mathematical Integration.
- interpolate: Represents functions to perform interpolation.
- linalg: Represents functions to perform operations on linear algebra equations.
- io: It contains functions to perform Input/Output operations on the given input.
- fftpack: Represents functions to perform Discrete Fourier Transform.
- signal: Represents functions and tools for Signal Processing in Python.
- sparse: Represents algorithms to deal with sparse matrices.
- cluster: Represents functions to perform hierarchical clustering.
Linear Algebra with Python SciPy
Linear Algebra represents linear equations and represents them with the help of matrices.
The
linalg sub-module of the SciPy library is used to perform all the functionalities related to linear equations. It takes the object to be converted into a 2-D NumPy array and then performs the task.
1. Solving a set of equations
Let us understand the working of the linalg sub-module along with the Linear equations with the help of an example:
4x+3y=12
3x+4y=18
Consider the above linear equations. Let us solve the equations through the
linalg.solve() function.
from scipy import linalg import numpy X=numpy.array([[4,3],[3,4]]) Y=numpy.array([[12],[18]]) print(linalg.solve(X,Y)) X.dot(linalg.solve(X,Y))-Y
In the above snippet of code, we have passed the coefficients and constant values present in the input equations through numpy.array() function.
Further,
linalg. solve() function solves the linear equations and displays the x and y value which works for that particular equation.
equation1.dot(linalg.solve())-equation2 command is used to check the output of the equations.
Output:
[[-0.85714286] [ 5.14285714]] array([[0.], [0.]])
array([[0.], [0.]]) ensures that the linear equations have been solved rightly.
[[-0.85714286] [ 5.14285714]]: These are the x and y values used to solve the linear equations.
2. Finding the Determinants of Matrices
The
linalg.det() method is used to find the determinant of the input matrix.
Example:
from scipy import linalg import numpy determinant=numpy.array([[2,4],[4,12]]) linalg.det(determinant)
Output:
8.0
3. Calculating Inverse of a Matrix
The
linalg.inv() method is used to calculate the inverse of an input matrix.
Example:
from scipy import linalg import numpy inverse=numpy.array([[2,4],[4,12]]) linalg.inv(inverse)
Output:
array([[ 1.5 , -0.5 ], [-0.5 , 0.25]])
Performing calculations on Polynomials with Python SciPy
The
poly1d sub-module of the SciPy library is used to perform manipulations on 1-d polynomials. It accepts coefficients as input and forms the polynomial objects.
Let’s understand the poly1d sub-module with the help of an example.
Example:
from numpy import poly1d # Creation of a polynomial object using coefficients as inputs through poly1d poly_input = poly1d([2, 4, 6, 8]) print(poly_input) # Performing integration for value = 4 print("\nIntegration of the input polynomial: \n") print(poly_input.integ(k=3)) # Performing derivation print("\nDerivation of the input polynomial: \n") print(poly_input.deriv())
In the above snippet of code,
poly1d() is used to accept the coefficients of the polynomial.
Further,
polynomial.integ(value) is used to find the integration of the input polynomial around the input scalar value. The
polynomial.deriv() function is used to calculate the derivation of the input polynomial.
Output:
3 2 2 x + 4 x + 6 x + 8 Integration of the input polynomial: 4 3 2 0.5 x + 1.333 x + 3 x + 8 x + 3 Derivation of the input polynomial: 2 6 x + 8 x + 6
Performing Integration with Python SciPy
The
integrate sub-module of the SciPy library is used to perform integration on the input equations.
Let’s perform integration on the following equation:
3*x*2 + 2*x + 6
from scipy import integrate integrate.quad(lambda x:3*x*2 + 2*x + 6,0,2)
In the above piece of code,
integrate.quad() function is used to calculate the integration of the input equation. It accepts the following arguments:
- equation
- upper limit
- lower limit
Output:
(28.0, 3.1086244689504383e-13)
Fourier Transforms with Python SciPy
Fourier Transforms enable us to understand and depict functions as a summation of periodic components.
The
fftpack sub-module of the SciPy library is used to perform Fourier transforms on the equations.
Example:
from scipy.fftpack import fft import numpy as np # Count of sample points n = 400 # sample spacing T = 1.0 / 500.0 x_i = np.linspace(0.0, n*T, n) y_i = np.tan(70.0 * 2.0*np.pi*x_i) + 0.5*np.tan(70.0 * 2.0*np.pi*x_i) y_f = fft(y_i) x_f = np.linspace(0.0, 1.0/(3.0*T), n//2) # matplotlib for plotting purposes import matplotlib.pyplot as plt plt.plot(x_f, 2.0/n * np.abs(y_f[0:n//2])) plt.show()
In the above snippet of code, we have used numpy.linspace() function to get evenly spaced integers. Further,
fft() function is used to calculate the Fourier value of the input. We have used the Python matplotlib module to plot the Tangent graph.
Output:
Special Functions of Python SciPy
The following is the list of some of the most commonly used Special functions from the
special package of SciPy:
- Cubic Root
- Exponential Function
- Log-Sum Exponential Function
- Gamma
1. Cubic Root
The
scipy.special.cbrt() function is used to provide the element-wise cube root of the inputs provided.
Example:
from scipy.special import cbrt val = cbrt([27, 8]) print(val)
Output:
[3. 2.]
2. Exponential Function
The
scipy.special.exp10() function is used to calculate the element-wise exponent of the given inputs.
Example:
from scipy.special import exp10 val = exp10([27, 8]) print(val)
Output:
[1.e+27 1.e+08]
3. Log-Sum Exponential Function
The
scipy.special.logsumexp() function is used to calculate the logarithmic value of the sum of the exponents of the input elements.
Example:
from scipy.special import logsumexp import numpy as np inp = np.arange(5) val = logsumexp(inp) print(val)
Here, numpy.arange() function is used to generate a sequence of numbers to be passed as input.
Output:
4.451914395937593
4. Gamma Function
Gamma function is used to calculate the gamma value, referred to as generalized factorial because, gamma(n+1) = n!
The
scipy.special.gamma() function is used to calculate the gamma value of the input element.
Example:
from scipy.special import gamma val = gamma([5, 0.8, 2, 0]) print(val)
Output:
[24. 1.16422971 1. inf]
Interpolation Functions
Interpolation is a process to find values between two or more points on a curve, line, etc.
The
scipy.interpolate package is used to perform interpolation on a particular graph.
Example:
import numpy as np from scipy import interpolate import matplotlib.pyplot as p a = np.linspace(0, 4, 12) b = np.sin(x**2/3+4) print(a,b) p.plot(a, b, 'o') # Plotting the graph assuming a and b arrays as x and y dimensions p.show()
In the above snippet of code, we have created a sine wave, and have plotted the values using Python PyPlot package of Matplotlib Module.
Output:
[0. 0.36363636 0.72727273 1.09090909 1.45454545 1.81818182 2.18181818 2.54545455 2.90909091 3.27272727 3.63636364 4. ] [-0.7568025 -0.78486887 -0.85971727 -0.9505809 -0.9999744 -0.92508408 -0.64146657 -0.12309271 0.51220599 0.96001691 0.85056799 0.09131724]
Conclusion
Thus, in this article, we have understood the functions served by the Python SciPy library.
References
Recommended read: Python Matplotlib Tutorial and Python NumPy | https://www.askpython.com/python-modules/python-scipy | CC-MAIN-2020-16 | refinedweb | 1,403 | 50.12 |
With Static Generation (SSG), Next.js pre-renders the page into HTML on the server ahead of each request, such as at build time. The HTML can be globally cached by a CDN and served instantly.
Static Generation is more performant, but because pre-rendering happens ahead of time, the data could become stale at request time.
Fortunately, there are ways to work around this issue without rebuilding the entire app when the data is updated. With Next.js, you can use Static Generation for maximum performance without sacrificing the benefits of Server-side Rendering.
In particular, you can use:
- Incremental Static Generation: Add and update statically pre-rendered pages incrementally after build time.
- Client-side Fetching: Statically generate parts of the page without data, and fetch the data on the client-side.
To demonstrate, let’s use a hypothetical e-commerce Next.js app as an example.
E-commerce Next.js App Example
An e-commerce app might have the following pages, each with different data requirements.
- About Us: This page shows the company information, which will be written directly in the app’s source code. No need to fetch data.
- All Products: This page shows the list of all products. The data will be fetched from a database. This page will look the same for all users.
- Individual Product: This page shows each individual product. Like the All Products page, the data will be fetched from a database, and each page will look the same for all users.
- Shopping Cart: This page shows a user’s shopping cart. The data will be fetched from a database. This page will look different for each user.
Per-page Basis
One of my favorite features of Next.js is per-page configuration for pre-rendering. You can choose a different data fetching strategy for each page.
For our e-commerce app example, we’ll use the following strategy for each page. We’ll explain how they work shortly.
- All Products / Individual Product: Static Generation with data, and then improve upon it using Incremental Static Generation.
- Shopping Cart: Static Generation without data, combined with Client-side Fetching.
If a page does not require fetching external data, it will automatically pre-render into HTML at build time. This is the default for Next.js pages. Let’s use this for the about page, which has no data requirements.
Create a file under the
pagesdirectory and export only the component.
// pages/about.js // This page can can be pre-rendered without // external data: It will be pre-rendered // into a HTML file at build time. export default function About() { return <div> <h1>About Us</h1> {/* ... */} </div> }
All Products Page: Static Generation with Data
Next, let’s create a page showing all products. We want to fetch from our database at build time, so we’ll use Static Generation.
Create a page component that exports a
getStaticPropsfunction. This function will be called at build time to fetch external data, and the data will be used to pre-render the page component.
// This function runs at build time on the build server export async function getStaticProps() { return { props: { products: await getProductsFromDatabase() } } } // The page component receives products prop // from getStaticProps at build time export default function Products({ products }) { return ( <> <h1>Products</h1> <ul> {products.map((product) => ( <li key={product.id}>{product.name}</li> ))} </ul> </> ) }
getStaticPropsis run on our build server (Node.js environment), so the code will not be included in the client-side JavaScript bundle. This means you can directly query your database.
Individual Product Page: Static Generation with Data
Your e-commerce app needs a page for each product with a route based on its id (for example,
/products/[id]).
In Next.js, this can be done at build time using dynamic routes and
getStaticPaths. By creating a file called
products/[id].jsand having
getStaticPathsreturn all possible ids, you can pre-render all individual product pages at build time.
Then, you can fetch data for the individual product from the database. We can use
getStaticPropsagain by providing the
idat build time.
// pages/products/[id].js // In getStaticPaths(), you need to return the list of // ids of product pages (/products/[id]) that you’d // like to pre-render at build time. To do so, // you can fetch all products from a database. export async function getStaticPaths() { const products = await getProductsFromDatabase()Database(params.id) } } } export default function Product({ product }) { // Render product }
Incremental Static Generation
Now, suppose your e-commerce app has grown significantly. Instead of 100 products, you now have 100,000. Products get updated frequently. This poses two problems:
- Pre-rendering 100,000 pages at build time can be very slow.
- When product data is updated, you’d only want to modify the affected pages. We can't have a full app rebuild every time a product is modified.
Both of these problems can be solved by Incremental Static Generation. Incremental Static Generation allows you to pre-render a subset of pages incrementally after build time. It can be used to add pages or update existing pre-rendered pages.
This allows you to use Static Generation for maximum performance without sacrificing the benefits of Server-side Rendering.
Adding Pages (Fallback)
If you have 100,000 products and pre-rendering all pages at build time is too slow, you can lazily pre-render the pages.
For example, suppose that one of those 100,000 products is called product X. Using Next.js, we can pre-render this page when a user requests the page for product X. Here’s how it works:
- A user requests the page for product X.
- But instantly, just like regular static generation.
To enable this behavior, you can specify
fallback: truein
getStaticPaths. Then, in the page itself, you can use
router.isFallbackto see if the loading indicator should be displayed.
// pages/products/[id].js... }
Updating Existing Pages (Incremental Static "Re"generation)
When product data is updated, you don’t want to rebuild the entire app. You only want the affected pages to change., the user will see the existing (out of date) page. In the background, Next.js pre-renders this page again.
- Once the pre-rendering has finished, Next.js will serve the updated page for product Y.
This approach is called Incremental Static Regeneration. To enable this, you can specify
revalidate: 60in
getStaticProps.
// pages/products/[id].js export async function getStaticProps({ params }) { return { props: { product: await getProductFromDatabase(params.id) }, revalidate: 60 } }
Inspired by stale-while-revalidate, this ensures traffic is served statically, and new pages are pushed only after generating successfully. A small number of users may get stale content, but most will get the latest content, and every request will be fast because Next.js always serves static content.
Both adding and updating pages are fully supported by both
next startand the Vercel Edge Network out of the box.
Shopping Cart Page: Static Generation without Data, Combined with Client-side Fetching
Some pages, like the shopping cart page, can only be partially pre-rendered ahead of a request. Because the items on a shopping cart are unique to each user, you must always render them at request time.
You might think this is when you opt for Server-side Rendering, but that’s not necessarily the case. Instead, for better performance, you can do Client-side Fetching on top of Static Generation without data:
- Pre-render the page without data and show a loading state. (Static Generation)
- Then, fetch and display the data client-side. (Client-side Fetching)> }
Benefits of Static
Using one of the Static Generation strategies we’ve discussed, you can gain the following benefits:
- Static is consistently and predictably fast. Pre-rendered HTML files can be cached and served by a global CDN.
- Static is always online. Even if your backend or data source (e.g. database) goes down, your existing pre-rendered page will still be available.
- Static minimizes backend load. With Static Generation, the database or API wouldn’t need to be hit on every request. Page-rendering code wouldn’t have to run on every request.
Server-side Rendering
If you want to use Server-side Rendering (pre-render a page on the server on every request) with Next.js, you can. To use this feature, you can export a function called
getServerSidePropsfrom a page, just like
getStaticProps. Server-side Rendering is also supported when deployed to Vercel.
However, by using Server-side Rendering, you’ll give up on the benefits of Static as mentioned above. We suggest trying Incremental Static Generation or Client-side Fetching and see if they fit your needs.
Also: Writing Data
Fetching data is only half the equation. Your app might need to write data back to your data source. For our e-commerce app, adding an item to the shopping cart is a good example of this.
Next.js has a feature called API Routes for this purpose. To use this feature, you can create a file inside the
pages/apidirectory, which creates an API endpoint we can use to mutate our data source. For example, we can create
pages/api/cart.js, which accepts a
productIdquery parameter and adds that item to our cart. external data sources securely. Using environment variables, we can include secrets for authentication without exposing the values client-side.
API routes can be deployed as Serverless Functions (which is the default when you deploy to Vercel).
Conclusion
With Next.js, you can use Static Generation for maximum performance without sacrificing the benefits of Server-side Rendering. For more information, please refer to the Next.js documentation. | https://vercel.com/blog/nextjs-server-side-rendering-vs-static-generation | CC-MAIN-2021-25 | refinedweb | 1,594 | 58.69 |
25th August 2014 5:15 pm
Django Blog Tutorial - the Next Generation - Part 7
Hello once again! In this instalment we’ll cover:
- Caching your content with Memcached to improve your site’s performance
- Refactoring and simplifying our tests
- Implementing additional feeds
- Creating a simple search engine
Don’t forget to activate your virtualenv:
$ source venv/bin/activate
Now let’s get started!
Memcached
If you frequent (or used to frequent) social media sites like Reddit, Slashdot or Digg, you may be familiar with something called variously the Digg or Slashdot effect, whereby if a page gets submitted to a social media site, and subsequently becomes popular, it can be hit by a huge number of HTTP requests in a very short period of time, slowing it down or even taking the server down completely.
Now, as a general rule of thumb, for most dynamic websites such as blogs, the bottleneck is not the web server or the programming language, but the database. If you have a lot of people hitting the same page over and over again in quick succession, then you’re essentially running the same query over and over again and getting the same result each time, which is expensive in terms of processing power. What you need to be able to do is cache the results of the query in memory for a given period of time so that the number of queries is reduced.
That’s where Memcached comes in. It’s a simple key-value store that allows you to store values in memory for a given period of time so that they can be retrieved without having to query the database. Memcached is a very common choice for caching, and is by far the fastest and most efficient type of cache available for Django. It’s also available on Heroku’s free tier.
Django has a very powerful caching framework that supports numerous types of cache in addition to Memcached, such as:
- Database caching
- Filesystem caching
- Local memory caching
There are also third-party backends for using other caching systems such as Redis.
Now, the cache can be used in a number of different ways. You can cache only certain parts of your site if you wish. However, because our site is heavily content-driven, we should be pretty safe to use the per-site cache, which is the simplest way to set up caching.
In order to set up Memcached, there’s a couple of Python libraries we’ll need. If you want to install them locally, however, you’ll need to install both memcached and libmemcached (on Ubuntu, the packages you need are called
memcached and
libmemcached-dev) on your development machine. If you don’t want to do this, then just copy and paste these lines into
requirements.txt instead:
If you are happy to install these dependencies locally, then run this command once memcached and libmemcached are installed:
$ pip install pylibmc django-pylibmc-sasl
With that done let’s configure Memcached. Open up the settings file and add the following at the bottom:
Then add the following to
MIDDLEWARE_CLASSES:
That’s it! The first section configures the application to use Memcached to cache the content when running on Heroku, and sets some configuration parameters, while the second section tells Django to use the per-site cache in order to cache all the site content.
Now, Heroku doesn’t include Memcached by default - instead it’s available as an add-on called Memcachier. To use add-ons you need to set up a credit card for billing. We will set it up to use the free developer plan, but if you outgrow this you can easily switch to a paid plan. To add Memcachier, run this command:
$ heroku addons:add memcachier:dev
Please note that Memcachier can take a few minutes to get set up, so you may want to leave it a little while between adding it and pushing up your changes. Now we’ll commit our changes:
Then we’ll push them up to our remote repository and to Heroku:
And that’s all you need to do to set up Memcached. In addition to storing your query results in Memcached, enabling the caching framework in Django will also set various HTTP headers to enable web proxies and browsers to cache content for an appropriate length of time. If you open up your browser’s developer tools and compare the response headers for your homepage on the latest version of the code with the previous version, you’ll notice that a number of additional headers appear, including
Cache-Control,
Expires and
Last-Modified. These tell web browsers and web proxies how often to request the latest version of the HTML document, in order to help you reduce the bandwidth used.
As you can see, for a site like this where you are the only person adding content, it’s really easy to implement caching with Django, and for a blog there’s very little reason not to do it. If you’re not using Heroku and are instead hosting your site on a VPS, then the configuration will be somewhat different - see here for details. You can also find information on using other cache backends on the same page.
That isn’t all you can do to speed up your site. Heroku doesn’t seem to be very good for serving static files, and if your site is attracting a lot of traffic you might want to host your static files elsewhere, such as on Amazon’s S3 service. Doing so is outside the scope of this tutorial, but for that use case, you should check out django-storages.
Clearing the cache automatically
There is one issue with this implementation. As it is right now, if you view the home page, add a post, then reload the page, you may not see the new post immediately because the cache will continue serving the old version until it has expired. That behaviour is less than ideal - we would like the cache to be cleared automatically when a new post gets added so that users will see the new version immediately. That response will still be cached afterwards, so it only means one extra query.
This is the ideal place to introduce signals. Signals are a way to carry out a given action when an event takes place. In our case, we plan to clear the cache when a post is saved (either created or updated).
Note that as we’ll be testing the behaviour of the cache at this point, you’ll need to install Memcached on your local machine, and we’ll need to change the settings to fall back to our local Memcached instance:
If you don’t want to install Memcached locally, you can skip this step, but be aware that the test we write for clearing the cache will always pass if you do skip it.
Then we’ll run our tests to make sure nothing has been broken:
Let’s commit:
Now we’ll add a test for clearing the cache to
PostViewTest:
This should be fairly self-explanatory. We create one post, and request the index page. We then add a second post, request the index page again, and check for the second post. The test should fail because the cached version is returned, rather than the version in the database.
Now we have a test in place, we can implement a fix. First, add this to the top of your
models.py:
Then add the following at the bottom of the file:
This is fairly straightforward. What we’re doing is first defining a function called
new_post that is called when a new post is created. We then connect it to the
post_save signal. When a post is saved, it calls
new_post, which clears the cache, making sure users are seeing the latest and greatest version of your site immediately.
Let’s test it:
There are a number of signals available, and when you create one, you have access to the created object via the
instance parameter. Using signals you can implement all kinds of functionality. For instance, you could implement the functionality to send an email when a new post is published.
If you’re using Travis CI, you’ll also need to update the config file:
Time to commit:
Formatting for RSS feeds
Now, we want to offer more than one option for RSS feeds. For instance, if your blog is aggregated on a site such as Planet Python, but you also blog about JavaScript, you may want to be able to provide a feed for posts in the
python category only.
If you have written any posts that use any of Markdown’s custom formatting, you may notice that if you load your RSS feed in a reader, it isn’t formatted as Markdown. Let’s fix that. First we’ll amend our test:
Don’t forget to run the tests to make sure they fail. Now, let’s fix it:
All we’re doing here is amending the
item_description method of
PostsFeed to render it as Markdown. Now let’s run our tests again:
With that done, we’ll commit our changes:
Refactoring our tests
Now, before we get into implementing the feed, our tests are a bit verbose. We create a lot of items over and over again - let’s sort that out. Factory Boy is a handy Python module that allows you to create easy-to-use factories for creating objects over and over again in tests. Let’s install it:
Now let’s set up a factory for creating posts. Add this at the top of the test file:
import factory.django
Then, before your actual tests, insert the following:
Now, wherever you call
Site(), add its attributes, and save it, replace those lines with the following:
site = SiteFactory()
Much simpler and more concise, I’m sure you’ll agree! Now, let’s run the tests to make sure they aren’t broken:
Let’s commit again:
Let’s do the same thing with
Category objects:
Again, just find every time we call
Category() and replace it with the following:
category = CategoryFactory()
Now if we run our tests, we’ll notice a serious error:
Thankfully, this is easy to fix. We just need to amend the custom
save() method of the
Category model:
That should resolve the issue:
Let’s commit again:
Now let’s do the same thing for tags:
And replace the sections where we create new
Tag objects:
tag = TagFactory()
Note that some tags have different values. We can easily pass different values to our
TagFactory() to override the default values:
tag = TagFactory(name='perl', description='The Perl programming language')
The
Tag model has the same issue as the
Category one did, so let’s fix that:
We run our tests again:
Time to commit again:
Next we’ll create a factory for adding users. Note that the factory name doesn’t have to match the object name, so you can create factories for different types of users. Here we create a factory for authors - you could, for instance, create a separate factory for subscribers if you wanted:
And as before, replace those sections where we create users with the following:
author = AuthorFactory()
Run the tests again:
We commit our changes:
Now we’ll create a flat page factory:
And use it for our flat page test:
page = FlatPageFactory()
Check the tests pass:
And commit again:
Now we’ll create a final factory for posts:
This factory is a little bit different. Because our
Post model depends on several others, we need to be able to create those additional objects on demand. By designating them as subfactories, we can easily create the associated objects for our
Post object.
That means that not only can we get rid of our
Post() calls, but we can also get rid of the factory calls to create the associated objects for
Post models. Again, I’ll leave actually doing this as an exercise for the reader, but you can always refer to the GitHub repository if you’re not too sure.
Make sure your tests still pass, then commit the changes:
Using Factory Boy made a big difference to the size of the test file - I was able to cut it down by over 200 lines of code. As your application gets bigger, it gets harder to maintain, so do what you can to keep the size down.
Additional RSS feeds
Now, let’s implement our additional RSS feeds. First, we’ll write a test for the category feed. Add this to the
FeedTest class:
Here we create two posts in different categories (note that we create a new category and override the post category for it). We then fetch
/feeds/posts/category/python/ and assert that it contains only one post, with the content of the first post and not the content of the second.
Run the tests and they should fail:
Because we haven’t yet implemented that route, we get a 404 error. So let’s create a route for this:
Note that the category RSS feed route is similar to the post RSS feed route, but accepts a
slug parameter. We will use this to pass through the slug for the category in question. Also note we import the
CategoryPostsFeed view. Now, we need to create that view. Fortunately, because it’s written as a Python class, we can extend the existing
PostsFeed class. Open up your views file and amend it to look like this:
Note that many of our fields don’t have to be explicitly defined as they are inherited from
PostsFeed. We can’t hard-code the title, link or description because they depend on the category, so we instead define methods to return the appropriate text.
Also note
get_object() - we define this so that we can ensure the category exists. If it doesn’t exist, then it returns a 404 error rather than showing an empty feed.
We also override
items() to filter it to just those posts that are in the given category.
If you run the tests again, they should now pass:
Let’s commit our changes:
Now, we can get our category RSS feed, but how do we navigate to it? Let’s add a link to each category page that directs a user to its RSS feed. To do so, we’ll need to create a new template for category pages. First, let’s add some code to our tests to ensure that the right template is used at all times. Add the following to the end of the
test_index method of
PostViewTest:
Then, add this to the end of
test_post_page:
Finally, add this to the end of
test_category_page:
These assertions confirm which template was used to generate which request.
Next, we head into our views file:
Note that we first of all change the template used by this view. Then, we override
get_context_data to add in additional data. What we’re doing is getting the slug that was passed through, looking up any category for which it is the slug, and returning it as additional context data. Using this method, you can easily add additional data that you may wish to render in your Django templates.
Finally, we create our new template:
Note that the category has been passed through to the template and is now accessible. If you run the tests, they should now pass:
With that done. we can commit our changes:
Next up, let’s implement another RSS feed for tags. First, we’ll implement our test:
This is virtually identical to the test for the categroy feed, but we adjust it to work with the
Tag attribute and change the URL. Let’s check that our test fails:
As before, we create a route for this:
Next, we create our view:
Again, this inherits from
PostsFeed, but the syntax for getting posts matching a tag is slightly different because they use a many-to-many relationship.
We also need a template for the tag pages. Add this to the end of the
test_tag_page method:
Let’s create that template:
This is virtually identical to the category template. You’ll also need to apply this template in the view for the tag list, and pass the tag name through as context data:
Let’s run our tests:
You may want to do a quick check to ensure your tag feed link works as expected. Time to commit:
Moving our templates
Before we crack on with implementing search, there’s one more piece of housekeeping. In Django, templates can be applied at project level or at app level. So far, we’ve been storing them in the project, but we would like our app to be as self-contained as possible so it can just be dropped into future projects where we need a blog. That way, it can be easily overridden for specific projects. You can move the folders and update the Git repository at the same time with this command:
$ git mv templates/ blogengine/
We run the tests to make sure nothing untoward has happened:
And we commit:
$ git commit -m 'Moved templates'
Note that
git mv updates Git and moves the files, so you don’t need to call
git add.
Implementing search
For our final task today, we will be implementing a very simple search engine. Our requirements are:
- It should be in the header, to allow for easy access from anywhere in the front end.
- It should search the title and text of posts.
First, we’ll write our tests:
Don’t forget to run the tests to make sure they fail:
With that done, we can add the search form to the header:
Now we’ll actually implement our search. Implementing search using Django’s generic views can be fiddly, so we’ll write our search view as a function instead. First, amend the imports at the top of your view file to look like this:
Next, add the following code to the end of the file:
As this is the first time we’ve written a view without using generic views, a little explanation is called for. First we get the values of the
q and
page parameters passed to the view.
q contains the query text and
page contains the page number. Note also that our page defaults to 1 if not set.
We then use the Q object to perform a query. The Django ORM will
AND together keyword argument queries, but that’s not the behaviour we want here. Instead we want to be able to search for content in the title or text, so we need to use a query with an
OR statement, which necessitates using the Q object.
Next, we use the
Paginator object to manually paginate the results, and if it raises an
EmptyPage exception, to just show the last page instead. Finally we render the template
blogengine/search_post_list.html, and pass through the parameters
page_obj for the returned page,
object_list for the objects, and
We also need to add a route for our new view:
Finally, let’s create a new template to show our results:
Let’s run our tests:
Don’t forget to do a quick sense check to make sure it’s all working as expected. Then it’s time to commit:
And push up your changes:
And that’s the end of this instalment. Please note this particular search solution is quite basic, and if you want something more powerful, you may want to look at Haystack.
As usual, you can get this lesson with
git checkout lesson-7 - if you have any problems, the repository should be the first place you look for answers as this is the working code base for the application, and with judicious use of a tool like
diff, it’s generally pretty easy to track down most issues.
In our next, and final instalment, we’ll cover:
- Tidying everything up
- Implementing an XML sitemap for search engines
- Optimising our site
- Using Fabric to make deployment easier
Hope to see you then! | https://matthewdaly.co.uk/blog/2014/08/25/django-blog-tutorial-the-next-generation-part-7/ | CC-MAIN-2019-13 | refinedweb | 3,376 | 63.93 |
Working with Entity bean using JPA
Working with Entity bean using JPA
Working
with Entity bean using JPA... or retrieved from that entity. For example, in a banking application, Customer
dao
();
}
return conn;
}
}
//bean:
package
Identify the interfaces and methods a CMP entity bean must and must not implement.
Identify the interfaces and methods a CMP entity bean must and must... the interfaces and methods a CMP entity bean must and must not implement.
The following are the requirements for an entity bean
From a list, identify the purpose, behavior, and responsibilities of the bean
provider for a CMP entity bean, including but not limited to:
setEntityContext, unsetEntityContext,
ejbC
descriptor. The entity Bean Provider declaratively specifies the EJB QL... of the bean
provider for a CMP entity bean, including but not limited...,
ejbFind, ejbHome, and ejbSelect.
Prev Chapter 7. CMP Entity Example - EJB
EJB Example Hi,
My Question is about enterprise java beans, is EJB stateful session bean work as web service? if yes can you please explain with small example.
Thanks
sravanth Hi Friend,
Please visit
Design and develop entity EJBs
use the Create an Enterprise Bean wizard to create a CMP entity bean.
To create an enterprise bean, you must first have an EJB..., Parent is a CMP entity
bean that contains an attribute id of type int
DAO Example
DAO Example Dear Friends
Could any one please give me any example of DAO application in struts?
Thanks & Regards
Rajesh Here is my question.
Can one entity bean class be associated with more than one table . And if yes how we can achieve this.
thanks
Chapter 7. CMP Entity Bean Life Cycle
Chapter 7. CMP Entity Bean Life CyclePrev Part ...;CMP Entity Bean Life CycleIdentify
correct and incorrect statements or examples about the life cycle of
a CMP entity bean
From a list, identify the responsibility of the container for a CMP entity bean,
including but not limited to: setEntityContext,
unsetEntityContext, ejbCreate,
ejbPostCreate, ejbActi
entity bean,
including but not limited to: setEntityContext....
Prev Chapter 7. CMP Entity Bean Life Cycle Next ... of the container for a CMP entity bean,
including but not limited
ejb vs hibernate - EJB
ejb vs hibernate 1>>> If we have ejb entity bean why we need hibernate?
2>>> Is hibernate distributed
Simple EJB3.0 - EJB
://
Thanks...;>> my question is how to make session bean and how to access this session
Session Bean
uses an entity bean to access or modify data. They implement business
logic...-lived components. The EJB container may destroy a session bean if
its client times... i.e. the EJB
container destroys a stateless session bean.
Session Bean Example
Session Bean Example I want to know that how to run ejb module by jboss 4.2.1 GA (session bean example by jboss configuration )?
Please visit the following link:
EJB container services
. We can deploy more than one entity beans in a container. When
the entity bean... interface for the entity bean. This home interface allows a client
in removing... business methods that are not specific to a particular entity bean object.
JNDI(Java message driven bean
Ejb message driven bean
... driven bean using EJB. Mesaage driven bean in EJB
have the following features... the EJB module and web module. The
steps involved in creating message driven bean
Chapter 8. Entity Beans
method responsible for that behavior.
A CONTAINER provides the entity bean instances with an EntityContext,
which gives the entity bean instance access... of the
bean instance’s EJB object
A Message-Driven Bean Example
A Message-Driven Bean Example
... of a simple message-driven bean application.
In this example, we are going to implement... implementation:
In EJB 3.0, the MDB bean class is annotated
EJB Hello world example
EJB Hello world example
... in EJB and testing it.
You can also create a hello world example to test your...
in the bean.@EJB is the
annotation
used for
configuring the EJB
EJB, Enterprise java bean- Why EJB (Enterprise Java Beans)?
Why EJB (Enterprise Java Beans)?
Enterprise Java Beans or EJB..., Enterprise
Edition (J2EE) platform. EJB technology enables rapid and simplified
Chapter 5. Client View of an Entity
of an
entity bean's local and remote home interface, including viewing the code used to
locate an entity bean's home interface and the home interface methods provided
to the client.
The client of an entity bean
Identify the use, syntax, and behavior of, the following entity bean home
method types, for Container-Managed Persistence (CMP);
finder methods, create methods, remove methods, and home me
the use, syntax, and behavior of, the following entity bean home
method... methods, remove methods, and home methods.
REMOTE view CMP Entity EJB... that is NOT
SPECIFIC to an entity bean instance.
They MUST NOT start with &ldquo
EntityBean - EJB
Persistence API starting from EJB 3.0.
Read for more information. In ejb3.0 does not have entity beans why how it persist ... helpful in providing business-specific functionality of an
EJB. Here
Accessing Database using EJB
through the EJB example given below to find out the steps involved in accessing... the methods which are defined in the bean.
@EJB:-This is the annotation... Accessing Database using EJB
Chapter 9. EJB-QL
. The Bean Provider uses
EJB QL to write queries based on the abstract...-fields of the related entity beans. The Bean Provider
can navigate from an entity bean to other entity beans by using the names
of cmr-fields
Chapter 13. Enterprise Bean Environment
ejb-ref-name, ejb-ref-type
(value must be either Entity... interfaces
of the referenced enterprise bean; and optional ejb-link information,
used to specify the referenced enterprise bean.
Used in: entity, message-driven...
Bean
Writing Entity Bean...
Writing Entity Bean with
Bean Managed Persistence
CRUD DAO
CRUD DAO how to create dao for create,read,update and delete?
... register(StudentBean bean) {
/**
* method to search student...) {
}
currentCon = null;
}
}
return bean;
}
}
try
doubt in ejb3 - EJB
;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity... EntityBean.UserEntityBean;
/**
* Session Bean implementation class UserBean
*/
@Stateless...(name="example")
EntityManager em;
public static final
java - EJB
an application by an example that contains a session bean and a CMP but not able.... Hi mona,
A session bean is the enterprise bean that directly... application. A session bean represents a single client accessing the enterprise
EJB 3.0 Tutorials
a message driven bean using EJB.
EJB lookup example... from SQL Table Using EJB
In the given example of Enterprise Java Bean, we... Bean
Example
Statelful Session Bean Example
Chapter 5. EJB transactions
it simultaneously.
An Entity EJB is a representation... with the persistent store (database). If a transactional
operation in such an Entity EJB....
The EJB 2.0 specification prohibits an Entity EJB from managing its own
Understanding Spring Struts Hibernate DAO Layer
Understanding Spring Struts Hibernate DAO Layer... Hibernate DAO Layer
The Data Access Object for this application is written...
file. An example of Login.hbm.xml is given below with their class.
3 - stateless - EJB
EJB stateless session bean Hi, I am looking for an example of EJB 3.0 stateless session bean
java bean code - EJB
java bean code simple code for java beans Hi Friend... the Presentation logic. Internally, a bean is just an instance of a class.
Java Bean Code:
public class EmployeeBean{
public int id;
public
How to connect to dao n bean classes with jsp
How to connect to dao n bean classes with jsp I have made this edao pkg
package edao;
import java.sql.Connection;
import...());
System.out.println("Bean set");
stmt.executeUpdate
Accessing Database using EJB
using EJB
This is a simple EJB Application that access the
database. Just go through the EJB example...
through which we can access the methods which are defined in the bean.
@EJB
Bean
visit the following links:
Stateless Session Bean Example Error
Stateless Session Bean Example Error Dear sir,
I'm getting following error while running StatelessSessionBean example on Jboss. Please help me...)
Please visit the following link:
Stateless Session Bean Example Interfaces
EJB Interfaces
Interface in java means a group of related methods with empty bodies.
EJB have generally 4... are the interface that has the methods that relate to a particular bean instance
fusion charts
fusion charts hi i have to use the fusion chart. i don't know how to use and code in jsp and i have to create the chart by using the data from db. please help me doing that with exapmles. thank you
EJB life cycle method
EJB life cycle method
The various stages through which an enterprise bean go
through its lifetime is known as the life cycle of EJB. Each type of enterprise
bean has different life cycle
hibernate criteria Distinct_Root_Entity
hibernate criteria Distinct_Root_Entity
In this Tutorial, We will discuss about hibernate criteria query, In this example we create a criteria instance... method. In This example
search the result according to Criteria
Java bean example in JSP
Java bean example in JSP
... that help in understanding
Java bean example in JSP.This code illustrates... of Java bean.
Understand with Example
In this example we want to describe you
EJB, Enterprise java bean, EJB Intoduction- Enterprise Java Beans (EJB) - An Introduction
that can be expressed as nouns. For example, an entity bean might....
Entity Beans: Container and Bean Managed
Persistence
An example... beans, entity beans, and message-driven beans. A bean developer
has EJB 2.0 and EJB 3.0?
GIVE ME....
---------------------------------------------------
Visit for more information with example.
Thanks.
Amardeep Hi friend,
Difference between EJB
EJB - EJB
EJB What is the difference between Stateless session bean and Statefull session bean? what are the lifecycle methods of both SLSB and SFSB ... session bean and Statefull session bean.
*) Stateful beans are also
implementing DAO - Struts
, exam in 3 days, and just now i found out our lecturer post a demo on DAO... divided into DAO factory Impl,employeeDAOImpl,DAOFactory,EmployeeDAO.
"I strongly... writing DAO Implementation classes." This is her advice. But as a beginner who just
Chapter 2. Client View of a Session Bean
,
RemoveException; // only Entity EJB !!!
}
The LOCAL... primaryKey) throws RemoveException,
EJBException; // only Entity EJB... or examples about the client view of a session
bean's local and remote home
EJB - Java Interview Questions
and Entity Beans.Thank you inadvance. Hi friend,
# Stateless Session Beans:
A stateless session bean does not maintain a conversational state with the client.
When a client invokes the methods of a stateless bean, the instance
Deleting a Row from SQL Table Using EJB
Deleting a Row from SQL Table Using EJB
In the given example of Enterprise Java Bean, we... access the methods which are defined in the bean.
@EJB
Error in simple session bean ..................
more
EJB Hello World Example
Please visit the following links...Error in simple session bean .................. Hi friends,
i am trying a simple HelloWOrld EJb on Websphere Applicatiopn server 6.1.
Can any
ejb - EJB
ejb hi
i am making a program in java script with sateful session bean. This program is Loan calculator.In this program three field 1-type... but use stateless session bean. when user submit your require.
Please early
ejb - EJB
ejb plz send me the process of running a cmp with a web application send me an example
EJB Insert data
through which we can access the methods which are defined in the bean.
@EJB...
.style1 {
color: #FFFFFF;
}
EJB Insert data... describes you the way to
insert data into the database using EJB. The steps
EJB communication - EJB
EJB communication i am trying to create call a bean from another bean but it will not call. i cann't understand the dd configuration.please help me
java struts DAO - Struts
java struts DAO hai friends i have some doubt regarding the how to connect strutsDAO and action dispatch class please provide some example to explain this connectivity.
THANKS IN ADVANCE
EJB deployment descriptor
EJB deployment descriptor
Deployment descriptor is the file which tells the EJB server
that which classes make up the bean implementation, the home interface and the remote
EJB deployment descriptor
application. In the example given below our application consists of
single EJB...
EJB deployment descriptor
Deployment descriptor is the file which tells the EJB server
that which classes make
calling a session bean bean from servlet using netbeans - EJB
calling a session bean from servlet using netbeans How to call a session bean from servlet using netbeans in Java
EJB
Transactional Attributes
or
entity bean's home or component interface....
For an ENTITY bean, the transaction attributes MUST be specified....
For ENTITY beans that use EJB 2.0 container-managed
Features of EJB 3.0
the container discards the bean
instances and creates new instances.
EJB Context: Bean... that the client can directly invoke methods on EJB rather
than creating the bean...
Features of EJB 3.0
Now
What is EJB 3.0?
on developing logic to solve business problems.
Types of EJB
Session Bean
Session...;
Entity Bean
Enity beans are persistence java objects, whose state can.... Entity bean
represents a row of the database table.
what is an entity in hibernate?
field static or final.
Example:
Here is an entity class named...what is an entity in hibernate? what is an entity in hibernate?
Entity: In general entity is an object that has some distinct value
DAO Layer explained
DAO Layer explained
In this section we will explain you the DAO Layer of our application.
DAO Layer Explained
DAO stand for Data
Ask Questions?
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://www.roseindia.net/tutorialhelp/comment/86044 | CC-MAIN-2013-20 | refinedweb | 2,276 | 59.3 |
According to these docs () the Spark REST API can be queried for metrics at. However, running this within a DataBricks notebook fails.
(note the image shows 4043, but I also tried 4040 and many other ports)
Does DataBricks Spark not support accessing cluster stats through this API?
Related: if there is a much better way to access metrics than via this API I am interested. I originally was trying to get access to the DropWizard metrics registry directly, but it is private:
I was also considering using the JMX sink and accessing metrics via JMX, but that seems a little complicated too:
And I did try access in scala too using this code as a starting point:
That failed with the same error: java.net.ConnectException: Connection refused (Connection refused)
Hey, were you able to access the spark API's in Databricks env. did you find a solution?
@turtlemonvh
I am trying to do the same: Get the SparkUI metrics using API within the databricks env.
Just wondering, if you found the solution.
Answer by dillon · Jul 09, 2018 at 11:22 AM
Databricks collects live and historical cluster metrics for you using Ganglia, so you don't have to access the Spark API directly or set up your own monitoring system while using Databricks.
To access Databricks metrics, navigate to cluster details page by clicking "Clusters" on the left hand side bar, then select the "Metrics" tab from this cluster details page.
To view live metrics, click the Ganglia UI link. To view historical metrics, click a snapshot file. The snapshot contains aggregated metrics for the hour preceding the selected time. You may also access GPU metrics here for GPU-enabled clusters (Databricks Runtime 4.1 and above).
In addition, you may also see information on jobs, stages, executors, etc. To do so, from the cluster details page, select "Spark UI" then use the tab bar beneath the primary tab bar to navigate.
Wow - that seems pretty crazy. I get that it is convenient to have data loaded into Ganglia and I do use that UI sometimes to diagnose job performance issues, but I would really like access to the raw metrics for more fine-grained analysis of job performance.
This is the second place where built in functionality in Spark has been disabled in DataBricks and the answer has been "use the UI", which is not awesome for me because most of our use of DataBricks is automated.
Thanks for the response, though. It's good to know I'm not doing anything too stupid trying to access the API.
Answer by dillon · Jul 09, 2018 at 02:52 PM
In that case, you can access spark master REST API by navigating to Clusters then selecting the "Spark Cluster UI - Master" tab. From here you can see the IP and port as "REST URL"
You can programmatically access the spark master address as the spark environment variable,
spark.master
I gave this a try, grabbing the master url from
spark.conf.get("spark.master"). The value I got was
spark://10.112.251.151:7077.
I tried to
curl in another cell, and the request was still open (no response) after 6 minutes.
I also tried port 4040 per the documentation here:
That didn't work either, yielding the same "Failed to connect" response I documented above.
<continued in next comment bc character limit...>
I went to the "Spark UI - master" page per your suggestion and noted that the value for "REST URL" uses a different port than "URL". (See image)
The value for "URL" is the same as the value I got from
spark.conf.get("spark.master"), but I was not able to find a setting that corresponded to "REST URL".
Still, I tried curl-ing the "REST URL" in a notebook, and it seems like that REST API is not the same as the API documented here. Here is an example response I got back trying to query.
I tried
curl as well and got a similar error.
<continued>
So this doesn't seem to be the same REST api that I was looking for.
Once again, if I am doing something silly here, please let me know!
This "REST API" corresponds with the one described here:. This API is more of a "submission gateway" (hence you should be able to use paths like /api/submissions/status).
On the other hand, sounds like you are actually trying to access the monitoring API (this is the one that is normally port 4040 by default). In Databricks, this is the same server thats hosting the web app, for example the URI would be demo.cloud.databricks.com/api/2.0/jobs. Note in this case that you must still authenticate using your Databricks credentials and Basic Auth.
Answer by Spencer McGhin · Apr 10 at 06:28 PM
Hi there @turtlemonv,
You can access the spark rest API via the url below. Note that the value for port is dynamic and will have to be obtained using the command in the code box.
https://<databricks-host>/driver-proxy-api/o/0/<cluster_id>/<port>/api/v1/applications/<application-id-from-master-spark-ui>/stages/<stage-id> port = spark.sql("set spark.ui.port").collect()[0].value
@spencer-mcghin
I want to parse the Spark UI metrics within the databricks notebook env and tried using the above API tooling. However, I get permission denied error: Traffic on this port is not permitted.
can you please advice on how to resolve it, or if there is some other way to parse the SparkUI metrics, which could be used later for monitoring/performance tunning.
Answer by Eugenio Marinetto · 2 days ago
Maybe this code could help next one pass by:
def get_storage_info(workspace_url, token):
import requests databricks_host = workspace_url cluster_id = spark.conf.get("spark.databricks.clusterUsageTags.clusterId") port = spark.sql("set spark.ui.port").collect()[0].value application_id_from_master_spark_ui = sc._jsc.sc().applicationId() url = 'http://{0}/driver-proxy-api/o/0/{1}/{2}/api/v1'.format(databricks_host, cluster_id, port, ) headers = {"Authorization": "Bearer {0}".format(token)} # Get App ID response = requests.get(url + '/applications', headers=headers) applications = response.json() if response.status_code == 200 else None for app in applications: if app['name'] == 'Databricks Shell': app_id = app['id'] # Get RDDs in storage/rdd url_app = url + '/applications/{0}'.format(app_id) response = requests.get(url_app + '/storage/rdd', headers=headers) response = response.json() if response.status_code == 200 else None if len(response) > 0: print('Current cached RDDs:') print() for rdd in response: print(' [{0}]'.format(rdd['name'])) print(' [{0}] ID'.format(rdd['id'])) print(' [{0}/{1}] Cached Partitions'.format(rdd['numCachedPartitions'], rdd['numPartitions'])) #print(' [{0}] Storage Level'.format(rdd['storageLevel'])) print(' [{0}] Memory Used'.format(rdd['memoryUsed'])) print(' [{0}] Disck Used'.format(rdd['diskUsed'])) print(' Partition distribution:') for p in rdd['dataDistribution']: percentage_memory = p['memoryUsed']/p['memoryRemaining'] print(' -[{0}][{1:.2f}%]'.format(p['address'].split(':')[0], percentage_memory))
workspace_url = '<YOUR-DOMAIN>.cloud.databricks.com' token = '<YOUR USER TOKEN>' get_storage_info(workspace_url, token)
Where does spark store metrics in databricks? 0 Answers
Enable detailed monitoring metrics for EC2 instances 0 Answers
Send 'spark.sql.streaming.metricsEnabled' metrics to datadog 1 Answer
How to increase spark.kryoserializer.buffer.max 3 Answers
Line plot by group shows missing value as zero 0 Answers
Databricks Inc.
160 Spear Street, 13th Floor
San Francisco, CA 94105
info@databricks.com
1-866-330-0121 | https://forums.databricks.com/questions/14499/accessing-spark-rest-api-from-databricks.html | CC-MAIN-2020-45 | refinedweb | 1,227 | 56.86 |
Chatlog 2009-01-14
From OWL
See original RRSAgent log and preview nicely formatted version.
Please justify/explain all edits to this page, in your "edit summary" text.
00:00:00 <scribenick> PRESENT: bmotik, Ivan, IanH, Zhe, Michael Schneider, Achille, baojie, Evan_Wallace, Bernardo Cuenca Grau, uli, Alan Ruttenberg, msmith, MarkusK, Joanne, Christine 00:00:00 <scribenick> REGRETS: Elisa Kendall 00:00:00 <scribenick> CHAIR: IanH 17:55:03 <RRSAgent> RRSAgent has joined #owl 17:55:03 <RRSAgent> logging to 17:55:12 <ewallace> ewallace has joined #owl 17:55:28 <IanH> IanH has changed the topic to: 17:55:41 <IanH> Zakim, this will be owlwg 17:55:41 <Zakim> ok, IanH; I see SW_OWL()1:00PM scheduled to start in 5 minutes 17:56:09 <IanH> ScribeNick: Achille Fokoue 17:56:25 <IanH> RRSAgent, make records public 17:58:05 <schneid> schneid has joined #owl 17:58:30 <bmotik> bmotik has joined #owl 17:59:04 <Zakim> SW_OWL()1:00PM has now started 17:59:11 <Zakim> + +0186528aaaa 17:59:12 <ivan> zakim, dial ivan-voip 17:59:12 <Zakim> ok, ivan; the call is being made 17:59:13 <Zakim> +Ivan 17:59:15 <bmotik> Zakim, this will be OWL 17:59:15 <Zakim> ok, bmotik, I see SW_OWL()1:00PM already started 17:59:37 <MarkusK_> MarkusK_ has joined #owl 17:59:54 <bmotik> Zakim, aaaa is me 17:59:54 <Zakim> +bmotik; got it 18:00:08 <Zakim> +IanH 18:00:09 <bmotik> Zakim, mute me 18:00:09 <Zakim> bmotik should now be muted 18:00:28 <IanH> zakim, who is here? 18:00:28 <Zakim> On the phone I see bmotik (muted), Ivan, IanH 18:00:35 <Zakim> On IRC I see MarkusK_, bmotik, schneid, ewallace, RRSAgent, Zakim, IanH, ivan, sandro, trackbot 18:00:37 <Zhe> Zhe has joined #owl 18:01:15 <Zakim> + +1.603.897.aabb 18:01:17 <Achille> Achille has joined #owl 18:01:17 <Bernardo Cuenca Grau> Bernardo Cuenca Grau has joined #owl 18:01:22 <Zakim> +[IPcaller] 18:01:32 <Zhe> zakim, +1.603.897.aabb is me 18:01:32 <Zakim> +Zhe; got it 18:01:35 <IanH> zakim, who is here? 18:01:35 <Zakim> On the phone I see bmotik (muted), Ivan, IanH, Zhe, [IPcaller] 18:01:36 <Zakim> On IRC I see Bernardo Cuenca Grau, Achille, Zhe, MarkusK_, bmotik, schneid, ewallace, RRSAgent, Zakim, IanH, ivan, sandro, trackbot 18:01:37 <Zhe> zakim, mute me 18:01:37 <Zakim> Zhe should now be muted 18:01:51 <schneid> zakim, [IPcaller] is me 18:01:51 <Zakim> +schneid; got it 18:01:52 <Zakim> +[IBM] 18:02:05 <schneid> zakim, mute me 18:02:05 <Zakim> schneid should now be muted 18:02:07 <Zakim> + +1.518.276.aacc 18:02:08 <Achille> Zakim, IBM is me 18:02:08 <Zakim> +Achille; got it 18:02:14 <schneid> zakim, unmute me 18:02:14 <Zakim> schneid should no longer be muted 18:02:21 <Zakim> +Evan_Wallace 18:02:30 <IanH> ScribeNick: Achille 18:02:31 <Achille> ScribeNick: Achille 18:02:32 <baojie> baojie has joined #owl 18:02:44 <Zakim> +??P15 18:02:49 <uli> uli has joined #owl 18:02:50 <Zakim> +??P12 18:02:54 <Bernardo Cuenca Grau> Zakim, ??P12 is me 18:02:54 <Zakim> +Bernardo Cuenca Grau; got it 18:03:04 <Bernardo Cuenca Grau> Zakim, mute me 18:03:04 <Zakim> Bernardo Cuenca Grau should now be muted 18:03:11 <Zakim> +??P16 18:03:19 <uli> zakim, ??P16 is me 18:03:19 <Zakim> +uli; got it 18:03:24 <baojie> Zakim, who is on the phone 18:03:24 <Zakim> I don't understand 'who is on the phone', baojie 18:03:37 <IanH> zakim, who is here? 18:03:37 <Zakim> On the phone I see bmotik (muted), Ivan, IanH, Zhe (muted), schneid, Achille, +1.518.276.aacc, Evan_Wallace, MarkusK_, Bernardo Cuenca Grau (muted), uli 18:03:39 <Zakim> On IRC I see uli, baojie, Bernardo Cuenca Grau, Achille, Zhe, MarkusK_, bmotik, schneid, ewallace, RRSAgent, Zakim, IanH, ivan, sandro, trackbot 18:03:42 <uli> zakim, mute me 18:03:42 <Zakim> uli should now be muted 18:03:45 <schneid> zakim, mute me 18:03:45 <Zakim> schneid should now be muted 18:03:49 <baojie> Zakim, aacc is baojie 18:03:49 <Zakim> +baojie; got it 18:03:51 <ivan> scribenick: Achille 18:03:51 <Zakim> +Jonathan_Rees 18:03:59 <ivan> scribe: Achille 18:04:34 <IanH> zakim, aacc is baojie 18:04:34 <Zakim> sorry, IanH, I do not recognize a party named 'aacc' 18:04:46 <msmith> msmith has joined #owl 18:04:53 <IanH> zakim, who is here? 18:04:53 :04:56 <Zakim> On IRC I see msmith, uli, baojie, Bernardo Cuenca Grau, Achille, Zhe, MarkusK_, bmotik, schneid, ewallace, RRSAgent, Zakim, IanH, ivan, sandro, trackbot 18:05:05 <alanr> alanr has joined #owl 18:05:23 <Achille> topic: Admin 18:05:23 <Achille> subtopic: Agenda amendments? 18:05:24 <alanr> zakim, who is here? 18:05:24 :05:27 :05:32 <Zakim> +msmith 18:05:36 <Achille> ianh: no agenda amendments 18:05:41 <alanr> zakim, Jonathan_Rees is alanr 18:05:41 <Zakim> +alanr; got it 18:05:49 <Achille> subtopic: Accept Previous Minutes (07 January) 18:05:59 <alanr> zakim, mute me 18:05:59 <Zakim> alanr should now be muted 18:06:00 <Achille> ian: ok to me 18:06:22 <Achille> PROPOSED: Accept Previous Minutes (07 January) 18:06:38 <Achille> RESOLVED: Accept Previous Minutes (07 January) 18:06:53 <Achille> subtopic: Pending Review Actions 18:07:08 <Achille> subsubtopic: Action 250: Send mime-type registrations in to IETF when we do last-call publications / Sandro Hawke 18:07:27 <schneid> I remember some mail this week from IETF people? 18:07:34 <Achille> ian: the applications have been made, and it is ongoing process 18:07:59 <Achille> subsubtopic: Action 261: Implement change to syntax for datetime xml schema coordination / Peter Patel-Schneider 18:08:21 <Achille> ianh: Peter has done his part. We are waiting for xml schema wg response 18:08:44 <Achille> subtopic: Due and overdue Actions 18:08:44 <Achille> subsubtopic: Action 262: Send mail to Cecil replying that we are waiting for the real comment / Alan Ruttenberg 18:08:45 <alanr> tyes 18:08:46 <alanr> yes 18:08:52 <alanr> sorry - muted 18:09:09 <Achille> ianh: Action 262 done! 18:09:35 <Achille> subtopic: Soliciting reviews of and/or comments on LC documents 18:09:48 <Achille> ianh: we did not receive a lot of comments this should be a cause for concerns at this point 18:10:03 <Zhe> q+ 18:10:20 <IanH> q? 18:10:20 <uli> zakim, mute me 18:10:21 <Zakim> uli was already muted, uli 18:10:21 <Zhe> zakim, unmute me 18:10:21 <Zakim> Zhe should no longer be muted 18:10:29 <Achille> ivan: i agree with ian concerns 18:10:42 <Achille> zhe: Oracle is sending some comments in a few days. It is hard to get further comments given the size of the spec and the background needed to understand it. 18:11:40 <ivan> q+ 18:11:43 <ivan> ack Zhe 18:11:49 <Achille> ianh: important to get comments from companies and organizations outside the working group 18:11:54 <IanH> ack zhe 18:11:57 <IanH> ack ivan 18:12:03 <Zhe> zakim, mute me 18:12:03 <Zakim> Zhe should now be muted 18:12:22 <alanr> I will do so again on the lists that I sent to. 18:12:25 <Achille> ivan: An explicit call for comment from the chair might have some positive effect 18:12:45 <Achille> ianh: yes, we will repeat the call for comment that we did initially 18:12:45 <alanr> will do 18:12:56 <Achille> ivan: great. The call should be cosign with Alan 18:13:09 <Achille> ianh: personal solicitations are even better 18:13:52 <alanr> zakim, unmute me 18:13:52 <Zakim> alanr should no longer be muted 18:13:55 <Achille> ivan: people with influencial blogs might also help by posting on their blogs 18:14:02 <Achille> ivan: Example: Alan, can you post it on your blog? 18:14:20 <msmith> yes, it does 18:14:23 <Achille> ianh: yes anybody with a blog 18:14:33 <msmith> yes 18:14:34 <Achille> alanr: Example: Clark & Parsia's blog? 18:14:36 <msmith> will pas it on 18:14:45 <alanr> zakim, mute me 18:14:45 <Zakim> alanr should now be muted 18:15:01 <Achille> ianh: Alan and I will send a final reminder on the various mailing lists 18:15:12 <Achille> ianh: people should write to their blogs 18:15:23 <Achille> ianh: personal solicitations are also recommended 18:15:35 <Achille> ianh: other ideas? 18:15:50 <Achille> subtopic: F2F5 (23-24 February, 2009) 18:16:33 <Achille> ianh: only 6 participants confirmed and 4 remote participants confirmed 18:16:51 <Achille> topic: Last Call Comments 18:17:10 <Achille> ianh: let's discuss Alan Rector's comment 18:17:11 <alanr> but this time to the official list 18:17:17 <alanr> zakim, unmute me 18:17:17 <Zakim> alanr should no longer be muted 18:17:21 <Zakim> + +1.781.271.aadd 18:17:24 <uli> i didn't see 2... 18:17:25 <msmith> I agree, it seemed close to the same 18:17:30 <Achille> ianh: is the latest version of the comment different from the first one? 18:17:39 <Achille> alanr: No, it is roughly the same. It was just moved to the right page 18:17:40 <Zhe> I just updated the F2f5, I will join. 18:17:54 <alanr> great, Zhe! 18:18:19 <IanH> zakim, who is here? 18:18:19 <Zakim> On the phone I see bmotik (muted), Ivan, IanH, Zhe (muted), schneid (muted), Achille, baojie, Evan_Wallace, MarkusK_, Bernardo Cuenca Grau (muted), uli (muted), alanr, msmith, +1.781.271.aadd 18:18:22 :19:14 <IanH> Who called in from USA area code 781? 18:19:24 <Achille> alanr: i have proposed a solution to the issue raised by Alan Rector at 18:19:31 <uli> what would the changes be? 18:19:35 <Achille> alanr: The proposed solution will require changes on our side 18:20:11 <ivan> q+ 18:20:18 <IanH> q? 18:21:09 <Achille> ivan: warning for ourselves: a major technical change will require a new Last Call (LC) 18:21:23 <uli> q+ 18:21:31 <IanH> ack ivan 18:21:42 <Achille> ianh: The change suggested by Alan will require a new LC 18:21:45 <uli> zakim, unmute me 18:21:45 <Zakim> uli should no longer be muted 18:21:45 <Achille> ivan: yes 18:21:45 <IanH> ack uli 18:22:03 <IanH> q? 18:22:12 <Achille> uli: what will be the required change? 18:22:24 <alanr> 18:22:30 <Achille> alanr: the proposed serialization is at 18:22:35 <Achille> alanr: the RDF mapping will have to change 18:22:43 <bmotik> q+ 18:23:20 <IanH> q? 18:23:27 <Joanne> Joanne has joined #owl 18:23:42 <Achille> uli: The parser will need to make sure that the strings are syntactically correct. 18:24:03 <IanH> q? 18:24:13 <Achille> uli: it sounds complicated 18:24:37 <Achille> alanr: the declarations for classes have no semantic impacts 18:25:03 <IanH> q? 18:25:26 <Achille> uli: the parser will have to make sure the class expressions are correct according to the syntax 18:25:59 <bmotik> Zakim, unmute me 18:25:59 <Zakim> bmotik should no longer be muted 18:26:08 <IanH> ack bmotik 18:26:18 <uli> zakim, mute me 18:26:18 <Zakim> uli should now be muted 18:28:01 <alanr> q+ 18:28:05 <IanH> q? 18:28:13 <Achille> bmotik: not a good idea to put all this kind of managarial information in annotation 18:28:47 <IanH> ack alanr 18:28:58 <Achille> bmotik: not important from an interoperability perspective 18:28:59 <bmotik> q+ 18:29:04 <uli> q+ 18:29:14 <uli> q- 18:29:28 <IanH> ack bmotik 18:29:30 <Achille> alanr: we cannot say to such a world-class expert in modeling that his view on modeling is wrong 18:29:39 <ivan> zakim, who is here? 18:29:39 <Zakim> On the phone I see bmotik, Ivan, IanH, Zhe (muted), schneid (muted), Achille, baojie, Evan_Wallace, MarkusK_, Bernardo Cuenca Grau (muted), uli (muted), alanr, msmith, +1.781.271.aadd 18:29:42 <uli> q+ 18:29:42 <Zakim> On IRC I see Joanne,:29:45 <uli> q- 18:29:47 <Achille> bmotik: annotations are not about modeling 18:29:53 <IanH> q? 18:30:01 <Achille> bmotik: for modeling purposes, use owl-dl 18:30:21 <Achille> bmotik: the Alan Rector's list of requirements has nothing to do with modeling 18:30:28 <IanH> q? 18:30:42 <uli> ...but we can say even to world-leading expert that, given that the complications incurred by his workaround and (!) the fact that it will still be a work-around (and not a proper fix), this isn't worth it 18:30:52 <Achille> ianh: should we continue this discussion on email? 18:31:19 <alanr> uli: Agree. Need a coherent explanation of what the complications are to support such. 18:31:19 <bmotik> q+ 18:31:23 <IanH> q? 18:31:42 <IanH> ack bmotik 18:31:46 <Achille> ianh: people should look at Alan's proposal and we need to clarify the technical issues/difficulties 18:31:59 <msmith> q+ 18:32:05 <Achille> bmotik: those issues were already discussed at the last F2F 18:32:12 <alanr> q+ 18:32:19 <msmith> q- 18:32:23 <IanH> q? 18:32:40 <Achille> ianh: i agree, but could someone send an email about the issues 18:32:48 <IanH> q? 18:32:51 <IanH> ack alanr 18:32:59 <Achille> ianh: for example,a summary of the discussions at the F2F or a pointer to the minutes of the last F2F 18:33:15 <IanH> q? 18:33:44 <Achille> alanr: i would like a discussion about the alternative solutions 18:33:55 <alanr> zakim, mute me 18:33:55 <Zakim> alanr should now be muted 18:34:19 <Achille> ianh: how do we deal with internal LC comments? 18:34:42 <ivan> q+ 18:34:50 <IanH> ack ivan 18:34:51 <Achille> ianh should they be treated the exact same way as external comments? 18:35:42 <Achille> ivan: the wiki page should contain all the comments (internal or external) because it will be used to track the changes to the spec 18:36:03 <IanH> q? 18:36:10 <alanr> ok by me 18:36:19 <schneid> +1 18:37:06 <IanH> q? 18:37:30 <IanH> q? 18:38:26 <IanH> q? 18:39:00 <Achille> ianh: I will send an email clarifying how to make and deal with WG internal comments on LC documents 18:39:44 <IanH> q? 18:39:46 <msmith> q+ 18:39:46 <ivan> action to IanH: send a mail to the group clarifying the dealing with WG internal comments on LC documents 18:39:46 <trackbot> Sorry, couldn't find user - to 18:39:56 <IanH> ack msmith 18:39:58 <Achille> action: ianh to send an email to clarify how to make and deal with WG comments on LC documents 18:39:58 <trackbot> Sorry, couldn't find user - ianh 18:40:19 <IanH> q? 18:40:47 <IanH> q? 18:41:00 <Achille> subtopic: Comment from Tim Redmond 18:41:02 <alanr> zakim, unmute me 18:41:02 <Zakim> alanr should no longer be muted 18:41:07 <IanH> q? 18:41:30 <Achille> ianh: we can simply send a note about the discussion we already had on the import issues 18:42:10 <IanH> q? 18:42:16 <Achille> alanr: I will call him to help clarify his understanding 18:42:41 <Achille> ianh: i agree with Alan that he may not have fully understood the spec 18:42:49 <IanH> q? 18:42:53 <alanr> we agreed to disagree :) 18:42:53 <ivan> yes 18:43:49 <alanr> action: alanr to talk to tim redmond about his lc comment 18:43:49 <trackbot> Sorry, couldn't find user - alanr 18:43:59 <Achille> subtopic: Comment from Andy Seaborne 18:44:11 <baojie> 18:44:13 <IanH> q? 18:44:19 <alanr> action: alanruttenberg to talk to tim redmond about his lc comment 18:44:19 <trackbot> Created ACTION-264 - Talk to tim redmond about his lc comment [on Alan Ruttenberg - due 2009-01-21]. 18:44:31 <ivan> -> Baojie's answer 18:45:03 <IanH> q? 18:45:43 <Achille> baojie: my response is at 18:45:46 <IanH> q? 18:45:51 <ivan> q+ 18:46:00 <IanH> ack ivan 18:46:48 <IanH> q? 18:46:57 <Achille> ivan: there is another comment from Andy about RDF wg taking over some datatypes 18:47:09 <IanH> q? 18:47:13 <schneid> I agree that only an RDF working group may make such a statement 18:47:27 <Achille> ivan: i agree with Andy that we should not have such a statement in our spec about RDF working group 18:47:49 <baojie> 18:47:49 <ivan> The text in the rdf:text says: "In addition to the RIF and OWL specifications, this datatype is expected to supersede RDF's plain literals with language tags" 18:48:15 <Achille> ivan: this should not be part of our document 18:48:38 <IanH> q? 18:48:42 <Achille> ianh: should we discuss this issue further? 18:48:49 <Zakim> -MarkusK_ 18:49:02 <Achille> ivan: baojie, did you also have a discussion with the RIF group? 18:49:07 <baojie> not yet 18:49:20 <IanH> q? 18:49:33 <Achille> ianh: let's add that to our todo list on the topic of coordination with RIF group 18:49:46 <Achille> topic: Test Cases 18:49:56 <Achille> ianh: Problems with approved test cases? 18:49:59 <Achille> ianh: no 18:50:30 <Achille> ianh: tests are coming in fast. It is not clear how to run the approval process 18:50:34 <alanr> q+ 18:50:38 <alanr> zakim, unmute me 18:50:38 <Zakim> alanr was not muted, alanr 18:50:40 <IanH> q? 18:50:42 <Achille> ianh: have anyone looked at the tests? 18:50:43 <IanH> ack alanr 18:50:58 <Achille> alanr: we should split the labor to make sure that every test is looked at by at least one person 18:52:39 <msmith> q+ 18:52:41 <IanH> q? 18:52:46 <Achille> ianh: If all reasoners pass successfully a test, it should not require additional human validation 18:52:46 <IanH> ack msmith 18:53:20 <Achille> mike: if there is no table entry, it means that the test cannot be tested by a OWL-DL reasoner (OWL Full test) 18:53:45 <IanH> q? 18:54:03 <Achille> mike: there are also tests meant to illustrate the differences between DL and Full 18:54:16 <IanH> q? 18:54:19 <uli> q+ 18:54:21 <schneid> q+ 18:54:22 <uli> q- 18:54:28 <schneid> zakim, unmute me 18:54:28 <Zakim> schneid should no longer be muted 18:54:29 <IanH> ack schneid 18:54:36 <MarkusK_> MarkusK_ has joined #owl 18:55:03 <IanH> q? 18:55:39 <msmith> I don't know of tests that touch these cases 18:55:40 <Zakim> +[IPcaller] 18:55:44 <Achille> schneid: there are some corner cases that will cease to be valid OWL DL 18:58:36 <schneid> schneid: there might be old test cases about the reserved vocabulary: OWL 2 DL is now more restrictive, cancelling out almost /all/ names from the rdf, rdfs, owl and xsd namespaces, where in OWL 1 many names were actually not disallowed. But these are corner cases. 18:55:58 <IanH> q? 18:56:05 <schneid> zakim, mute me 18:56:05 <Zakim> schneid should now be muted 18:56:11 <bmotik> Zakim, mute me 18:56:11 <Zakim> bmotik should now be muted 18:56:12 <IanH> q? 18:56:28 <alanr> that's one way 18:57:03 <alanr> I'll take 5 18:57:06 <Achille> ianh: how to process tests validation by reasoners? 18:57:09 <IanH> q? 18:57:14 <ivan> ok 18:57:15 <Zhe> I will take 5 18:57:26 <msmith> I've already eye-balled them all, so can do it again, but that won't help. 18:57:45 <Achille> no objection from me 18:58:02 <uli> ...why doesn't eye-balling help 18:58:04 <ivan> zakim, who is here? 18:58:04 <Zakim> On the phone I see bmotik (muted), Ivan, IanH, Zhe (muted), schneid (muted), Achille, baojie, Evan_Wallace, Bernardo Cuenca Grau (muted), uli (muted), alanr, msmith, +1.781.271.aadd, MarkusK_ 18:58:05 <uli> ? 18:58:08 <Zakim> On IRC I see MarkusK_, Joanne, alanr, msmith, uli, baojie, Bernardo Cuenca Grau, Achille, Zhe, bmotik, schneid, ewallace, RRSAgent, Zakim, IanH, ivan, sandro, trackbot 18:58:10 <Achille> ianh: does anybody object to receiving 5 testcases to evaluate? 18:58:11 <MarkusK_> I missed the discussion -- I also will check some further tests 18:58:11 <ivan> zakim, aadd is Joanne 18:58:11 <Zakim> +Joanne; got it 18:58:20 <IanH> q? 18:58:23 <uli> zakim, unmute me 18:58:23 <Zakim> uli should no longer be muted 18:58:23 <Zhe> please let me know which 5 though :) 18:58:42 <Christine> Christine has joined #owl 18:58:55 <msmith> yes. 18:59:02 <msmith> you can check my sanity :) 18:59:17 <Achille> ianh: i am not convince that it will help 18:59:39 <IanH> q? 18:59:43 <msmith> q+ 18:59:56 <Achille> alanr: it will help make sure that they are not OWL DL 19:00:07 <IanH> q? 19:00:16 <IanH> ack msmith 19:00:23 <Achille> ianh: if all three reasoners say there are not OWL DL that should be good enough, right? 19:00:48 <Zakim> +??P24 19:01:12 <Christine> Zakim, ??P24 is Christine 19:01:12 <Zakim> +Christine; got it 19:01:28 <IanH> q? 19:01:35 <Achille> mike: the entries in the table are the ones that are now OWL DL. 19:02:02 <IanH> q? 19:02:06 <Achille> mike: the only one handle to the reasoner were the OWL DL examples 19:03:08 <msmith> will do shortly 19:03:52 <uli> 19:03:54 <ivan> i do not have a practice in m'ter syntax, sorry 19:04:16 <msmith> q+ 19:04:22 <IanH> q? 19:04:27 <IanH> ack msmith 19:04:43 <msmith> +5, this would be nice 19:04:58 <msmith> @alan regarding declarations 19:05:08 <uli> zakim, mute me 19:05:08 <Zakim> uli should now be muted 19:05:32 <Achille> ianh: we can use the converter as a species checker provided that the repair functionality is disable 19:05:51 <Achille> topic: Plans for non-LC documents 19:05:55 <IanH> q? 19:06:53 <Achille> ianh: last week strawpoll on ManchesterSyntax to become Rec Track was not conclusive 19:07:16 <Achille> ianh: has anyone changed his/her mind since then? 19:07:26 <ivan> q+ 19:07:30 <Zhe> q+ 19:07:55 <Achille> ianh: would anybody raise a formal objection if ManchesterSyntax were to become a Rec Track? 19:08:09 <Christine> +q 19:08:10 <Zhe> zakim, unmute me 19:08:10 <Zakim> Zhe should no longer be muted 19:08:11 <IanH> ack ivan 19:08:48 <Achille> ivan: I do not think it is part of our scope 19:08:52 <IanH> q? 19:09:05 <Achille> ivan: it was not part of the charter, and we are taking too much here 19:09:11 <IanH> ack zhe 19:09:36 <uli> no, I don't think so 19:09:39 <Achille> Zhe: what are the consequences if it becomes rec track? will vendors be required to support it? 19:10:03 <Achille> ianh: no. 19:10:29 <Achille> ianh: it will be optional 19:10:52 <uli> q+ 19:10:57 <IanH> q? 19:11:32 <Achille> ivan: but it will mean that it is a syntax taken seriously by the group 19:12:15 <IanH> q? 19:12:19 <IanH> ack christine 19:13:16 <Achille> christine: it will become first class syntax if it becomes rec track 19:13:20 <IanH> q? 19:14:14 <uli> zakim, unmute me 19:14:14 <Zakim> uli should no longer be muted 19:14:14 <IanH> ack uli 19:14:27 <Achille> christine: what are the arguments in favor of it being rec track? 19:15:08 <Achille> uli: better visibility, interoperability between tools, and shared human readable syntax 19:16:14 <ivan> q+ 19:16:29 <ivan> q- 19:16:46 <uli> zakim, mute me 19:16:46 <Zakim> uli should now be muted 19:17:07 <IanH> q? 19:17:08 <Achille> ianh: how about ManchesterSyntax being a Note? 19:17:55 <Achille> ianh: seems nobody will vote against it 19:18:09 <uli> not extremely unhappy, but I would think that this was "treating the MS designers no too nicely" (note, I am not one of them) 19:18:11 <Achille> PROPOSED : ManchesterSyntax will be a Note 19:18:26 <schneid> what about the editor? 19:18:29 <uli> ...but I will shut up now 19:18:50 <schneid> q+ 19:18:54 <schneid> zakim, unmute me 19:18:54 <Zakim> schneid should no longer be muted 19:18:58 <IanH> ack schneid 19:19:28 <Achille> schneid: peter would be in favor of a recommendation 19:19:36 <Christine> +q 19:20:00 <schneid> zakim, mute me 19:20:00 <Zakim> schneid should now be muted 19:20:33 <Achille> ianh: we can vote now and revisit the vote in light of completely new arguments 19:20:52 <IanH> q? 19:21:19 <Achille> ivan: my impression was that peter was just lukewarmly in favor of it being Rec track 19:21:47 <Achille> christine: it would not be wlecome to delay the vote again and again. It has been on the Agenda several times before (on TC (2008.12.17), on TC (2009.01.07) and has already been postponed because one (or another) author was not there (indeed, Peter had the opportunity to support MS as a Rec if he wanted so since he was there on the previous TC 2008.12.17 and 2009.01.07, but he did not argue for it, e.g. before the straw-poll; on 2009.01.07 Bijan was not there again but Uli was there as a Manchester representative. 19:21:59 <Achille> PROPOSED : ManchesterSyntax will be a Note 19:21:59 <IanH> ROPOSED : ManchesterSyntax will be a Note 19:22:11 <ivan> +1 19:22:12 <ewallace> +1 19:22:12 <baojie> +1 19:22:14 <uli> -0 19:22:14 <Achille> +0.5 19:22:14 <MarkusK_> +0 19:22:15 <Zhe> +1 (ORACLE) 19:22:16 <msmith> 0 19:22:16 <Bernardo Cuenca Grau> 0 19:22:18 <schneid> +1 19:22:18 <bmotik> -0 19:22:18 <Christine> +1 19:22:29 <IanH> 0 19:22:50 <Achille> RESOLVED: ManchesterSyntax will be a Note 19:23:13 <Zakim> -uli 19:23:21 <Achille> topic: Coordination with RIF 19:23:51 <Achille> ianh: jie agrees to take the job wrt to rdf:text 19:24:03 <Achille> ianh: what do we need for this coordination? 19:24:12 <IanH> q? 19:24:28 <IanH> ack christine 19:24:41 <Achille> baojie: what are the other issues on the list wrt to the coordination? 19:25:01 <Christine> -q 19:25:02 <Achille> ianh: some issues regarding datatypes 19:25:08 <IanH> q? 19:25:52 <Achille> ivan: one of the issues is the difference between how owl and xml schema handle datatype value spaces 19:26:04 <baojie> is there a pointer to previous discussions? thanks 19:27:03 <Achille> ivan: we do not want different view of datatypes by owl wg and rif wg 19:27:14 <Achille> ianh: no need to discuss it in detail now 19:29:29 <Achille> topic: Additional other business 19:30:07 <Zakim> -Evan_Wallace 19:30:12 <msmith> thanks everyone, bye 19:30:13 <Zakim> -bmotik 19:30:15 <Zakim> -msmith 19:30:19 <Zhe> bye 19:30:19 <Zakim> -Achille 19:30:25 <Zakim> -MarkusK_ 19:30:28 <Zakim> -Zhe 19:30:35 <Zakim> -Christine 19:30:41 <Zakim> -Joanne 19:30:48 <Zakim> -baojie 19:30:55 <baojie> baojie has left #owl 19:31:03 <Zakim> -schneid 19:32:01 <Zakim> -Bernardo Cuenca Grau 19:32:35 <alanr> have to go to another call 19:32:44 <Zakim> -alanr 19:34:28 <alanr> alanr has joined #owl | http://www.w3.org/2007/OWL/wiki/Chatlog_2009-01-14 | CC-MAIN-2015-32 | refinedweb | 4,905 | 69.04 |
A new version of the IBM Cloud Pak for Integration, 2019.4.1, was recently released which includes new IBM App Connect Enterprise certified container features.
The new features in this release include:
- Support for Red Hat OpenShift Container Platform 4.2
IBM Cloud Pak for Integration 2019.4.1 requires OpenShift 4.2, and for IBM App Connect Enterprise users that includes the addition of OpenShift Routes for HTTP and HTTPS traffic to a deployed integration server, which provide consistent endpoints for interactions.
- Deploy API flows authored in IBM App Connect Designer
You can now combine the ease of authoring flows for APIs in IBM App Connect Designer with the flexibility of deploying into your own private cloud. Previously, the managed cloud service had been the only valid deployment target for a Designer-authored flow, but now you can deploy into IBM Cloud Pak for Integration with IBM App Connect Enterprise. In 2019.4.1 this also includes the ability to run a subset of connectors locally, in addition to interacting with connectors in the IBM App Connect managed cloud service. See this blog post for more information about this feature.
- User authorization for the IBM App Connect Enterprise dashboard
User authorization has been added for the IBM App Connect Enterprise dashboard using the Identity and Access Management (IAM) service. The authority to use a dashboard can now be determined by the user’s authority for the namespace that contains the dashboard. The different roles for the users provide different permissions for actions in the dashboard.
IBM Cloud Pak for Integration 2019.4.1 is available in a PPA via IBM Passport Advantage (Part CC4R5EN), or via the IBM Cloud Entitled Registry.
It’s Really nice. Thank you for this. | https://developer.ibm.com/integration/blog/2019/12/06/cloud-pak-for-integration-2019-4-1-ace/ | CC-MAIN-2020-34 | refinedweb | 291 | 54.83 |
5.7. Releasing the GIL to take advantage of multi-core processors with Cython and Open
As we have seen in this chapter's introduction, CPython's GIL prevents pure Python code from taking advantage of multi-core processors. With Cython, we have a way to release the GIL temporarily in a portion of the code in order to enable multi-core computing. This is done with OpenMP, a multiprocessing API that is supported by most C compilers.
In this recipe, we will see how to parallelize the previous recipe's code on multiple cores.
Getting ready
To enable OpenMP in Cython, you just need to specify some options to the compiler. There is nothing special to install on your computer besides a good C compiler. See the instructions in this chapter's introduction for more details.
The code of this recipe has been written for gcc on Ubuntu. It can be adapted to other systems with minor changes to the
%%cython options.
How to do it...
Our simple ray tracing engine implementation is "embarrassingly parallel" (see); there is a main loop over all pixels, within which the exact same function is called repetitively. There is no crosstalk between loop iterations. Therefore, it would be theoretically possible to execute all iterations in parallel.
Here, we will execute one loop (over all columns in the image) in parallel with OpenMP.
You will find the entire code on the book's website (
ray7 example). We will only show the most important steps here:
1. We use the following magic command:
%%cython --compile-args=-fopenmp --link-args=-fopenmp --force
2. We import the
prange() function:
from cython.parallel import prange
3. We add
nogil after each function definition in order to remove the GIL. We cannot use any Python variable or function inside a function annotated with
nogil. For example:
cdef Vec3 add(Vec3 x, Vec3 y) nogil: return vec3(x.x + y.x, x.y + y.y, x.z + y.z)
4. To run a loop in parallel over the cores with OpenMP, we use
prange():
with nogil: for i in prange(w): # ...
The GIL needs to be released before using any parallel computing feature such as
prange().
5. With these changes, we reach a 3x speedup on a quad-core processor compared to the fastest version of the previous recipe.
How it works...
The GIL has been described in the introduction of this chapter. The
nogil keyword tells Cython that a particular function or code section should be executed without the GIL. When the GIL is released, it is not possible to make any Python API calls, meaning that only C variables and C functions (declared with
cdef) can be used.
See also
- Accelerating Python code with Cython
- Optimizing Cython code by writing less Python and more C
- Distributing Python code across multiple cores with IPython | https://ipython-books.github.io/57-releasing-the-gil-to-take-advantage-of-multi-core-processors-with-cython-and-openmp/ | CC-MAIN-2019-09 | refinedweb | 475 | 64.71 |
#include <shadow.h> int putspent(const struct spwd *p, FILE *fp);
The putspent() function is the inverse of getspent(). See getspnam(3C). Given a pointer to a spwd structure created by getspent() or getspnam(), putspent() writes a line on the stream fp that matches the format of /etc/shadow.
The spwd structure contains the following members:
char *sp_namp; char *sp_pwdp; int sp_lstchg; int sp_min; int sp_max; int sp_warn; int sp_inact; int sp_expire; unsigned int sp_flag;
If the sp_min, sp_max, sp_lstchg, sp_warn, sp_inact, or sp_expire member of the spwd structure is −1, or if sp_flag is 0, the corresponding /etc/shadow field is cleared.
The putspent() function returns a non-zero value if an error was detected during its operation. Otherwise, it returns 0.
Since this function is for internal use only, compatibility is not guaranteed. For this reason, its use is discouraged. If used at all, if should be used with putpwent(3C) to update the password file.
See attributes(5) for descriptions of the following attributes:
getpwnam(3C), getspnam(3C), putpwent(3C), attributes(5) | http://docs.oracle.com/cd/E36784_01/html/E36874/putspent-3c.html | CC-MAIN-2016-30 | refinedweb | 175 | 53.1 |
.
You may need to read my previous tutorial How to install Git on Windows
Creating a Project
This section is to learn how to create a git repository from scratch.
Creating a hello directory
Go to the physical drive
D and create a directory called
GitProjects and under this
GitProjects directory create another directory called
hello.
Creating a repository
So in the previous step I have created a
hello directory under another directory
GitProjects but the
hello directory has not yet been repository.
Now open a cmd prompt and navigate to the directory
D:\GitProjects\hello and type the command
git init to create a repository hello. You will see the message after successful creation of the git repository on directory
hello
Initialized empty Git repository in D:/GitProjects/hello/.git/
Adding a page to the repository
Create the below java class under the directory
hello
public class HelloWorld { public static void main(String[] args) { // Prints "Hello, World" to the terminal window. System.out.println("Hello, World"); } }
But the above java file has not been yet added to the repository. To add the above file to the repository, type the command
git add HelloWorld.java. Now the java file has been added to the repository but has not been committed to the repository, something similar to the SVN concept. Now to commit the file execute the command
git commit -m "First java commit", where
-m "First java commit" represents your commit comment. You will see the below message after successful commit to the repository
[master (root-commit) f7f4e7c] First java commit 1 file changed, 8 insertions(+) create mode 100644 HelloWorld.java
Checking status of the repository
This section is to learn how to check the status of repository.
To check the status of the repository execute the command
git status. You will see the below message
On branch master nothing to commit, working tree clean
The above message means that there is nothing left in the repository to commit in the current state of the working directory.
Modification on the working directory files
This section is to learn how to monitor on the state of current working directory.
Modification to the HelloWorld.java file
Let’s remove the comment
// Prints "Hello, World" to the terminal window. from the HelloWorld class
Checking the status
Run the command
git status, you will see the following message
On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: HelloWorld.java no changes added to commit (use "git add" and/or "git commit -a")
The first important point here is that git knows
HelloWorld.java file has been changed, but the changes are not yet committed to the repository.
Another point is that the status message hints about what to do next. If you want to add these changes to the repository, use
git add <file>. To undo the changes use
git checkout -- <file>.
Staging the Modifications or Changes
This section is to learn how to stage changes or modifications for the upcoming commits.
Staging is a step before the commit process in Git. That is, a commit in Git is performed in two steps: staging and actual commit. As long as a change or modification is in the staging area, Git allows you to edit it as you like (replace staged files with other versions of staged files, remove changes from staging, etc.).
Let Git know about the changes
Run the command
git add HelloWorld.java. Then again run the command
git status. You will see the following message
On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: HelloWorld.java
Changes to the
HelloWorld.java have been staged. This means that Git knows about the changes, but it is not permanent in the repository.
If you want not to commit the change, the status command above reminds you that you can use the
git reset HEAD <file> command to unstage these changes.
If you want to add multiple files to the Git repository then execute the command, for example, if you want to add three files – file1, file2, file3 to the repository,
git add file1 file2 file3
If you want your all modified files to be added to the repository then execute the command
git add -A
Commit the changes
This section is to learn how to commit the changes or modifications.
If you simply execute the command
git commit then it will ask for comment message for the commit. If you execute the command
git commit -m "<some comment>" then it will not prompt for the commit comment.
When you simply execute
git commit then you will see something similar to below window for inputting your comment for the commit and a cursor will continuously blink.
So now press
i from keyboard and write the comment as
"remove comment" and press
Esc from keyboard and type
:wq and press
Enter key.
You will see the following message in the cmd prompt
[master 76a6e8d] "remove comment" 1 file changed, 1 deletion(-)
Now if you execute command
git status then you will see the below message and it clearly says there is nothing to commit. So all commits have been made permanent to the repository.
On branch master nothing to commit, working tree clean
Project’s History
This section is to learn about the history of changes in the project or working directory.
To list the changes in a project, execute the command
git log. You will see the history of changes made to the repository
hello
commit 76a6e8d79acf28003d0ba351079bdcadab32af9c Author: moni <[email protected]> Date: Thu Jan 5 10:23:53 2017 +0530 "remove comment" commit f7f4e7c6b0a28ecd6cd59ec259fcda48d0174678 Author: moni <[email protected]> Date: Wed Jan 4 08:20:42 2017 +0530 First java commit
The above history shows in multiple lines and if you want to see it in one line, execute the command
git log --pretty=oneline. You will see the below output
76a6e8d79acf28003d0ba351079bdcadab32af9c "remove comment" f7f4e7c6b0a28ecd6cd59ec259fcda48d0174678 First java commit
You can have other options with the git log command, for example
To see the history of only last two changes:
git log --pretty=oneline --max-count=2
To see the history of changes that have happened since 04/01/2017:
git log --pretty=oneline --since='04/01/2017'
To see the history of changes that have happened until 04/01/2017:
git log --pretty=oneline --until='04/01/2017'
To see the history of changes done by an author:
git log --pretty=oneline --author=<your name>
To see the history of all changes:
git log --pretty=oneline --all
More about git log command can be found at
Thanks for reading.Tags: Version Control
2 thoughts on “Git Tutorial”
HI, Soumitra Roy Sarkar
Do you have source code in github?
No. | https://www.roytuts.com/git-tutorial/ | CC-MAIN-2020-16 | refinedweb | 1,140 | 57.3 |
Your Account
Print
PRESS QUERIES ONLY
O'Reilly Media
(707) 827-7000
August 17, 2006
Sebastopol, CA--Recently JavaScript has gone from being the ugly
duckling of web scripting languages to being the force behind such Ajax powerhouses as Gmail and Backpack. The language has grown in importance and the size of scripts has ballooned.
As David Flanagan, author of the JavaScript: The Definitive
Guide (Fifth
edition, O'Reilly, US $49.99) notes, "After the fourth edition of my
book
was published in 2001, the world of client-side web development
entered a
four-year period of relative stability. JavaScript was stable and well
supported at version 1.5. The W3C DOM was stable, and reasonably well
supported by developers. I grew complacent...there never seemed to be
the
need to update the fourth edition.
"Then."
So Flanagan set himself to overhauling the classic, bestselling guide to
JavaScript (with more than 300,000 copies sold). He explains, "The new
edition has been thoroughly updated so that it covers JavaScript the way
it is used today, rather than the way it was used in 2001. These changes
appear throughout the book. But the most important new material are the
new chapters on scripted HTTP and XML manipulation: these are the
cornerstones of Ajax applications, and these two new chapters explain
them, with detailed examples.
"Almost as important are the rewritten chapter on JavaScript classes and
the new chapter on JavaScript namespaces. For today's web applications,
JavaScript developers are writing programs that are an order of
magnitude
longer than the scripts that most of us were writing five years ago. The
new material on classes and namespaces explains how to structure
JavaScript programs and offer techniques for successfully using
JavaScript
for 'programming in the large.'"
This book is both an example-driven programmer's guide and a
keep-on-your-desk reference, with new chapters that explain
everything you
need to know to get the most out of JavaScript.
Part I explains the core JavaScript language in detail. Those who are
new
to JavaScript can learn the language from this section. Experienced
JavaScript programmers can read it to sharpen their skills and deepen
their tag.
Flanagan is pleased with the new volume's coverage, "Many JavaScript
developers have started to write longer programs and use more
sophisticated programming techniques, such as closures and namespaces.
This fifth edition has been fully revised for the new world of Ajax and
Web 2.0 technologies. I was surprised to discover that I had almost
twice
as many examples as I did in the fourth edition and the examples are
more
than twice as long."
More than 300,000 JavaScript programmers around the world have made this
their indispensable reference book for building JavaScript applications.
This updated version will lead them and others into the new world of
JavaScript programming.
JavaScript: The Definitive Guide, Fifth Edition
David Flanagan
ISBN: 978-0-596-10199-2, 994. | http://oreilly.com/pub/pr/1614 | CC-MAIN-2013-20 | refinedweb | 490 | 60.95 |
CodePlexProject Hosting for Open Source Software
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="_default" %>
<asp:Content
**paste here whatever you like, like what's already in a newpage.aspx **
</asp:Content>
I think I have a working example of what Amateur was trying to do.
here is some code that uses the blogengine controlls and then access some of the non blogengine controls. This example is a downoad page.
the first part is download.aspx.cs
________________________________________________
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.IO;
public partial class download : BlogBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
// Some code here. whatever you are trying to accomplish
}
}
_________________________________
download.aspx
___________________________________
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="download.aspx.cs" Inherits="download" ValidateRequest="false" %>
<%@ Import Namespace="BlogEngine.Core" %>
<asp:Content
<asp:Button
</asp:Content>
_________________________
I got to this point by hacking contact.aspx and contact.aspx.cs and then of course put the <a id="A2" href="~/download.aspx" runat="server">Download</a> By the other links in site.master
I spent about 6-8 hours on this. I sould of gave up on google after 20 minutes and worked it out myself.
Can anyone explain how I do 2.
Set this page as FrontPage via the admin interface
Can't find this option anywhere
Thanks in advance
Edit the page you wish to be the Front page and the checkbox is at the top right to make it a Front page.
Jerry,
Thanks for the prompt response, as stupid as this may sound can you explain where the
check box in the top right is?
i'm using VWD 2008 if that makes a difference.
Thanks in advance
Do this though your web browser, with BE 2.0 you login, click on pages, then the page that you want to be the front page or create the page, with that page open click on edit and the checkbox is there.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://blogengine.codeplex.com/discussions/20397 | CC-MAIN-2017-22 | refinedweb | 410 | 62.44 |
.
- Functions: run arbitrary pieces of code to either modify or validate your configurations.
- Function pipeline: a set of functions that the package author has included with the package.
- Resource management: apply, update, and delete the resources that correspond to your configurations in a Kubernetes cluster.
Objectives
- Create a Google Kubernetes Engine (GKE) cluster.
- Use kpt to download an existing set of Kubernetes configurations.
- Use kpt.
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.:
mkdir -p ~/bin curl -L --output ~/bin/kpt && chmod u+x ~/bin/kpt export PATH=${HOME}/bin:${PATH}
Download an example set of configurations. For more information, see
kpt pkg get.
kpt pkg get
The preceding command downloads the
wordpresssample package that is available in the kpt GitHub repository, at the version tagged
v0.7.
Examine the package contents:
kpt pkg tree.
kpt pkg tree wordpress/
The output looks like the following:
Package "wordpress" ├── [Kptfile] Kptfile wordpress ├── [service.yaml] Service wordpress ├── deployment │ ├── [deployment.yaml] Deployment wordpress │ └── [volume.yaml] PersistentVolumeClaim wp-pv-claim └── Package "mysql" ├── [Kptfile] Kptfile mysql ├── [deployment.yaml] PersistentVolumeClaim mysql-pv-claim ├── [deployment.yaml] Deployment wordpress-mysql └── [deployment.yaml] Service wordpress-mysql
The package contains two packages the top level one
wordpressand a subpackage
wordpress/mysql, both of these packages contain a metadata file
Kptfile.
Kptfileis only consumed by kpt itself and has data about the upstream source, customization and validation of the package
Update the label of the package
The author of the package added a rendering pipeline which is often used to convey the expected customizations.
less wordpress/Kptfile
The contents should look something like this:
apiVersion: kpt.dev/v1 kind: Kptfile metadata: name: wordpress upstream: type: git git: repo: directory: /package-examples/wordpress ref: v0.7 updateStrategy: resource-merge upstreamLock: type: git git: repo: directory: /package-examples/wordpress ref: package-examples/wordpress/v0.7 commit: cbd342d350b88677e522bf0d9faa0675edb8bbc1 info: emails: - kpt-team@google.com description: This is an example wordpress package with mysql subpackage. pipeline: mutators: - image: gcr.io/kpt-fn/set-label:v0.1 configMap: app: wordpress validators: - image: gcr.io/kpt-fn/kubeval:v0.1
You can use your favorite editor to change the parameters of the set-label function from
app: wordpressto
app: my-wordpress
Edit the MySQL deployment
wordpress/mysql/deployment.yamlusing your favorite editor to change the MySQL version and add an argument.
Before:
[...] containers: - name: mysql image: mysql:5.6 [...]
After:
[...] containers: - name: mysql image: mysql:5.7 args: - --ignore-db-dir=lost+found [...]
Unlike tools that operate only through parameters, kpt allows you to edit files in place using an editor and then will still merge the upstream updates. You can edit the
deployment.yamldirectly without having to craft a patch or creating a function in the pipeline.
Annotate the configuration with
sample-annotation: sample-value.
kpt fn eval wordpress --image gcr.io/kpt-fn/set-annotations:v0.1 \ -- sample-annotation=sample-value
The output should look something like this:
[RUNNING] "gcr.io/kpt-fn/set-annotations:v0.1" [PASS] "gcr.io/kpt-fn/set-annotations:v0.1"
To see the new annotation you can examine any configuration value, a simple one to see is
wordpress/service.yaml
In this example we did a customization using a function in a way that the package author didn't plan for. kpt is able to support declarative and imperative function execution to allow for a wide range of scenarios.
If this package was developed using infrastructure-as-code we would need to go to the source of the package and edit code there.
Run the pipeline and validate the changes using kubeval through kpt.
kpt fn render wordpress
The package author has included a validation step in the pipeline:
... validators: - image: gcr.io/kpt-fn/kubeval:v0.1
The successful output of this rendering pipeline looks like this:
Package "wordpress/mysql": [RUNNING] "gcr.io/kpt-fn/set-label:v0.1" [PASS] "gcr.io/kpt-fn/set-label:v0.1" Package "wordpress": [RUNNING] "gcr.io/kpt-fn/set-label:v0.1" [PASS] "gcr.io/kpt-fn/set-label:v0.1" [RUNNING] "gcr.io/kpt-fn/kubeval:v0.1" [PASS] "gcr.io/kpt-fn/kubeval:v0.1" Successfully executed 3 function(s) in 2 package(s). wordpress
Initialize the package for deployment:
kpt live init wordpress
The preceding command builds an inventory of the configurations that are in the package. Among other things, kpt uses the inventory to prune configurations when you remove them from the package. For more information, see
kpt live.
Create a secret that contains the MySQL password:
kubectl create secret generic mysql-pass --from-literal=password=foobar
Apply the configurations to your GKE cluster:
kpt live apply wordpress
The output looks like the following:
service/wordpress created service/wordpress-mysql created deployment.apps/wordpress created deployment.apps/wordpress-mysql created persistentvolumeclaim/mysql-pv-claim created persistentvolumeclaim/wp-pv-claim created 6 resource(s) applied. 6 created, 0 unchanged, 0 configured, 0 failed 0 resource(s) pruned, 0 skipped, 0 failed
Wait a few minutes, and then verify that everything is running as expected:
kpt live status wordpress
The output looks like the following:
service/wordpress is Current: Service is ready service/wordpress-mysql is Current: Service is ready deployment.apps/wordpress is Current: Deployment is available. Replicas: 1 deployment.apps/wordpress-mysql is Current: Deployment is available. Replicas: 1 persistentvolumeclaim/mysql-pv-claim is Current: PVC is Bound persistentvolumeclaim/wp-pv-claim is Current: PVC is Bound wordpress/ git init git config user.email "YOUR_EMAIL" git config user.name "YOUR_NAME"
Commit your configurations:
git add . git commit -m "First version of helloworld" cd ..
Update your local package. In this step, you pull the
v0.8version from upstream.
kpt pkg update wordpress@v0.8
Observe that updates from upstream are applied to your local package:
cd wordpress/ git diff
In this case, the update has changed the wordpress deployment volume from 2Gi to 3Gi.
Commit your changes:
git commit -am "Update to package version v0.8"
Apply the new version of the package:
kpt live apply ."
Apply the change, and then verify that kpt pruned the wordpress service::
gsutil cp gs://config-management-release/released/latest/linux_amd64/nomos ~/bin/nomos chmod +x ~/bin/nomos.
Use kpt to copy the package's content in the Config Sync repository, and then add labels to customize it:
kpt fn source default-deny/ | \ kpt fn eval - --image=gcr.io/kpt-fn/set-annotations:v0.1 -- \ anthos-security-blueprint.
Create the
namespace.yamlfile in the Config Sync repository:
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Delete the project
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Delete the. | https://cloud.google.com/architecture/managing-cloud-infrastructure-using-kpt?utm_campaign=CDR_ale_GCP_twigcp_2021week9&utm_source=Blog&utm_medium=Blog | CC-MAIN-2022-27 | refinedweb | 1,209 | 50.63 |
User talk:KTucker
Leave a message for Ktucker
Portals[edit source]
I've been looking at the Wikipedia portal pages that use "tabs" and wondering how to make them. I've made most of the existing Wikiversity portal pages by starting with Template:Box portal skeleton. Is there a similar way to start portals like Portal:Social entrepreneurship? --JWS 13:27, 20 October 2007 (UTC)
[edit source]
- "finding a consistent way to have a snippet in a portal box with a link to 'more ...'." <-- I'm not sure what you mean. At the Education Portal the section called "The Wikiversity model for online learning" has a link like this: .....read more.....
- See also Making links.
- "how deep to make hierarchies (I guess no more than 3 levels is a good rule of thumb." <-- A significant amount of Wikiversity content is organized hierarchically using content development projects. However, there can also be a hierarchy of portals. For example, Portal:Science links to other science-related portals such as Portal:Life Sciences. So if there are ever too many learning resources to fit into an existing portal page for some topic, you can always start making new portals that are devoted to subtopics. It is also useful to have "navigation boxes" that provide links to related pages. For example see the Web 2.0 template in the "see also" section of Rendering models of living organisms. --JWSchmidt 15:08, 20 October 2007 (UTC)
Pages for deletion[edit source]
Hi. You left quite a lot of notes on pages for them to be deleted after content was moved. Your methods were not quite kosher, although well-intended. Probably the best thing is to "move" the page, rather than the content. If you really have to move the content and not the page, then use a deletion template, because otherwise most custodians wouldn't find your notes! I was slightly surprised, as I assumed you were an experienced wiki editor. Something I missed?! Anyway, I've cleared up the pages for you, and if there's any more you need me to delete, you can also leave me a message. McCormack 09:35, 23 November 2007 (UTC)
- Thanks for your off-wiki question about deleting pages. If you need to delete anything in future, or find anything which needs deleting, there are two recommended methods. One is to use a deletion template (which can be quite time-consuming, as you need to enter your reasons on a separate page); the second method is to contact a custodian (which is easy, because the custodian then does the work!). McCormack 12:27, 11 December 2007 (UTC)
Image:Theme-based.png[edit source]
Please provide a license template and source for this image. Thanks. – Mike.lifeguard | @en.wb 21:53, 13 February 2008 (UTC)
Moving your portals to the main namespace[edit source]
Hi. I've made a proposal at Wikiversity:Portal reform to move your Floss4Science and Social Entrepreneurship portals into the main namespace of Wikiversity. I wanted to ask if you are OK with this. There are a number of advantages. One is that portals are really only for orientation, not content. Another is that your material will be more easily found in the main namespace, due to things like how automated categorisation and search results work. Please let me know if the move is OK with you. You don't have to worry about the technical side - that will be done for you. --McCormack 15:52, 12 May 2008 (UTC)
- Hi again, and thanks for your comments on the talk page of the portal reform project. I hope you weren't offended by my rather megalomaniac suggestions. The main namespace was seen rather as a "promotion" of the status of your content and would have drawn it more to the eyes of others. I'd like to suggest an alternative, if the intention of all these portal subpages is organisational: the alternative is the Topic namespace. In fact the Portal, School and Topic namespaces are all organisational at Wikiversity, the Portal namespace really being for very major topic areas like "Education" or "History", while the other two are for more specialised project organisation. My guess is that FLOSS4Science could come under the Education and Science portals, although I'm not sure which superordinate area Social Entrepreneurship fits into. The idea is that we would fit these Topics into the framework of major portals, so that people could find them more easily. What do you think? And where does Social Entrepreneurship fit in subject-wise? Thanks for any guidance you can give. --McCormack 17:17, 13 May 2008 (UTC)
- Hi yet again. Thanks for your "not convinced" post. This probably means you really don't like the mainspace suggestion, but what about the Topic: namespace suggestion? And could you clarify which disciplines these cross into for categorisation purposes? Thanks! --McCormack 12:26, 16 May 2008 (UTC)
- Thanks James. At the end of this we should be in a good position to extend the guidelines for editors of portals :-). Sometimes these may need to be customised for specific types of portals and according to the preferences of the initiator and/or community. For our tabbed portals (see Make a portal) we have some Guidelines for editors (Social Entrepreneurship and FLOSS4Science).
Multiple learning models[edit source]
Hi Kim, and thanks for your comments and support of a "multiple learning models" approach. This is just what I've been trying to work on, piece by piece, for a long time now. One of my more recent contributions here was Wikiversity:learning models (note the "s" on the end), but all of this work is still at an early phase. I'm trying to bind my work into a thoroughly empirical or fact-driven analysis of Wikiversity, so that I don't wander too far from what actual contributors want. If you'd like to help with this process at all, you are extremely welcome. I appreciate feedback, as I know there is always a danger of imposing one's own views, even when one tries to stick to the data. --McCormack 08:22, 22 August 2008 (UTC)
Dear K Tucker, I am available for any help for the project on social entrepreneurship. --Prof. Vivek Sharma 06:47, 5 September 2008 (UTC)
Hope you don't mind[edit source]
I edited your sandbox a bit... The "E" on the end of FULLPAGENAME lets the "pipe" work (so it doesn't interpret the space in "My sandbox" improperly: it reads it as My_sandbox instead). The span stuff is explained at mw:Plainlinks. --SB_Johnny talk 15:37, 10 December 2008 (UTC)
Think tank[edit source]
Hi Kim. Would you be willing to help out with Wikiversity:Think tank? Your template experience could be a big help when jump-starting new initiatives! --SB_Johnny talk 12:23, 15 December 2008 (UTC)
- Sure - though I cannot really commit to doing anything on account of time limitations. Most of what I am doing and learning via the SSE project may be improved, refined and generalised. Ktucker 14:49, 15 December 2008 (UTC)
Your question at colloquium[edit source]
Hello, Ktucker. I have prefixed your FULLPAGENAME with a ":". Do these (Portal:Sandbox, main space sandbox) satisfy you? Hillgentleman | //\\ |Talk 12:52, 30 December 2008 (UTC)
Deletion requested for categories[edit source]
For your information: I requested a deletion fo a lot for categories
- Category:Project Types (Social Entrepreneurship)
- Category:Themes (Social Entrepreneurship)
- Category:Social (Social Entrepreneurship)
- Category:Literacy (Social Entrepreneurship)
- Category:ICT Literacy (Social Entrepreneurship)
- Category:Health (Social Entrepreneurship)
- Category:Environment (Social Entrepreneurship)
- Category:Education System (Social Entrepreneurship)
- Category:Education (Social Entrepreneurship)
- Category:Economic (Social Entrepreneurship)
- Category:Cultural Development (Social Entrepreneurship)
- Category:Business Management (Social Entrepreneurship)
- Category:Agriculture (Social Entrepreneurship)
- Category:Themes (Social Entrepreneurship)
- Category:Recreation (Social Entrepreneurship)
- Category:ICT (Social Entrepreneurship)
- Category:Environmental (Social Entrepreneurship)
- Category:Entrepreneurial (Social Entrepreneurship)
- Category:Educational (Social Entrepreneurship)
because these are all empty sinc creation in dec 2007. HenkvD 19:34, 12 February 2009 (UTC)
Also:
- Category:Africa (Social Entrepreneurship)
- Category:Togo (Social Entrepreneurship)
- Category:Nigeria (Social Entrepreneurship)
- Category:Ghana (Social Entrepreneurship)
- Category:South Africa (Social Entrepreneurship)
- Category:Namibia (Social Entrepreneurship)
- Category:Botswana (Social Entrepreneurship)
- Category:Uganda (Social Entrepreneurship)
- Category:Kenya (Social Entrepreneurship)
- Category:East Africa (Social Entrepreneurship)
for the same reason. HenkvD 19:47, 12 February 2009 (UTC)
Hi HenkvD,
Thanks for your diligence and for caring about keeping the Wikiversity categories tidy.
In this case, please reverse the speedy deletions of the categories you mentioned on my user talk page.
The project with which they are associated is due to be promoted in 2009. Having the categories already available will be useful to new entrants. The categories are listed in the guidelines for editors.
There are also many pages which still need to be categorised using these categories. I have just not had time to do it of late and don't have time now to comment on all the categories you have flagged.
Thanks
Kim Ktucker 22:37, 12 February 2009 (UTC)
- Noted, I will act later. HenkvD 14:23, 13 February 2009 (UTC); I just undid me deletion request. I wish you all the best with promotion of this project. HenkvD 18:58, 13 February 2009 (UTC)
hi there[edit source]
Hi Kim,
Where are you from? I will be attending the Skoll World Forum at the end of March. I live in Silver Spring, MD.
Hear from you soon.
Tegy
- Hi Tegy, I have e-mailed you. Kim
FLOSS4Science[edit source]
I hadn't noticed Portal:FLOSS4Science until just now. This is a great idea, and I would like to see this developed. --mikeu talk 11:46, 6 September 2009 (UTC)
/* Ktucker => KTucker */moves done[edit source]
It may be best if the old Ktucker user talk page is moved here, and if there is annotation with both accounts that they are both you. In theory, the rename should have been done, but we are a bit short of 'crat work at this point. Will you allow me to assist you with this as a custodian? Thanks. --Abd 16:00, 7 October 2011 (UTC)
- Sure, you are welcome to help if you have time. For me this is not urgent and does not matter that much any more since I managed to set KTucker as my global SUL login and can use it on all Wikimedia projects :-). If it makes sense to phase out the lower case name, it would be good to migrate the user page itself (User:Ktucker => User:KTucker) and all the other things that go with it: sub-pages (there are many especially under my sandbox), talk pages, history, contributions, watch list, .... I can probably do some of it (e.g. copy my watch list) but others are beyond my current knowledge and permissions. - K 19:13, 7 October 2011 (UTC) and KTucker 19:14, 7 October 2011 (UTC)
- Here is what I'd do: move all your user subpages to the new user name. That's a single command for me, subpage moves can be such for a custodian. It's just not easily undoable!
- I would rename your old user and user talk pages to the new name, if that's what you want, leaving behind redirects so that if anyone tries to contact Ktucker, they will get your user page, KTucker. This is pretty much what a 'crat would have done; the only difference will be that the Ktucker contributions history will not show under KTucker contributions. We'll handle that with references so that someone who needs to see it can easily find it. Okay? --Abd 22:03, 7 October 2011 (UTC)
DoneAll pages under User or User talk Ktucker have been moved. Redirect was suppressed for all pages under and including User:Ktucker/My Sandbox. A redirect was left for all other pages moved. The content above in this section was copied from User talk:KTucker/temp, now deleted. I'd moved that out of the way so that the move would complete. I probably could have done that better, with a merge, but ... I haven't done a page merge yet. This did the job.
- This is your current user page space content, and this is your current user Talk content.
- If you wish any of these pages deleted, where you are the only author, you may place a speedy deletion template on them, use this, at the top:
{{delete|author request --~~~~ (= Ktucker)}}
and it will normally be quickly done. You may also wish to look at the created subpage redirects, [1], some might be deletable.
- I have not checked for links to all your moved pages. While I intend to check, it's not impossible that some redirects were broken or that double redirects were created. --Abd 16:50, 8 October 2011 (UTC)
- Thanks :-).
- Re: "Redirect was suppressed for all pages under and including User:Ktucker/My Sandbox" (above):
- Is it possible to restore the red links on this page those pages have sub-pages which do exist. My sandbox is a personal learning environment and I sometimes direct people there to show them how to do stuff. - KTucker 17:23, 8 October 2011 (UTC)
- I'm puzzled. User:KTucker/My Sandbox#Page and Section Layout Templates shows redlinks in that section. However, if I edit the section and Preview, they are valid links. The redlinks also can be followed to the pages. I think this has to do with the usage of the pipe in the link. I saw this with another page today. Bug? In any case, eliminating the terminal / in the pagename works. I fixed them. --Abd 19:22, 14 October 2011 (UTC)
- Thanks. There are a few more under Properties (and sub-pages). - KTucker 19:49, 14 October 2011 (UTC)
- Those red links are due to explicit page links to subpages still referring to locations in User:Ktucker space. I fixed them, but if you find more, you should fix them if you can. By the way, I'm not a 'crat, if you were referring to me with [2]. --Abd 00:20, 15 October 2011 (UTC)
- Oh, so it is just a matter of changing explicit links to Ktucker. Thanks for changing those, I will change others as I find them. Apologies re "'crat" - I just meant someone with more knowledge, skills and privileges than I have who might have an automatic way of finding such broken links. Thanks again - KTucker 08:28, 15 October 2011 (UTC)
Test Subst[edit source]
I don't really think this should be in mainspace if it's only used to test the subst: function (which can be done with pages which do belong in the mainspace). I've therefore tagged it for speedy deletion. Thanks. --S Larctia 11:13, 9 October 2011 (UTC)
File:SusanSteinman64x96.jpg[edit source]
Hi! I've been doing a bit of a clean up of non-free images, and came across one of Susan Steinman that you uploaded. As policy prohibits the use of non-free images of living people, I've had to remove it for now. I hope that isn't a problem, but if it is I'd be really happy to help either find a replacemant or look at whether or not there is a way of using one there. As ana side, though, your Portal:Social entrepreneurship work is great - it looks like a wonderful project. :) - Bilby 04:26, 19 October 2011 (UTC)
- Hi. Thanks for letting me know. The person in the photo, gave it to me to use on that page on WikiVersity while we were working on the project in 2008. If removing it is the right thing to do, then thanks for doing so. - KTucker 09:44, 19 October 2011 (UTC)
- For the file to be used, it has to be released under a free license, such as CC-BY-SA 3.0/GFDL dual licensing, or released into the public domain. If you could confirm this from Ms. Steinman, the file can be kept, but I'm afraid that otherwise we'll have to delete the image. --Simone 09:47, 19 October 2011 (UTC)
Appreciative Valuation[edit source]
Hi. Just to let you know, this resource has been proposed for deletion. If you would like it to stay at Wikiversity, feel free to contest the deletion by removing the {{proposed deletion}} template. --Claritas 21:09, 6 January 2012 (UTC) | https://en.wikiversity.org/wiki/User_talk:Ktucker | CC-MAIN-2020-50 | refinedweb | 2,742 | 63.29 |
Geek Challenge Results: Fractal Snowflake Ken Brey 02/05/2015 0 Comments The winner of the Fractal Snowflake Geek Challenge is John Jacobsma of Dickson. Tim Jager of DMC also responded with a correct value of C, 10830. The Fractal Snowflake Challenge was a study in recursive programming. Recursive programming is a technique where a function calls itself, usually many times, until eventually instead of calling itself, it just does something. The program had two layers of recursive programming in it: The function MakeTriangle was what actually did something in the end. It made one of the little blue triangles we were counting. The function Sierpinski made the triangle shaped fractal. It is called with an Order parameter, and if the order is zero, then it calls MakeTriangle. If the order parameter is > 0, it just calls itself 3 times with an order decremented by 1. The function KochSide is responsible for jagged looking sides of the snowflake. It also takes an Order parameter; At order 0, it does nothing, but at higher orders it calls itself 4 times, and Sierpinski once, all with order decremented by 1. The function CombinedFractal calls Sierpinski once to fill in the largest fractal triangle, then calls KochSide 3 times to fill out the jagged edge pattern on all sides of the triangle. To solve the puzzle of counting the little triangles, the easiest way to do it was to modify MakeTriangle to simply count instead of actually making triangles. Then run the program, and it will give the answer: 10830. John Jacobsma simplified and re-wrote the program in Java. Without any of the geometry, this program shows just the recursive nature of the problem: package counttriangles; public class CountTriangles implements Runnable { public static void main(String[] args) { new CountTriangles().run(); } @Override public void run() { System.out.println(combined(6)); } int combined(int order) { return sierpinski(order) + 3 * koch(order); } int koch(int order) { if (order <= 0) return 0; return sierpinski(order - 1) + 4 * koch(order - 1); } int sierpinski(int order) { if (order <= 0) return 1; return 3 * sierpinski(order - 1); } } The problem can also be solved without delving into the programming, but by analyzing the pattern. Order 0 has just 1 triangle. Each additional order spits each triangle into 3, so it has 3 times more triangles than the previous. So, the triangle counts of Sierpinski triangles are 1, 3, 9, 27, 81, 243 and 729. Also note that the order of a Sierpinski triangle can be determined by counting the interior white triangles down the middle. Three white triangles down the middle indicates an order 3 Sierpinski triangle: Next, the Koch pattern can be analyzed. A level 2 Koch snowflake is shown here with the edges marked. The level pattern in Red is repeated 4 times by pattern in Green. Each additional level continues to multiply by 4. But the first Red pattern is performed only 3 times, for the 3 sides of the center triangle. So, the number of triangles that make up solid Koch snowflake is 1, 3, 12, 48, 192, 768, 3072. Since the fractal snowflake pattern is made of Sierpinski triangles instead of solid triangles, the pattern of the order of the Sierpinski triangles has to be determined. It can be observed that the central triangle is order 6, and each smaller triangle on the perimeter is seen to be 1 level smaller, down to level 0 triangles on the fringes: Now, the two numeric sequences can be combined and summed to determine the total number of triangles: Sierpinski Koch Total Triangles Triangles Triangles 1 3072 3072 3 768 2304 9 192 1728 27 48 1296 81 12 972 243 3 729 729 1 729 Sum 10830 Comments There are currently no comments, be the first to post one. Post a comment Name (required) Email (required) Enter the code shown above: Notify me of followup comments via e-mail | https://www.dmcinfo.com/latest-thinking/blog/id/8960/geek-challenge-results-fractal-snowflake | CC-MAIN-2021-43 | refinedweb | 652 | 50.67 |
In this post we are going to control a Servo Motor using a web browser with the help of Arduino and Wi-Fi module ESP8266. The ESP8266 will establish a connection between the servo and the web browser through the IP address and then by moving the Slider on the web page, the servo will move accordingly. Even by setting Port Forwarding in your router, you can control the Servo from anywhere in the world over the internet, we will explain that later in this tutorial.
In our previous projects, we have controlled the servo by using many other techniques like we have controlled the servo using Flex sensor, using Force sensor, using MATLAB etc. And we have also covered tutorials on interfacing of Servo with different Microcontrollers like with Arduino, Raspberry Pi, 8051, AVR etc. You can check all Servo related projects here.
Required Components:
The components used in this project are as follows
- Servo (sg90)
- Arduino Uno
- Wi-Fi module ESP8266
- Three 1K resistors
- Connecting wires
Circuit Diagram and Connections: 4 of the Arduino and the RX pin of the ESP8266 to the pin 5 of Arduino through the resistors.
ESP8266 Wi-Fi module gives your projects access to Wi-Fi or internet. It is a very cheap device and make your projects very powerful. It can communicate with any microcontroller and it is the most leading devices in the IOT platform. Learn more about using ESP8266 with Arduino here.
Then connect the Servo Motor with the Arduino. The connections of the servo motor with the Arduino are very easier. Connect the VCC and the ground pin of the servo motor to the 5V and the ground of the Arduino and the signal pin of the servo motor to the pin 9 of the Arduino.
How to run it:
To run it, you will have to make an HTML file that will open a web page. For that, you will have to copy below given HTML code (check downwards) and save it in a notepad. There should be ‘.html’ at the end of the file, means file must be saved with ‘.html’ extension. So, if you want to name the file as ‘servo’ then it should be as ‘servo.html’ so that it can be easily get opened in the web browser.
After this, you will have to place the jQuery file in the same folder where you have placed the html file. You can download the HTML file and jQuery from here, extract this zip file and use them directly. jQuery is the library of Java Script which has many JS functions which makes DOM manipulation (Document Object Model), event handling and use of Ajax easy-to-use.
Now open the html file in the web browser, it will look like this.
Now paste the Arduino code in the Arduino IDE and change the name of the Wi-Fi and the password with your Wi-Fi network name and password and upload the code. You will be given with an IP address in the Serial Monitor. Type this IP address in the box on web page. Now when you will move the slider, the Servo will move according to the Slider. So that is how you can control the Servo using Webpage.
HTML Code Explanation:
Here is the complete HTML code for this Web controlled Servo project, we will get through it line by line:
<!DOCTYPE html > <html> <head> <title>Web controlled Servo</title> <script src="jquery.js"></script> </head> <body> <h1> <b> Web Controlled Servo by circuitdigest.com </b> </h1> <h4> <b> Enter the IP address of esp8266 shown in the serial monitor below </b> </h4> <div style="margin: 0; width:500px; height:80px;"> <FORM NAME="form" ACTION="" METHOD="GET"> ESP8266 IP Address: <INPUT TYPE="text" NAME="inputbox" VALUE="192.168.0.9"> </FORM> </div> <h3> Scroll it to move servo 1 </h3> <input type="range" min="20" max="170" onmouseup="servo1(this.value)" /> </body> <script> $.ajaxSetup({timeout:1000}); function servo1(angle) { TextVar = form.inputbox.value; ArduinoVar = "http://" + TextVar + ":80"; $.get( ArduinoVar, { "sr1": angle }) ; {Connection: close}; } </script> </html>
The <!DOCTYPE html > tag will tell the web browser that which version of html we have used to write the html. This should be written at the top. Everything will be written after that.
The code written between the <html> </html> tags will be read by the browser. These are used to tell the web browser that the html code has started from here. The code written out of it will not be displayed on the webpage. The <head> </head> tags are used to define the title, links, jQuery and style. We have defined the title and the jQuery script in it. The data written in the <title></title> will be the name of the tab in the browser. In our code, we have named the tab as the “Web Controlled Servo”.
The <script></script> tags are used to include the jQuery. The jQuery is the JavaScript library and it greatly simplifies our code.
The body tags are used to define all the elements onto the webpage like textbox, range slider, button, text area etc. We can also define sizes for the elements. The h1, h2, h3, h4, h5 and h6 headings are used to write the data in different sizes. In our code, we have used the h1, h3 and h4 headings.
Then we have created a textbox for writing the IP address in it. It will match the IP address with the ESP8266 and will send the data at this IP address. After that, we created a slider (input type="range") that will send the value to the function named “servo1” from angle 20 to 170 for moving the slider.
function servo1(angle) { TextVar = form.inputbox.value; ArduinoVar = "http://" + TextVar + ":80"; $.get( ArduinoVar, { "sr1": angle }) ; {Connection: close}; }
Then the function will be executed and it will send the value to the Arduino to move the servo and will close the connections.
Arduino Code Explanation:
Complete Arduino Code for this Web Controlled Servo is given below in Code section. First of all we will include the Software Serial and the servo libraries. If you don’t have these libraries, then install it before uploading the code. Then define the pins where we have connected the ESP8266.The ‘DEBUG true’ will display the messages of the ESP8266 on the Serial Monitor. Then define the servo pin and declare a variable for servo.
#include <SoftwareSerial.h> #include <Servo.h> SoftwareSerial esp(4, 5); //set ESP8266 RX pin = 5, and TX pin = 4 #define DEBUG true //display ESP8266 messages on Serial Monitor #define servopin 9 //servo 1 on digital port 9 Servo ser; //servo 1
Then tell the Arduino that at which pin we have connected the servo and set it to max position. Then set the baud rate of serial monitor and the ESP8266 at ‘115200’.
ser.attach(servopin); ser.write(maxpos); ser.detach(); Serial.begin(115200); esp.begin(115200);
Below code will connect the ESP8266 to the Wi-Fi of your router which you have entered in the code and will tell you the IP address at which it will communicate with the webpage and will receive the data.
sendData("AT+RST\r\n", 2000, DEBUG); //reset module sendData("AT+CWMODE=1\r\n", 1000, DEBUG); //set station mode sendData("AT+CWJAP=\"Arsenal\",\"12345678\"\r\n", 2000, DEBUG); //connect wifi network while(!esp
In the void loop() function, ESP8266 will check that if the data is arrived or not. If the data is arrived then it will read this data and will show it on the serial monitor and also will move the servo according to this data.); }
Finally sendData function is used to send the commands to the ESP8266 and to check their response.
String sendData(String command, const int timeout, boolean debug) { String response = ""; esp.print(command); long int time = millis(); while ( (time + timeout) > millis()) { while (esp.available()) { char c = esp.read(); response += c; } } if (debug) { Serial.print(response); } return response; }
We have setup a local server to demonstrate its working, you can check the Video below. But to control the Servo from anywhere, you need to forward the port 80 (used for HTTP or internet) to your local or private IP address (192.168*) of you device. After port forwarding all the incoming connections will be forwarded to this local address and you can just open the given HTML file and enter the public IP address of your internet in the Textbox on webpage. You can forward the port by logging into your router (192.168.1.1) and find the option to setup the port forwarding.
#include <SoftwareSerial.h> //Including the software serial library
#include <Servo.h> //including the servo library
SoftwareSerial esp(4, 5);
#define DEBUG true //This will display the ESP8266 messages on Serial Monitor
#define servopin 9 //connect servo on pin 9
Servo ser; //variable for servo
int current_pos = 170;
int v = 10;
int minpos = 20;
int maxpos = 160;
void setup()
{
ser.attach(servopin);
ser.write(maxpos);
ser.detach();
Serial.begin(115200);
esp.begin(115200);
sendData("AT+RST\r\n", 2000, DEBUG); //This command will reset module
sendData("AT+CWMODE=1\r\n", 1000, DEBUG); //This will set the esp mode as station mode
sendData("AT+CWJAP=\"wifi-name\",\"wifi-password\"\r\n", 2000, DEBUG); //This will connect to wifi network
while(!esp.find("OK")) { //this will wait for connection
}
sendData("AT+CIFSR\r\n", 1000, DEBUG); //This will show IP address on the serial monitor
sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); //This will allow multiple connections
sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); //This will start the web server on port 80
}
void loop()
{);
}
delay(100);
//move servo to desired angle
if(command == "sr1") {
//limit input angle
if (value >= maxpos) {
value = maxpos;
}
if (value <= minpos) {
value = minpos;
}
ser.attach(servopin); //attach servo
while(current_pos != value) {
if (current_pos > value) {
current_pos -= 1;
ser.write(current_pos);
delay(100/v);
}
if (current_pos < value) {
current_pos += 1;
ser.write(current_pos);
delay(100/v);
}
}
ser.detach(); //dettach
}
}
}
}
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
esp.print(command);
long int time = millis();
while ( (time + timeout) > millis())
{
while (esp.available())
{
char c = esp.read();
response += c;
}
}
if (debug)
{
Serial.print(response);
}
return response;
}
Awesome
Thanks for such projects
Is it possible to control it from site which is on web server? fro example from justexample.com?
I have run this project, it works fine, but serial monitor shows lot of mixed garbage message along with normal message...also moving the slider to left or right some times ESP8266 responds, sometimes it does not, also on serial monitor many times sr1,20 or sr1,170 is displayed correctly and some times garbage is displayed,,,how can I get rid of this garbage....I tried various baud rates like 9600, 115200, 57600 for Serail.begin and/or esp.begin. Rx pin of ESP8266 is connected to three 1K resistors combination from Tx of Arduino, to adjust for 3.3 v expected at ESP8266 Rx. Can I connect Tx of Arduino directly to Rx of 8266. will it be safe ? will it remove garbage ?
the card is not receiving all the commands how can i solve this problem | https://circuitdigest.com/microcontroller-projects/iot-web-controlled-servo-motor | CC-MAIN-2018-17 | refinedweb | 1,874 | 63.9 |
. You’ll learn more in the video below.
If you like videos like this share it
Code from the Video
DRIVABLE.JAVA
/* Java doesn't allow you to inherit from more than one * class. So, what do you do when you want do you do * when you want to add additional functionality? * You create an interface. Interfaces are empty * classes. They provide all of the methods you must * use, but none of the code. */ // This is how you define an interface. They normally // have a name that is an adjective. Adjectives modify // nouns. Most objects have noun names public interface Drivable { // You can put fields in an interface, but understand // that their values are final and can't be changed double PI = 3.14159265; // All methods in an interface must be implemented // They are public and abstract by default // An abstract method must be defined by any class // that uses the interface int getWheels(); // You can't define a method as final and abstract // final means the method can't be changed and // abstract means it must be changed void setWheels(int numWheels); double getSpeed(); void setSpeed(double speed); }
CRASHABLE.JAVA
/* If you want to create a class in which every method * doesn't have to be implemented use abstract classes. */ // Create an abstract class with the abstract keyword public abstract class Crashable{ boolean carDrivable = true; public void youCrashed(){ this.carDrivable = false; } public abstract void setCarStrength(int carStrength); public abstract int getCarStrength(); }
VEHICLE.JAVA
/* You define that you want a class to use an interface * with the implements keyword. This class must create * a method for each method defined in Drivable * You can implement more than 1 interface like this * public class Vehicle implements Drivable, Crashable */ // You make a class part of an abstract class by using //the extends keyword public class Vehicle extends Crashable implements Drivable { int numOfWheels = 2; double theSpeed = 0; int carStrength = 0; // All methods must be as visible as those in the // interface. If they are public in the interface // they must be public in the subclass public int getWheels(){ return this.numOfWheels; } public void setWheels(int numWheels){ this.numOfWheels = numWheels; } public double getSpeed(){ return this.theSpeed; } public void setSpeed(double speed){ this.theSpeed = speed; } public Vehicle(int wheels, double speed){ this.numOfWheels = wheels; this.theSpeed = speed; } public void setCarStrength(int carStrength){ this.carStrength = carStrength; } public int getCarStrength(){ return this.carStrength; } }
LESSONFIFTEEN.JAVA
public class LessonFifteen { public static void main(String[] args){ Vehicle car = new Vehicle(4, 100.0); // Using methods from the interface Drivable System.out.println("Cars Max Speed: "+car.getSpeed()); System.out.println("Cars Number of Wheels: "+car.getWheels()); // Using methods from abstract method Crashable car.setCarStrength(10); System.out.println("Car Strength: "+car.getCarStrength()); } }
Derek, thanks again for this video, i am just curious how u completed ur Computer programming, i mean are u a self taught programmer if so how much time it took u to reach the level ur now, i know it is kind of personal question, but do answer plz thank you.
I’m mainly book taught, but since I started in the 80s that was the only option. I think anyone can get very good in this day if they focus on object oriented design and uml. Then they can easily learn any oop language like java and c++.
Feel free to ask questions
When r you going to upload videos on android development or game development using JAVA
Very very soon 🙂
You are a good teacher. I am learning at wonderful pace 🙂
Thank you very much 🙂
You are a great teacher and inspiration. I wish some day I would be like you, sharing knowledge to world free of cost
Thank you very much for the kind message 🙂 I do my best. I’m glad you are finding the tutorials useful
I am trying to get this to work with the interface and I get this error. What am I doing wrong?
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The type Drivable cannot be a superinterface of Vehicle; a superinterface must be an interface
at Vehicle.(Vehicle.java:2)
at LessonFifteen.main(LessonFifteen.java:6)
Hello,
The topic of interfaces really seems to bog me down, I can’t seem to get my head to click around it. To me, it seems like you are implementing the interface, which defines certain methods which must be used in your class. But, you are also defining them in the class which implements them. Why write the same code twice? Is it simply to make sure that a sort of ‘checklist’ is fulfilled or am I looking at this from the wrong angle?
Thanks for great videos
Hello Jake,
Take a look at the first 2 videos in my design patterns video tutorial. I bet they will make interfaces make more sense.
thanks a million for your tutorials and code!!!
Can you recommend or say which book you read and think they are good enough?
thanks
You’re very welcome 🙂 I like the Head First books. They are fun to read and very detailed.
It is very help full video. Thank you very much.
You’re very welcome 🙂
which book should i use to learn java object oriented programming.
Everyone seems to like the Head First Java book. I made a very detailed tutorial on Object Oriented Design that you may find useful as well.
Hey what is the difference between using the interface and the abstract class I am not sure, seems like you can use either or. Can you give me an example in which you’d use one over the other sorry to be a bother.
With an interface every method must be abstract meaning it can’t do anything at all except force the class that implements it to create that method.
An abstract class can have non-abstract methods in it that contain code. That is the main difference. Over time you’ll find you rarely use abstract classes, but they are useful when you need them.
Hi Derek, I really didn’t understand what you did with Cat tempCat = (Cat) randAnimal; is this a new class? could you please share a link where it is explained thoroughly?
The Cat extends Animal. That means it can be passed as an Animal and then converted into its true form being a Cat. Watch part 1 of my design patterns tutorial. It explains this in another way that may help.
Your tutorials are really helpful !
Thank you 🙂
thanks Derek, all your tutorials are good. i’ve learned a lot.
Thank you 🙂 You’re very welcome
Hi Derek,
The best explanation of interfaces I have seen anywhere. You have made many of these concepts that are often explained in very confusing ways, very easy to understand.
Thank you 🙂 I’m happy I could help
Hello Derek. Thanks for the tutorials. I am learning a lot. 🙂
I want to ask you if we can put two vehicles classes inside the lessonfifteen.java class
For example can i create another class-> Vehicle carTwo = new Vehicle(5, 200.0); inside the class and print out the output respectively?
Thanks
Yes you can do that | http://www.newthinktank.com/2012/02/java-video-tutorial-15/ | CC-MAIN-2016-50 | refinedweb | 1,196 | 74.59 |
Part 8: Deferred Poetry
This continues the introduction started here. You can find an index to the entire series here.
Client 4.0
Now that we have know something about deferreds, we can rewrite our Twisted poetry client to use them. You can find client 4.0 in twisted-client-4/get-poetry.py.
Our
get_poetry function no longer needs
callback or
errback arguments. Instead, it returns a new deferred to which the user may attach callbacks and errbacks as needed.
def get_poetry(host, port): """ Download a poem from the given host and port. This function returns a Deferred which will be fired with the complete text of the poem or a Failure if the poem could not be downloaded. """ d = defer.Deferred() from twisted.internet import reactor factory = PoetryClientFactory(d) reactor.connectTCP(host, port, factory) return d
Our factory object is initialized with a deferred instead of a callback/errback pair. Once we have the poem, or we find out we couldn’t connect to the server, the deferred is fired with either a poem or a failure:
class PoetryClientFactory(ClientFactory): protocol = PoetryProtocol def __init__(self, deferred): self.deferred = deferred def poem_finished(self, poem): if self.deferred is not None: d, self.deferred = self.deferred, None d.callback(poem) def clientConnectionFailed(self, connector, reason): if self.deferred is not None: d, self.deferred = self.deferred, None d.errback(reason)
Notice the way we release our reference to the deferred after it is fired. This is a pattern found in several places in the Twisted source code and helps to ensure we do not fire the same deferred twice. It makes life a little easier for the Python garbage collector, too.
Once again, there is no need to change the
PoetryProtocol, it’s just fine as is. All that remains is to update the
poetry_main function:
def poetry_main(): addresses = parse_args() from twisted.internet import reactor poems = [] errors = [] def got_poem(poem): poems.append(poem) def poem_failed(err): print >>sys.stderr, 'Poem failed:', err errors.append(err) def poem_done(_): if len(poems) + len(errors) == len(addresses): reactor.stop() for address in addresses: host, port = address d = get_poetry(host, port) d.addCallbacks(got_poem, poem_failed) d.addBoth(poem_done) reactor.run() for poem in poems: print poem
Notice how we take advantage of the chaining capabilities of the deferred to refactor the
poem_done invocation out of our primary callback and errback.
Because deferreds are used so much in Twisted code, it’s common practice to use the single-letter local variable
d to hold the deferred you are currently working on. For longer term storage, like object attributes, the name “
deferred” is often used.
Discussion
With our new client the asynchronous version of
get_poetry accepts the same information as our synchronous version, just the address of the poetry server. The synchronous version returns a poem, while the asynchronous version returns a deferred. Returning a deferred is typical of the asynchronous APIs in Twisted and programs written with Twisted, and this points to another way of conceptualizing deferreds:
A
Deferredobject represents an “asynchronous result” or a “result that has not yet come”.
We can contrast these two styles of programming in Figure 13:
By returning a deferred, an asynchronous API is giving this message to the user:
I’m an asynchronous function. Whatever you want me to do might not be done yet. But when it is done, I’ll fire the callback chain of this deferred with the result. On the other hand, if something goes wrong, I’ll fire the errback chain of this deferred instead.
Of course, that function itself won’t literally fire the deferred, it has already returned. Rather, the function has set in motion a chain of events that will eventually result in the deferred being fired.
So deferreds are a way of “time-shifting” the results of functions to accommodate the needs of the asynchronous model. And a deferred returned by a function is a notice that the function is asynchronous, the embodiment of the future result, and a promise that the result will be delivered.
It is possible for a synchronous function to return a deferred, so technically a deferred return value means the function is potentially asynchronous. We’ll see examples of synchronous functions returning deferreds in future Parts.
Because the behavior of deferreds is well-defined and well-known (to folks with some experience programming with Twisted), by returning deferreds from your own APIs you are making it easier for other Twisted programmers to understand and use your code. Without deferreds, each Twisted program, or even each internal Twisted component, might have its own unique method for managing callbacks that you would have to learn in order to use it.
When You’re Using Deferreds, You’re Still Using Callbacks, and They’re Still Invoked by the Reactor
When first learning Twisted, it is a common mistake to attribute more functionality to deferreds than they actually have. Specifically, it is often assumed that adding a function to a deferred’s chain automatically makes that function asynchronous. This might lead you to think you could use, say,
os.system with Twisted by adding it to a deferred with
addCallback.
I think this mistake is caused by trying to learn Twisted without first learning the asynchronous model. Since typical Twisted code uses lots of deferreds and only occasionally refers to the reactor, it can appear that deferreds are doing all the work. If you have read this introduction from the beginning, it should be clear this is far from the case. Although Twisted is composed of many parts that work together, the primary responsibility for implementing the asynchronous model falls to the reactor. Deferreds are a useful abstraction, but we wrote several versions of our Twisted client without using them in any way.
Let’s look at a stack trace at the point when our first callback is invoked. Run the example program in twisted-client-4/get-poetry-stack.py with the address of a running poetry server. You should get some output like this:
File "twisted-client-4/get-poetry-stack.py", line 129, in poetry_main() File "twisted-client-4/get-poetry-stack.py", line 122, in poetry_main reactor.run() ... # some more Twisted function calls protocol.connectionLost(reason) File "twisted-client-4/get-poetry-stack.py", line 59, in connectionLost self.poemReceived(self.poem) File "twisted-client-4/get-poetry-stack.py", line 62, in poemReceived self.factory.poem_finished(poem) File "twisted-client-4/get-poetry-stack.py", line 75, in poem_finished d.callback(poem) # here's where we fire the deferred ... # some more methods on Deferreds File "twisted-client-4/get-poetry-stack.py", line 105, in got_poem traceback.print_stack()
That’s pretty similar to the stack trace we created for client 2.0. We can visualize the latest trace in Figure 14:
Again, this is similar to our previous Twisted clients, though the visual representation is starting to become vaguely disturbing. We probably won’t be showing any more of these, for the sake of the children. One wrinkle not reflected in the figure: the callback chain above doesn’t return control to the reactor until the second callback in the deferred (
poem_done) is invoked, which happens right after the first callback (
got_poem) returns.
There’s one more difference with our new stack trace. The line separating “Twisted code” from “our code” is a little fuzzier, since the methods on deferreds are really Twisted code. This interleaving of Twisted and user code in a callback chain is common in larger Twisted programs which make extensive use of other Twisted abstractions.
By using a deferred we’ve added a few more steps in the callback chain that starts in the Twisted reactor, but we haven’t changed the fundamental mechanics of the asynchronous model. Recall these facts about callback programming:
- Only one callback runs at a time.
- When the reactor is running our callbacks are not.
- And vice-versa.
- If our callback blocks then the whole program blocks.
Attaching a callback to a deferred doesn’t change these facts in any way. In particular, a callback that blocks will still block if it’s attached to a deferred. So that deferred will block when it is fired (
d.callback), and thus Twisted will block. And we conclude:
Deferreds are a solution (a particular one invented by the Twisted developers) to the problem of managing callbacks. They are neither a way of avoiding callbacks nor a way to turn blocking callbacks into non-blocking callbacks.
We can confirm the last point by constructing a deferred with a blocking callback. Consider the example code in twisted-deferred/defer-block.py. The second callback blocks using the
time.sleep function. If you run that script and examine the order of the
Summary
By returning a
Deferred, a function tells the user “I’m asynchronous” and provides a mechanism (add your callbacks and errbacks here!) to obtain the asynchronous result when it arrives. Deferreds are used extensively throughout the Twisted codebase and as you explore Twisted’s APIs you are bound to keep encountering them. So it will pay to become familiar with deferreds and comfortable in their use.
Client 4.0 is the first version of our Twisted poetry client that’s truly written in the “Twisted style”, using a deferred as the return value of an asynchronous function call. There are a few more Twisted APIs we could use to make it a little cleaner, but I think it represents a pretty good example of how simple Twisted programs are written, at least on the client side. Eventually we’ll re-write our poetry server using Twisted, too.
But we’re not quite finished with deferreds. For a relatively short piece of code, the
Deferred class provides a surprising number of features. We’ll talk about some more of those features, and their motivation, in Part 9.
Suggested Exercises
- Update client 4.0 to timeout if the poem isn’t received after a given period of time. Fire the deferred’s errback with a custom exception in that case. Don’t forget to close the connection when you do.
- Update client 4.0 to print out the appropriate server address when a poem download fails, so the user can tell which server is the culprit. Don’t forget you can add extra positional- and keyword-arguments when you attach callbacks and errbacks. | http://krondo.com/2009/10/ | CC-MAIN-2017-09 | refinedweb | 1,736 | 56.86 |
There are some things about the .NET threading classes that I have not
appreciated much. The first shock I got was when I realized that the
System::Threading::Thread class was a sealed class.
public __gc __sealed class.
As if that was not bad enough, my next shock was when I realized that the thread proc delegate would not take any parameters.
public __gc __delegate void ThreadStart();.
I might have missed out on something. Two likely candidates are
AllocateDataSlot and
AllocateNamedDataSlot. I haven't really understood their
exact purpose. But I guess I'll have to search deeper into the
documentation..
#include "stdafx.h" #using <mscorlib.dll> using namespace System; using namespace System::Threading; __gc class CalcThread { public: CalcThread(int num,String *s); private: void ThreadFunc(); Thread *t; int x; String *s1; }; int wmain(void) { CalcThread *c1,*c2,*c3; Console::WriteLine("Starting thread c1"); c1=new CalcThread(77,"c1"); Console::WriteLine("Starting thread c2"); c2=new CalcThread(66,"c2"); Console::WriteLine("Starting thread c3"); c3=new CalcThread(99,"c3"); return 0; } CalcThread::CalcThread(int num, String *s) { x=num; s1=s; t=new Thread(new ThreadStart(this,&CalcThread::ThreadFunc)); t->Start(); } void CalcThread::ThreadFunc() { Console::WriteLine("Thread {0} has initialized",s1); for(int i=0;i<5;i++) { x^=i; Console::WriteLine("Thread {0} Intermediate Result : {1}", s1,__box(x)); Thread::Sleep(500); } Console::WriteLine("Thread {0} finished with result {1}", s1,__box(x)); }
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/threads/mcppthreads01.aspx | crawl-002 | refinedweb | 241 | 55.95 |
Production Postmortem: A Behind-the-Scenes Look at Data Corruption
Production Postmortem: A Behind-the-Scenes Look at Data Corruption
It seemed that the only way this issue could have occurred was from a dev banging his head on a keyboard. But that's not what happened in this data corruption terms of severity, there are very few things that we take more seriously than data integrity. In fact, the only thing that pops to mind as a higher priority is security issues. A user reported an error when using a pre-release 4.0 database that certainly looked like data corruption, so we were very concerned when we go the report, and were quite happy about the actual error. If this sounds, it helps deserves some explanation. We don’t assume that our software is perfect, so we took steps in advance. The hashing the data and validating it is one such step, but another is built, upfront, the recovery tools for when the inevitable happens. That meant that the way we lay out the data on disk was designed, upfront and deliberately, to allow us to recover the data in the case of corruption.
Admittedly, I was mostly thinking about the corruption of the data as a result of a physical failure, but the way we lay out the data on disk also protects became.
At one point, we got something that could reliably generate an error — it was on the 213th write to the system. It didn’t matter what write, but the 213th write would led to less head banging before the problem could be reproduced. The problem was that we always caught it too late; we kept going backward in the code, each time really excited that we would:
public class UserStorage { private int _usersId; private User[] _users = new User[16]; // imagine that we have enough storage private Dictionary<string, int> _byName = new Dictionary<string, int>(); public int CreateUser(string name) { var id = ++_usersId; var user = new User(name, _usersId); _users[_usersId] = user; _byName.Add(name, user); return id; } public void RemoveUser(int id) { var user = _users[id]; _users[id] = null; _byName.Remove(user.Name); } public User GetUser(int id) { return _users[id]; } public string GetUserEmail(string name) { if(_byName.TryGetValue(name, out var id)) return _users[id].Name; return null; } }
There isn’t anything wrong with the code here at first glance, but look at the Remove method, and now at this code that uses the storage:
var id = storage.CreateUser("something"); var user = storage.Get(id); user.Name = "something else"; // mutate the instance that the storage.Remove(id); storage.GetUserEmail("something"); // NRE thrown here:
public void RemoveUser(int id) { var user = _users[id]; if(user == null) return; // delete twice? if(_byName.TryGetValue(user.Name, out var userFromIndex) == false || userfromIndex != user) throw new DataCorruption(); _byName.Remove(user.Name); } three that, a detailed analysis of the data in parallel to verify that we could yours — the a lot of time on figuring out what the problem was and the fix was two lines of code. I wrote this post independently of this investigation, but it hit the nail straight }} | https://dzone.com/articles/production-postmortem-data-corruption-a-view-from | CC-MAIN-2018-43 | refinedweb | 524 | 59.94 |
Hello everyone
I would like to know if there is a way Dynamo can create a triangle from the lenght of its sides. If I have in data three numbers: 3,4,5, for example, can I draw a pythagorean triangle shape in a Dynamo model?
I’ve looking at this Python forum and an user asked how to create a triangle:
from turtle import color, begin_fill, forward, left, end_fill, done from math import acos, degrees def triangle_exists(a, b, c): """Return True iff there exists a triangle with sides a, b, c.""" return a + b > c and b + c > a and c + a > b def triangle_angle(a, b, c): """Return the angle (in degrees) opposite the side of length a in the triangle with sides a, b, c.""" # See return degrees(acos((b ** 2 + c ** 2 - a ** 2) / (2.0 * b * c))) def draw_triangle(a, b, c): """Draw a triangle with sides of lengths a, b, and c.""" assert(triangle_exists(a, b, c)) color('black', 'yellow') begin_fill() forward(c) left(180 - triangle_angle(b, c, a)) forward(a) left(180 - triangle_angle(c, a, b)) forward(b) end_fill() done() >>> draw_triangle(400, 350, 200)
This is the code presented in the page I linked.
I would like to know if Dynamo can create geometries for triangles from code or if there exist nodes that help to do this.
Thanks in advance | https://forum.dynamobim.com/t/how-can-i-create-a-triangle-shape-from-the-lenght-of-its-sides/57474 | CC-MAIN-2021-10 | refinedweb | 229 | 64.85 |
First,
But his metaphor breaks down a little, because the second stack isn't really a stack:
A considerable minority uses a stack like this. It’s important that the Prime Stack isn’t exact: you might not use Cucumber at all, for example, or maybe you don’t have a service layer.
On the (private, but cheap) Ruby Rogues "Parley" email list, I came up with an alternate interpretation:
I think the problem is the concept of a stack.
Everybody builds Rails apps their own way. There's a 37Signals (or
omakase) stack, a Thunderbolt stack, a Hashrocket stack, and many
other stacks, and in most cases the "stack" is not a fixed machine but
a fluctuating ecosystem. (I'm not sure if that's the right metaphor
either, but it'll work until I get an idea for a better one.) You
experiment with different gems on different projects, and some of them
you use more often than others.
There's an approved set of choices which represents Official Rails™,
but this doesn't have much to do with any actual consensus among Rails
developers. A lot of people depart from the canonical path a little
bit, for many different reasons. But Rails developers know the value
of convention over configuration, so we all try to develop
*conventions* for our deviations from the canonical path.
For example, "we use DataMapper on every project" becomes a local
convention at Company XYZ. But prior to Rails 3, you maybe had to
write a shell script or something to strip out ActiveRecord and swap
in DataMapper, so if you're doing this, and you do a lot of
consulting, you might start to accrue a little library of post-
installation scripts.
If this continues for a long time, and your company develops a
sufficiently sophisticated set of consistent deviations from Rails
canon, it's almost like you have an alternate version of Rails.
In my opinion the alternative "stack" is really an intersection of
many alternate versions of Rails. Within the context of companies
(i.e., semi-private communities), we've created a huge range of custom
Rails permutations, and people share a vague consensus about certain
consistent ways these individual branches differ from the official,
canonical stem.
(Trying to think of the right metaphor but nothing springs to mind.)
Anyway, I think this is a good thing, but I think the Rails docs would
be better if they acknowledged this process, and its artifacts, and if
we had ways to sharpen the focus and turn the vague consensus into
something more specific.
But I was wrong. Rails has supported this use case for many years, and the docs for the upcoming Rails 4 release describe it in detail.
Rails's creator David Heinemeier Hansson has a Twitter feed. The bad news: I find that feed kind of noisy. The good news: I found a good tweet in it today, and I think it deserves some attention.
Rails application templates provide a simple DSL for creating local, custom Rails "defaults." We've had this feature since Rails 2.
Caveat: in some cases, the DSL gets a little silly:
That's a custom command, in this DSL, for running arbitrary git commands. I might put any git commands in a shell script instead, but even if you opted for a Unix-centric approach, you can still trigger shell scripts (or indeed any arbitrary Unix software) from within a Rails app template via the
runcommand, which allows you to execute arbitrary Unix commands.
Templates operate as command-line arguments to
rails new, either as filenames or URLs, e.g.:
$ rails new my_application_name -m ~/my_company_defaults.rb
$ rails new my_application_name -m
Which would be somewhat equivalent to running this manually:
rails new my_application_name && ruby ~/bin/my_company_rails_customizer.rb
...but with a much nicer syntax.
Irony time: the use case for which Hansson recommends using Rails application templates is not actually a use case which the Rails app templates DSL supports.
Many of the least popular changes to Rails have revolved around very small changes to the standard Gemfile -- typically a matter of removing a few lines when you first generate your app -- but the Rails app templates DSL does not have a
removecommand. It does have a
gemcommand for adding gems, but if you're removing them, you'll be using custom code in either Ruby or some other language.
However, this is easy in Ruby, and extremely easy in bash.
Say you've got some Rails
Gemfilewhich includes both an awesome gem and a lame one:
[01-24 10:55] ~/dev/example_project
↪ cat Gemfile
gem 'awesome'
gem 'lame'
Removing the lame gem is a one-liner in bash:
[01-24 10:55] ~/dev/example_project
↪ grep -v "lame" Gemfile > Gemfile.new && mv Gemfile.new Gemfile
Problem solved.
[01-24 10:55] ~/dev/example_project
↪ cat Gemfile
gem 'awesome'
With the
runcommand, that is of course also a one-liner in a Rails application template:
run "grep -v 'lame' Gemfile > Gemfile.new && mv Gemfile.new Gemfile"
Admittedly, it's a long line, and you have to be decent at Unix to make any sense of it, but it's still better than doing it by hand or arguing about it on the Internet. By the way, if you find a cleaner way to do it in bash, please gist me a solution (
@gilesgoatboyon Twitter) as I'm no bash wizard. I hope it's obvious you can wrap that in a method:
def no_fugu_please(toxin, dish)
unix = "grep -v '#{toxin}' #{dish} > #{dish}.new && " +
"mv #{dish}.new #{dish}"
run unix
end
Now you have a usable
remove:
no_fugu_please("some_lame_gem", "Gemfile")
no_fugu_please("/bin", ".gitignore")
If you don't want to litter your code with obscure sushi jokes, you could even just use
removefor your method name:
remove("some_lame_gem", "Gemfile")
remove("/bin", ".gitignore")
It's important to realize, however, that this does not solve the fundamental problem, on its own, of Rails having two "default stacks." The only way for the community to solve that problem is to both use Rails app templates and share them on GitHub.
Apart from anything else, if you can count the number of Rails app templates which throw away one gem and replace it with another, you now have an objective metric for what techniques the Rails community favors at any given time, as well as a subjective metric ("who uses what") for the credibility of individual gems and tweaks.
So please, use Rails application templates, and share them on GitHub.
Update: improved Unix-fu from Anthony Moralez and more from a Zander.
Also a GNU sed version and old generator web sites. | https://gilesbowkett.blogspot.com/2013/01/we-can-solve-multiple-default-stacks.html | CC-MAIN-2017-39 | refinedweb | 1,108 | 59.43 |
(defmacro backwards [form] (reverse form)) (backwards (" backwards" " am" "I" str)) ; => "I am backwards".
Macros allow you to transform arbitrary expressions into valid Clojure, so you can extend the language itself to fit your needs. And you don’t even have to be a wizened old dude or lady in a robe to use them!
To get just a sip of this power, consider this trivial macro:
The
backwards macro allows Clojure to successfully evaluate the expression
(" backwards" " am" "I" str), even though it doesn’t follow Clojure’s built-in syntax rules, which require an expression’s operand to appear first (not to mention the rule that an expression not be written in reverse order). Without
backwards, the expression would fail harder than millennia of alchemists ironically spending their entire lives pursuing an impossible means of achieving immortality. With
backwards, you’ve created your own syntax! You’ve extended Clojure so you can write code however you please! Better than turning lead into gold, I tell you!
This chapter gives you the conceptual foundation you need to go mad with power writing your own macros. It explains the elements of Clojure’s evaluation model: the reader, the evaluator, and the macro expander. It’s like the periodic table of Clojure elements. Think of how the periodic table reveals the properties of atoms: elements in the same column behave similarly because they have the same nuclear charge. Without the periodic table and its underlying theory, we’d be in the same position as the alchemists of yore, mixing stuff together randomly to see what blows up. But with a deeper understanding of the elements, you can see why stuff blows up and learn how to blow stuff up on purpose.
An Overview of Clojure’s Evaluation Model
Clojure (like all Lisps) has an evaluation model that differs from most other languages: it has a two-phase system where it reads textual source code, producing Clojure data structures. These data structures are then evaluated: Clojure traverses the data structures and performs actions like function application or var lookup based on the type of the data structure. For example, when Clojure reads the text
(+ 1 2), the result is a list data structure whose first element is a
+ symbol, followed by the numbers 1 and 2. This data structure is passed to Clojure’s evaluator, which looks up the function corresponding to
+ and applies that function to 1 and 2.
Languages that have this relationship between source code, data, and evaluation are called homoiconic. (Incidentally, if you say homoiconic in front of your bathroom mirror three times with the lights out, the ghost of John McCarthy appears and hands you a parenthesis.) Homoiconic languages empower you to reason about your code as a set of data structures that you can manipulate programmatically. To put this into context, let’s take a jaunt through the land of compilation.
Programming languages require a compiler or interpreter for translating the code you write, which consists of Unicode characters, into something else: machine instructions, code in another programming language, whatever. During this process, the compiler constructs an abstract syntax tree (AST), which is a data structure that represents your program. You can think of the AST as the input to the evaluator, which you can think of as a function that traverses the tree to produce the machine code or whatever as its output.
So far this sounds a lot like what I described for Clojure. However, in most languages the AST’s data structure is inaccessible within the programming language; the programming language space and the compiler space are forever separated, and never the twain shall meet. Figure 7-1 shows how you might visualize the compilation process for an expression in a non-Lisp programming language.
But Clojure is different, because Clojure is a Lisp and Lisps are hotter than a stolen tamale. Instead of evaluating an AST that’s represented as some inaccessible internal data structure, Lisps evaluate native data structures. Clojure still evaluates tree structures, but the trees are structured using Clojure lists and the nodes are Clojure values.
Lists are ideal for constructing tree structures. The first element of a list is treated as the root, and each subsequent element is treated as a branch. To create a nested tree, you can just use nested lists, as shown in Figure 7-2.
First, Clojure’s reader converts the text
(+ 1 (* 6 7)) into a nested list. (You’ll learn more about the reader in the next section.) Then, Clojure’s evaluator takes that data as input and produces a result. (It also compiles Java Virtual Machine ( JVM) bytecode, which you’ll learn about in Chapter 12. For now, we’ll just focus on the evaluation model on a conceptual level.)
With this in mind, Figure 7-3 shows what Clojure’s evaluation process looks like.
S-Expressions
In your Lisp adventures, you’ll come across resources that explain that Lisps evaluate s-expressions. I avoid that term here because it’s ambiguous: you’ll see it used to refer to both the actual data object that gets evaluated and the source code that represents that data. Using the same term for two different components of Lisp evaluation (code and data) obscures what’s important: your text represents native data structures, and Lisps evaluate native data structures, which is unique and awesome. For a great treatment of s-expressions, check out.
However, the evaluator doesn’t actually care where its input comes from; it doesn’t have to come from the reader. As a result, you can send your program’s data structures directly to the Clojure evaluator with
eval. Behold!
(def addition-list (list + 1 2)) (eval addition-list) ; => 3
That’s right, baby! Your program just evaluated a Clojure list. You’ll read all about Clojure’s evaluation rules soon, but briefly, this is what happened: when Clojure evaluated the list, it looked up the list that
addition-list refers to; then it looked up the function corresponding to the
+ symbol; and then it called that function with
1 and
2 as arguments, returning
3. The data structures of your running program and those of the evaluator live in the same space, and the upshot is that you can use the full power of Clojure and all the code you’ve written to construct data structures for evaluation:
(eval (concat addition-list [10])) ; => 13 (eval (list 'def 'lucky-number (concat addition-list [10]))) ; => #'user/lucky-number lucky-number ; => 13
Figure 7-4 shows the lists you sent to the evaluator in these two examples.
Your program can talk directly to its own evaluator, using its own functions and data to modify itself as it runs! Are you going mad with power yet? I hope so! Hold on to some of your sanity, though, because there’s still more to learn.
So Clojure is homoiconic: it represents abstract syntax trees using lists, and you write textual representations of lists when you write Clojure code. Because the code you write represents data structures that you’re used to manipulating and the evaluator consumes those data structures, it’s easy to reason about how to programmatically modify your program.
Macros are what allow you to perform those manipulations easily. The rest of this chapter covers Clojure’s reader and evaluation rules in detail to give you a precise understanding of how macros work.
The Reader
The reader converts the textual source code you save in a file or enter in the REPL into Clojure data structures. It’s like a translator between the human world of Unicode characters and Clojure’s world of lists, vectors, maps, symbols, and other data structures. In this section, you’ll interact directly with the reader and learn how a handy feature, the reader macro, lets you write code more succinctly.
Reading
To understand reading, let’s first take a close look at how Clojure handles the text you type in the REPL. First, the REPL prompts you for text:
user=>
Then you enter a bit of text. Maybe something like this:
user=> (str "To understand what recursion is," " you must first understand recursion.")
That text is really just a sequence of Unicode characters, but it’s meant to represent a combination of Clojure data structures. This textual representation of data structures is called a reader form. In this example, the form represents a list data structure that contains three more forms: the
str symbol and two strings.
Once you type those characters into the prompt and press enter, that text goes to the reader (remember REPL stands for read-eval-print-loop). Clojure reads the stream of characters and internally produces the corresponding data structures. It then evaluates the data structures and prints the textual representation of the result:
"To understand what recursion is, you must first understand recursion."
Reading and evaluation are discrete processes that you can perform independently. One way to interact with the reader directly is by using the
read-string function.
read-string takes a string as an argument and processes it using Clojure’s reader, returning a data structure:
(read-string "(+ 1 2)") ; => (+ 1 2) (list? (read-string "(+ 1 2)")) ; => true (conj (read-string "(+ 1 2)") :zagglewag) ; => (:zagglewag + 1 2)
In the first example,
read-string reads the string representation of a list containing a plus symbol and the numbers 1 and 2. The return value is an actual list, as proven by the second example. The last example uses
conj to prepend a keyword to the list. The takeaway is that reading and evaluating are independent of each other. You can read text without evaluating it, and you can pass the result to other functions. You can also evaluate the result, if you want:
(eval (read-string "(+ 1 2)")) ; => 3
In all the examples so far, there’s been a one-to-one relationship between the reader form and the corresponding data structures. Here are more examples of simple reader forms that directly map to the data structures they represent:
- () A list reader form
- str A symbol reader form
- [1 2] A vector reader form containing two number reader forms
- {:sound "hoot"} A map reader form with a keyword reader form and string reader form
However, the reader can employ more complex behavior when converting text to data structures. For example, remember anonymous functions?
(#(+ 1 %) 3) ; => 4
Well, try this out:
(read-string "#(+ 1 %)") ; => (fn* [p1__423#] (+ 1 p1__423#))
Whoa! This is not the one-to-one mapping that we’re used to. Reading
#(+ 1 %) somehow resulted in a list consisting of the
fn* symbol, a vector containing a symbol, and a list containing three elements. What just happened?
Reader Macros
I’ll answer my own question: the reader used a reader macro to transform
#(+ 1 %). Reader macros are sets of rules for transforming text into data structures. They often allow you to represent data structures in more compact ways because they take an abbreviated reader form and expand it into a full form. They’re designated by macro characters, like
' (the single quote),
#, and
@. They’re also completely different from the macros we’ll get to later. So as not to get the two confused, I’ll always refer to reader macros using the full term reader macros.
For example, you can see how the quote reader macro expands the single quote character here:
(read-string "'(a b c)") ; => (quote (a b c))
When the reader encounters the single quote, it expands it to a list whose first member is the symbol
quote and whose second member is the data structure that followed the single quote. The
deref reader macro works similarly for the
@ character:
(read-string "@var") ; => (clojure.core/deref var)
Reader macros can also do crazy stuff like cause text to be ignored. The semicolon designates the single-line comment reader macro:
(read-string "; ignore!\n(+ 1 2)") ; => (+ 1 2)
And that’s the reader! Your humble companion, toiling away at transforming text into data structures. Now let’s look at how Clojure evaluates those data structures.
The Evaluator
You can think of Clojure’s evaluator as a function that takes a data structure as an argument, processes the data structure using rules corresponding to the data structure’s type, and returns a result. To evaluate a symbol, Clojure looks up what the symbol refers to. To evaluate a list, Clojure looks at the first element of the list and calls a function, macro, or special form. Any other values (including strings, numbers, and keywords) simply evaluate to themselves.
For example, let’s say you’ve typed
(+ 1 2) in the REPL. Figure 7-5 shows a diagram of the data structure that gets sent to the evaluator.
Because it’s a list, the evaluator starts by evaluating the first element in the list. The first element is the plus symbol, and the evaluator resolves that by returning the corresponding function. Because the first element in the list is a function, the evaluator evaluates each of the operands. The operands 1 and 2 evaluate to themselves because they’re not lists or symbols. Then the evaluator calls the addition function with 1 and 2 as the operands, and returns the result.
The rest of this section explains the evaluator’s rules for each kind of data structure more fully. To show how the evaluator works, we’ll just run each example in the REPL. Keep in mind that the REPL first reads your text to get a data structure, then sends that data structure to the evaluator, and then prints the result as text.
Data
I write about how Clojure evaluates data structures in this chapter, but that’s imprecise. Technically, data structure refers to some kind of collection, like a linked list or b-tree, or whatever, but I also use the term to refer to scalar (singular, noncollection) values like symbols and numbers. I considered using the term data objects but didn’t want to imply object-oriented programming, or using just data but didn’t want to confuse that with data as a concept. So, data structure it is, and if you find this offensive, I will give you a thousand apologies, thoughtfully organized in a Van Emde Boas tree.
These Things Evaluate to Themselves
Whenever Clojure evaluates data structures that aren’t a list or symbol, the result is the data structure itself:
true ; => true false ; => false {} ; => {} :huzzah ; => :huzzah
Empty lists evaluate to themselves, too:
() ; => ()
Symbols
One of your fundamental tasks as a programmer is creating abstractions by associating names with values. You learned how to do this in Chapter 3 by using
def,
let, and function definitions. Clojure uses symbols to name functions, macros, data, and anything else you can use, and evaluates them by resolving them. To resolve a symbol, Clojure traverses any bindings you’ve created and then looks up the symbol’s entry in a namespace mapping, which you learned about in Chapter 6. Ultimately, a symbol resolves to either a value or a special form—a built-in Clojure operator that provides fundamental behavior.
In general, Clojure resolves a symbol by:
- Looking up whether the symbol names a special form. If it doesn’t . . .
- Looking up whether the symbol corresponds to a local binding. If it doesn’t . . .
- Trying to find a namespace mapping introduced by
def. If it doesn’t . . .
- Throwing an exception
Let’s first look at a symbol resolving to a special form. Special forms, like
if, are always used in the context of an operation; they’re always the first element in a list:
(if true :a :b) ; => :a
In this case,
if is a special form and it’s being used as an operator. If you try to refer to a special form outside of this context, you’ll get an exception:
if ; => CompilerException java.lang.RuntimeException: Unable to resolve symbol: if in this context, compiling:(NO_SOURCE_PATH:0:0)
Next, let’s evaluate some local bindings. A local binding is any association between a symbol and a value that wasn’t created by
def. In the next example, the symbol
x is bound to 5 using
let. When the evaluator resolves
x, it resolves the symbol
x to the value 5:
(let [x 5] (+ x 3)) ; => 8
Now if we create a namespace mapping of
x to 15, Clojure resolves it accordingly:
(def x 15) (+ x 3) ; => 18
In the next example,
x is mapped to 15, but we introduce a local binding of
x to 5 using
let. So
x is resolved to 5:
(def x 15) (let [x 5] (+ x 3)) ; => 8
You can nest bindings, in which case the most recently defined binding takes precedence:
(let [x 5] (let [x 6] (+ x 3))) ; => 9
Functions also create local bindings, binding parameters to arguments within the function body. In this next example,
exclaim is mapped to a function. Within the function body, the parameter name
exclamation is bound to the argument passed to the function:
(defn exclaim [exclamation] (str exclamation "!")) (exclaim "Hadoken") ; => "Hadoken!"
Finally, in this last example,
map and
inc both refer to functions:
(map inc [1 2 3]) ; => (2 3 4)
When Clojure evaluates this code, it first evaluates the
map symbol, looking up the corresponding function and applying it to its arguments. The symbol
map refers to the map function, but it shouldn’t be confused with the function itself. The
map symbol is still a data structure, the same way that the string
"fried salad" is a data structure, but it’s not the same as the function itself:
(read-string ("+")) ; => + (type (read-string "+")) ; => clojure.lang.Symbol (list (read-string "+") 1 2) ; => (+ 1 2)
In these examples, you’re interacting with the plus symbol,
+, as a data structure. You’re not interacting with the addition function that it refers to. If you evaluate it, Clojure looks up the function and applies it:
(eval (list (read-string "+") 1 2)) ; => 3
On their own, symbols and their referents don’t actually do anything; Clojure performs work by evaluating lists.
Lists
If the data structure is an empty list, it evaluates to an empty list:
(eval (read-string "()")) ; => ()
Otherwise, it is evaluated as a call to the first element in the list. The way the call is performed depends on the nature of that first element.
Function Calls
When performing a function call, each operand is fully evaluated and then passed to the function as an argument. In this example, the
+ symbol resolves to a function:
(+ 1 2) ; => 3
Clojure sees that the list’s head is a function, so it proceeds to evaluate the rest of the elements in the list. The operands 1 and 2 both evaluate to themselves, and after they’re evaluated, Clojure applies the addition function to them.
You can also nest function calls:
(+ 1 (+ 2 3)) ; => 6
Even though the second argument is a list, Clojure follows the same process here: look up the
+ symbol and evaluate each argument. To evaluate the list
(+ 2 3), Clojure resolves the first member to the addition function and proceeds to evaluate each of the arguments. In this way, evaluation is recursive.
Special Forms
You can also call special forms. In general, special forms are special because they implement core behavior that can’t be implemented with functions. For example:
(if true 1 2) ; => 1
Here, we ask Clojure to evaluate a list beginning with the symbol
if. That
if symbol gets resolved to the
if special form, and Clojure calls that special form with the operands
true,
1, and
2.
Special forms don’t follow the same evaluation rules as normal functions. For example, when you call a function, each operand gets evaluated. However, with
if you don’t want each operand to be evaluated. You only want certain operands to be evaluated, depending on whether the condition is true or false.
Another important special form is
quote. You’ve seen lists represented like this:
'(a b c)
As you saw in “The Reader” on page 153, this invokes a reader macro so that we end up with this:
(quote (a b c))
Normally, Clojure would try to resolve the
a symbol and then call it because it’s the first element in a list. The
quote special form tells the evaluator, “Instead of evaluating my next data structure like normal, just return the data structure itself.” In this case, you end up with a list consisting of the symbols
a,
b, and
c.
def,
let,
loop,
fn,
do, and
recur are all special forms as well. You can see why: they don’t get evaluated the same way as functions. For example, normally when the evaluator evaluates a symbol, it resolves that symbol, but
def and
let obviously don’t behave that way. Instead of resolving symbols, they actually create associations between symbols and values. So the evaluator receives a combination of data structures from the reader, and it goes about resolving the symbols and calling the functions or special forms at the beginning of each list. But there’s more! You can also place a macro at the beginning of a list instead of a function or a special form, and this can give you tremendous power over how the rest of the data structures are evaluated.
Macros
Hmm . . . Clojure evaluates data structures—the same data structures that we write and manipulate in our Clojure programs. Wouldn’t it be awesome if we could use Clojure to manipulate the data structures that Clojure evaluates? Yes, yes it would! And guess what? You can do this with macros! Did your head just explode? Mine did!
To get an idea of what macros do, let’s look at some code. Say we want to write a function that makes Clojure read infix notation (such as
1 + 1) instead of its normal notation with the operator first (
+ 1 1). This example is not a macro. Rather, it merely shows that you can write code using infix notation and then use Clojure to transform it so it will actually execute. First, create a list that represents infix addition:
(read-string "(1 + 1)") ; => (1 + 1)
Clojure will throw an exception if you try to make it evaluate this list:
(eval (read-string "(1 + 1)")) ; => ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
However,
read-string returns a list, and you can use Clojure to reorganize that list into something it can successfully evaluate:
(let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix))) ; => (+ 1 1)
If you
eval this, it returns
2, just as you’d expect:
(eval (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix)))) ; => 2
This is cool, but it’s also quite clunky. That’s where macros come in. Macros give you a convenient way to manipulate lists before Clojure evaluates them. Macros are a lot like functions: they take arguments and return a value, just like a function would. They work on Clojure data structures, just like functions do. What makes them unique and powerful is the way they fit in to the evaluation process. They are executed in between the reader and the evaluator—so they can manipulate the data structures that the reader spits out and transform with those data structures before passing them to the evaluator.
Let’s look at an example:
(defmacro ignore-last-operand [function-call] (butlast function-call)) ➊ (ignore-last-operand (+ 1 2 10)) ; => 3 ;; This will not print anything (ignore-last-operand (+ 1 2 (println "look at me!!!"))) ; => 3
At ➊ the macro
ignore-last-operand receives the list
(+ 1 2 10) as its argument, not the value
13. This is very different from a function call, because function calls always evaluate all of the arguments passed in, so there is no possible way for a function to reach into one of its operands and alter or ignore it. By contrast, when you call a macro, the operands are not evaluated. In particular, symbols are not resolved; they are passed as symbols. Lists are not evaluated either; that is, the first element in the list is not called as a function, special form, or macro. Rather, the unevaluated list data structure is passed in.
Another difference is that the data structure returned by a function is not evaluated, but the data structure returned by a macro is. The process of determining the return value of a macro is called macro expansion, and you can use the function
macroexpand to see what data structure a macro returns before that data structure is evaluated. Note that you have to quote the form that you pass to
macroexpand:
(macroexpand '(ignore-last-operand (+ 1 2 10))) ; => (+ 1 2) (macroexpand '(ignore-last-operand (+ 1 2 (println "look at me!!!")))) ; => (+ 1 2)
As you can see, both expansions result in the list
(+ 1 2). When this list is evaluated, as in the previous example, the result is
3.
Just for fun, here’s a macro for doing simple infix notation:
(defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2)) ; => 3
The best way to think about this whole process is to picture a phase between reading and evaluation: the macro expansion phase. Figure 7-6 shows how you can visualize the entire evaluation process for
(infix (1 + 2)).
And that’s how macros fit into the evaluation process. But why would you want to do this? The reason is that macros allow you to transform an arbitrary data structure like
(1 + 2) into one that can Clojure can evaluate,
(+ 1 2). That means you can use Clojure to extend itself so you can write programs however you please. In other words, macros enable syntactic abstraction. Syntactic abstraction may sound a bit abstract (ha ha!), so let’s explore that a little.
Syntactic Abstraction and the -> Macro
Often, Clojure code consists of a bunch of nested function calls. For example, I use the following function in one of my projects:
(defn read-resource "Read a resource into a string" [path] (read-string (slurp (clojure.java.io/resource path))))
To understand the function body, you have to find the innermost form, in this case
(clojure.java.io/resource path), and then work your way outward from right to left to see how the result of each function gets passed to another function. This right-to-left flow is opposite of what non-Lisp programmers are used to. As you get used to writing in Clojure, this kind of code gets easier and easier to understand. But if you want to translate Clojure code so you can read it in a more familiar, left-to-right, top-to-bottom manner, you can use the built-in
-> macro, which is also known as the threading or stabby macro. It lets you rewrite the preceding function like this:
(defn read-resource [path] (-> path clojure.java.io/resource slurp read-string))
You can read this as a pipeline that goes from top to bottom instead of from inner parentheses to outer parentheses. First,
path gets passed to
io/
resource, then the result gets passed to
slurp, and finally the result of that gets passed to
read-string.
These two ways of defining
read-resource are entirely equivalent. However, the second one might be easier understand because we can approach it from top to bottom, a direction we’re used to.!!!
Summary
In this chapter, you learned about Clojure’s evaluation process. First, the reader transforms text into Clojure data structures. Next, the macro expander transforms those data structures with macros, converting your custom syntax into syntactically valid data structures. Finally, those data structures get sent to the evaluator. The evaluator processes data structures based on their type: symbols are resolved to their referents; lists result in function, macro, or special form calls; and everything else evaluates to itself.
The coolest thing about this process is that it allows you to use Clojure to expand its own syntax. This process is made easier because Clojure is homoiconic: its text represents data structures, and those data structures represent abstract syntax trees, allowing you to more easily reason about how to construct syntax-expanding macros.
With all these new concepts in your brainacles, you’re now ready to blow stuff up on purpose, just like I promised. The next chapter will teach you everything you need to know about writing macros. Hold on to your socks or they’re liable to get knocked off!
Exercises
These exercises focus on reading and evaluation. Chapter 8 has exercises for writing macros.
- Use the
listfunction, quoting, and
read-stringto create a list that, when evaluated, prints your first name and your favorite sci-fi movie.
- Create an infix function that takes a list like
(1 + 3 * 4 - 5)and transforms it into the lists that Clojure needs in order to correctly evaluate the expression using operator precedence rules. | http://www.braveclojure.com/read-and-eval/ | CC-MAIN-2016-40 | refinedweb | 4,834 | 60.14 |
The
HashSet<T> generic class in the
System.Collections.Generic namespace provides the
Clear() method, which is used to remove all the elements from a HashSet
HashSet<T> becomes empty after the
Clear() method is called.
public void Clear ();
Other object references from elements of the
HashSet<T> are also released after calling the
Clear() method.
The HashSet’s
Count property becomes
Clear() method is called.
This method does not change the capacity of the HashSet
This method changes the state of the HashSet.
In the example below, we first create a HashSet of strings and add two strings to it:
January and
February. We then print the count of elements in the HashSet.
Next, we call the
Clear() method to remove all elements of the HashSet. We again print the count and observe zero after the
Clear() method is called.
The program prints the following output and exits.
Added 'January' and 'February' to HashSet, Count : 2 Count of HashSet afte Clear() : 0
using System; using System.Collections.Generic; class HashSetAdd { static void Main() { HashSet<string> monthSet = new HashSet<string>(); monthSet.Add("January"); monthSet.Add("February"); Console.WriteLine($"Added 'January' and 'February' to HashSet, Count : {monthSet.Count}"); monthSet.Clear(); Console.WriteLine($"Count of HashSet afte Clear() : {monthSet.Count}"); } }
RELATED TAGS
CONTRIBUTOR
View all Courses | https://www.educative.io/answers/how-to-remove-all-elements-from-the-hashset-in-c-sharp | CC-MAIN-2022-33 | refinedweb | 214 | 58.38 |
How to Build a Chat App With Next.js & Firebase
In this tutorial, we will guide you through building a simple chat application with Next.js and Firebase.
Apple dropped a bombshell for developers on WWDC 19. Among a bunch of other things, they released SwiftUI — a whole new way of making iOS apps and the biggest change to iOS development since Swift came out. Say goodbye to storyboards, auto-layout or coding your UI by hand, SwiftUI is here to replace all of that. If this sounds good to be true, you might be right. This introduction is here to show you what SwiftUI is all about, how it fits in the existing ecosystem and what it means for iOS developers.
Whether or not you're brave enough to switch to SwiftUI now, the fact is that the future of iOS development is SwiftUI. Currently, SwiftUI is in the same place Swift was a couple of years ago, starting small with a handful of early adopters. But Apple's messaging is pretty clear: Just like Swift, SwiftUI will become the dominant framework in a couple of years.
That's why learning SwiftUI, sooner rather than later, is a valuable (and marketable!) skill for any iOS developer and this introduction is here to get you started.
To see just how different SwiftUI is from UIKit, let's look at a SwiftUI login screen.
That screen is coded with the following code:
{% c-block language="swift" %}
import SwiftUI
struct ContentView: View {
@State var email = ""
@State var password = ""
@State var error: String?
var body: some View {
NavigationView {
VStack {
TextField("Email", text: $email, onCommit: validate)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.emailAddress)
SecureField("Password", text: $password, onCommit: validate)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: login) {
Text("Sign in")
}.disabled(error != nil)
error.flatMap {
Text("Error: \($0)").foregroundColor(.red)
}
}.navigationBarTitle("Log In")
}
}
func validate() { ... }
func login() { ... }
}
{% c-block-end %}
Right now you might not understand everything that's going on in the code above — that's okay. Focus on how much code there is. This is the whole UI. There are no additional storyboards, constraint setup code or UIView subclasses. Even without knowing SwiftUI, you can kind of figure out what the screen looks like and what it does just by looking at the code.
You can think of SwiftUI views as being split between two workers. The workers are each working on their own thing, and only indirectly impacting each other. The first worker renders the UI based on the current state. The other worker takes input from the user and changes the state.
In a SwiftUI View, the state is a variable marked with @State, while the view is a computed variable called body.
{% c-block language="swift" %}
struct ContentView: View {
@State var count = 0
var body: some View {
VStack {
Button(action: { self.count += 1 }) {
Text("Increment")
}
Text("Count: \(count)")
}
}
}
{% c-block-end %}
You can think of body as a function from the state to the view. The @State annotation tells SwiftUI to listen to changes of that variable. Whenever it changes, SwiftUI will call body to re-render the view based on that new state.
The Body
The syntax inside of body might look strange, like a different language embedded into Swift. In reality, it's all just plain old Swift. There's no compiler magic or special exceptions for SwiftUI: You could implement SwiftUI using plain Swift if you had enough time.
Single-expression functions don't need a return keyword, which is why, in the above example, body can return a VStack even if you don’t write return.
Function builders let you define functions that implicitly return an array as a list of expressions. For instance, if you had a builder for an array of integers, you could write a function like the following:
{% c-block language="swift" %}
@NumbersBuilder
func build() -> [Int] {
1
2 + 2
3
}
{% c-block-end %}
Swift will then create an empty array, take every top-level expression in the function, evaluate then and add their results to the array, returning [1, 4, 3] for the above example.
Similarly, in the SwiftUI example above, VStack is a struct that receives a function builder of Views in its initializer. Because Swift lets us emit the round brackets around closures, the syntax looks like VStack { ... }. Inside the curly braces, every top-level expression gets evaluated to a list of Views (in this case containing Button and Text) and added to a vertical stack view.
If you remove all syntax sugar from the above body, you'll end up with this:
{% c-block language="swift" %}
var body: some View {
let button = Button(
action: { self.count += 1 },
label: { return ViewBuilder.buildBlock(Text("Increment")) })
let countText = Text("Count: \(count)")
return VStack(content: {
return ViewBuilder.buildBlock(button, countText)
})
}
{% c-block-end %}
It looks a lot messier, but you might get a better idea of what the code does this way.
The reason I'm telling you this is because SwiftUI will look daunting at first. You'll also receive very opaque error messages that you that will make you scratch your head in confusion. Knowing that underneath it all lies familiar old Swift will illuminate a lot of these errors for you.
The State
The counter screen example works without any additional code. You'll notice there's no "glue" code anywhere telling SwiftUI to update the counter label with the new text. That's because SwiftUI does that automatically.
By annotating count with @State, SwiftUI knows to call body to reload the view whenever count changes.
This still isn't compiler magic, just plain Swift. The @State annotation is made with a new Swift feature called property wrappers. Property wrappers are structs or classes that hold a single property and expose a setter and a getter, but when used they indistinguishable from a plain value.
By incrementing count (count += 1), you're really calling the setter in the State property wrapper. In other words, the following lines:
{% c-block language="swift" %}
@State var count = 0
count += 1
{% c-block-end %}
Can be de-sugared to:
{% c-block language="swift" %}
let countState = State(initialValue: 0)
countState.wrappedValue += 1
{% c-block-end %}
State has a defined setter for wrappedValue that will tell SwiftUI to reload the view. Thankfully, you don't have to write all that. By using property wrappers, SwiftUI lets you use the state as a regular variable, reloading the view automatically on every change.
You might notice an issue here. If we re-render the body every time a tiny change happens, we'll end up rewriting the whole UI every couple of seconds! Thankfully, SwiftUI only updates the views that need updating. The view hierarchy has a tree-like structure, and you can compare the current tree of views with the next one. Only the nodes that are different (and their sub-nodes) need to be updated.
The goal of SwiftUI is to let the system take care of more things, so you can focus on making the app you like.
You'll hear a lot of buzzwords around SwiftUI, both from Apple and the community. To realize what SwiftUI means, it's important to unpack those buzzwords:
Composable
First, SwiftUI is composable. It doesn't separate views from view controllers, instead, your whole UI is made up of Views. This gives you the flexibility to separate your code in any way you see fit. You can have one huge View for your app, or have a huge hierarchy of small Views. This also makes it easier to reuse stuff. Every View can be placed inside every other View, with no need for child view controllers or lifecycle management pains.
This makes SwiftUI development incredibly easy for copy-and-paste development. While seasoned developers might scoff at that sentence, the way people build apps these days is by searching for simple things like "how to make a button" and copying the code.
I built a login screen this way in SwiftUI, without any previous knowledge, in 15 minutes. If I wanted to do that in UIKit, I'd have to spend days reading about Interface Builder, auto-layout and outlets before I could even start coding.
Finding a working example and tweaking it to your needs is incredibly productive, and SwiftUI lets you do that.
Declarative
Secondly, SwiftUI is declarative. Instead of creating a storyboard or creating your UI by instantiating and setting up views, SwiftUI lets you use Swift code to describe your UI. You tell SwiftUI, "I want a black view here, and a red view inside of it." SwiftUI then goes and draws those views for you. And it's all just plain Swift code.
What's frustrating about Storyboards is that they're not code. Everything needs to be constant and pre-determined. You can't dynamically calculate a margin or hide a view based on some condition. In other words, there are no **if**s in a storyboard.
However, the code inside SwiftUI's body is plain Swift. That means that all of Swift's tools are available to you: You can use structs, classes, collections, loops and control blocks to write out your UI. If you want to show an empty state in your list, you can check if the list is empty and show that view, and otherwise show the list.
By giving you the flexibility of Swift, your UI code becomes a lot simpler, and the tension between the Storyboard and your code disappears.
Reactive
Finally, SwiftUI is reactive. If you want to change the color of a button in UIKit, you'd grab the button and directly set its color. SwiftUI doesn't offer this direct control. Instead, you'd have a state variable that defines button's color. You'd also have a different function that returns a new button based on this new variable. Whenever you change the state variable, SwiftUI will automatically call the latter function and draw the new button.
This eliminates a whole class of bugs that come up as a result of a difference between your view controller's state and what's shown on the UI. By letting SwiftUI reload your views automatically, you know that your view's state is the single source of truth for the view. This lets you focus on working only on the state, without having to think of what will happen in your view.
This idea of separating working on your state and your view is a long-standing idea in the iOS community. It's the idea behind the most popular architectural patterns like MVP (Model and Presenter separated from the View), MVVM (Model and View Model separated from the View), VIPER and others. With SwiftUI, you get this separation out of the box.
This combination of features in a single framework isn't new by a long shot. React, Vue.js and Angular — three of the most JavaScript UI frameworks already have these features. With frameworks like Electron, React Native, Jetpack Compose and Flutter, this approach to UI is already here on mobile, in huge apps like Instagram, Uber or Pinterest. This is well-trodden territory and has proved itself to be one of the most productive ways to program UIs.
By now you noticed that SwiftUI works a lot differently than UIKit. Just like you can't write Swift as you wrote Objective-C, you can't write SwiftUI like you wrote UIKit. SwiftUI requires a change of mindset.
When looking at a login screen, an iOS developer will first think of a view controller containing two text views and a button. In SwiftUI, you'll instead think of three different Views. First, you'll need a View for the text view. Next, you'll need another View for the button. Finally, you'll need a View that will assemble two text views and the button.
When working with SwiftUI, you'll stop thinking in terms of properties and methods, and start thinking in terms of state. A text view has a state variable that holds the text. Instead of changing textView.text, you'll update the state. The state change will then trigger a call of the body variable, where you'll return a new text field containing the new text.
By starting simple and slowly building out a whole app, this type of thinking will become second-nature by the end of our SwiftUI course.
I won't lie to you, SwiftUI is completely different than UIKit. When I first started building an app in SwiftUI I had a little identity crisis. Here I was, an iOS developer who has worked on tens of apps, wrote and edited books about iOS, spoke at iOS meetups — struggling with centering a text field.
Over time, though, I found my way around the different types of views. When I get stuck, I knew what to try and where to find the solutions. I realized that, even though my UIKit knowledge isn't of much use, I still understand Swift, the iOS ecosystem and programming. Thankfully, SwiftUI is nothing but Swift! Armed with these skills (and our course!), I'm sure you'll quickly get the hang of SwiftUI.
That's where we come in. During the following few months, we'll be releasing a SwiftUI course that will teach you how to make a complete, production-level SwiftUI app. Read to the end of this article to find out more about the course!
You can think of UIKit now as Objective-C a couple of years ago. Even though SwiftUI is the new hotness, it still stands on the shoulders of UIKit (and Objective-C, for that matter). That means that UIKit isn't going away soon.
Slowly, over time, Apple will probably put more and more focus on SwiftUI, until eventually, SwiftUI will be the framework receiving new features instead of UIKit. Don't worry, though, you still have plenty of time.
Speaking of which, the pragmatists among you might want to hold out a little bit until you convert your app to SwiftUI. Just like the early days of Swift, SwiftUI is young and not fully molded into shape. Some things that exist in UIKit are still just plain missing. As SwiftUI evolves and matures, expect a lot of changes and View rewriting.
That isn't to say you shouldn't learn SwiftUI. If you're an iOS developer, knowing SwiftUI (and knowing it early) can help you stand out among other, more conservative developers. Eventually, everybody doing iOS development will need people who know SwiftUI. Getting in early can be a competitive advantage for you or your company.
You should learn SwiftUI as soon as possible. But, should you convert or start making your app in SwiftUI? The answer is, as it is often, an unsatisfying “it depends”.
SwiftUI is very young and the small SwiftUI community is only starting to grow. Some things that are available in UIKit don't yet exist in SwiftUI, and there are some kinks Apple still needs to work out. I expect SwiftUI to change a little bit in a year's time, which might not be the best thing to hear if you want to convert your whole app.
If you're starting to make an app now and only want to support iOS 13, I'd strongly consider using SwiftUI as much as possible.
If you already have an existing app, it might be more practical to build new views in SwiftUI (and convert a few existing smaller ones) and use UIKit and SwiftUI in tandem, slowly increasing the ratio of SwiftUI code over UIKit. John Sundell seems to agree with this thinking and has some good practical advice on his blog post about how to mix and match SwiftUI with UIKit.
If you decide to go full SwiftUI, be ready for some changes down the line. If you decide to not use SwiftUI at all, don't be surprised when Apple pulls the UIKit rug out from under you sooner than you expect. I suggest going right down the middle and gradually adopting SwiftUI as you go.
To help you master SwiftUI, we're working on a full SwiftUI course that we'll release over the coming few months.
This SwiftUI course is designed for the practical developer. You'll learn SwiftUI by building our a real-world production-level chat app. You'll see the benefits and disadvantages of SwiftUI on a scale larger than a simple example app. You'll also learn how large SwiftUI apps can be structured and architected, as well as how to leverage other new frameworks like Combine to help you build your apps.
While other courses and Apple's website offer great short examples, diving in deep is the only way to fully learn a framework, and that's what we'll do in this course.
Here's how this course is structured:
If you want to receive the next part of the course as soon as it comes out, follow me here, or check out the posts on CometChat's blog!
The most robust suite of cloud-hosted text, voice and video solutions on the market. CometChat seamlessly integrates onto websites and apps quickly and securely, powering digital communities across the globe. | https://www.cometchat.com/tutorials/introduction-to-swift-ui | CC-MAIN-2021-21 | refinedweb | 2,885 | 71.95 |
31205/can-not-make-a-peer-in-hyperledger-fabric
I am trying to make a peer using make peer command but when I run this, I am getting the following error:
update-java-alternatives: directory does not exist: /usr/lib/jvm/java-1.8.0-openjdk-amd64
The command '/bin/sh -c core/chaincode/shim/java/javabuild.sh' returned a non-zero code: 1
Makefile:217: recipe for target 'build/image/javaenv/.dummy' failed
make: *** [build/image/javaenv/.dummy] Error 1
How to solve this?
You have not installed jdk on your system. You can install it using this:
sudo apt-get install default-jdk-headless
The peers communicate among them through the ...READ MORE
When you run the command:
peer channel create ...READ MORE
New nodes doesn't depend on a single ...READ MORE
This link might help you: ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
In a hyperledger fabric network transactions are ...READ MORE
Try this:
kafka1.hyperfabric.xyz:
image: hyperledger/fabric-kafka
restart: ...READ MORE
I know it is a bit late ...READ MORE
OR | https://www.edureka.co/community/31205/can-not-make-a-peer-in-hyperledger-fabric | CC-MAIN-2019-22 | refinedweb | 198 | 54.39 |
Java while loop is used to execute a block of statements continuously till the given condition is true. Earlier we looked into java for loop.
Table of Contents
Java while loop
While loop in java syntax is as follows.
while (expression) { // statements }
The
expression for while loop must return boolean value, otherwise it will throw compile time error.
While loop java flow diagram
Java while loop example
Here is a simple java while loop example to print numbers from 5 to 10.
package com.journaldev.javawhileloop; public class JavaWhileLoop { public static void main(String[] args) { int i = 5; while (i <= 10) { System.out.println(i); i++; } } }.
List<String> veggies = new ArrayList<>(); veggies.add("Spinach"); veggies.add("Potato"); veggies.add("Tomato"); Iterator<String> it = veggies.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
It will print output as below.
Spinach Potato Tomato.
package com.journaldev.javawhileloop; public class WhileTrueJava { public static void main(String[] args) { while(true) { System.out.println("Start Processing"); // look for a file at specific directory // if found then process it, say insert rows into database System.out.println("End Processing"); // wait for 10 seconds and look again try { Thread.sleep(10*1000); } catch (InterruptedException e) { System.out.println("Thread Interrupted, exit now"); System.exit(0); } } } }.
boolean mutex = false; while(mutex) { System.out.println("incomplete code"); }
That’s all about java while loop, I hope you get clear idea how and when to use while loop in java.
Reference: Oracle Documentation
while(true){
System.out.println(“Keep posting these tutorials”);
System.out.println(“Thank you very much”);
}
Thanks a lot for the appreciation, I really liked the way you have put it.
I have studied a lot about the java while loop function. It is a very helpful function and it is required now in mostly in every program. The function is very much helpful. | https://www.journaldev.com/16510/java-while-loop | CC-MAIN-2021-04 | refinedweb | 308 | 51.65 |
Data Science
OCI Data Science – Create a Project & Notebook, and Explore the Interface
In my previous blog post I went through the steps of setting up OCI to allow you to access OCI Data Science. Those steps showed the setup and configuration for your Data Science Team.
In this post I will walk through the steps necessary to create an OCI Data Science Project and Notebook, and will then Explore the basic Notebook environment.
1 – Create a Project
From the main menu on the Oracle Cloud home page select Data Science -> Projects from the menu.
Select the appropriate Compartment in the drop-down list on the left hand side of the screen. In my previous blog post I created a separate Compartment for my Data Science work and team. Then click on the Create Projects button.
Enter a name for your project. I called this project, ‘DS-Demo-Project’. Click Create button.
That’s the Project created.
2 – Create a Notebook
After creating a project (see above) you can not create one or many Notebook Sessions.
To create a Notebook Session click on the Create Notebook Session button (see the above image). This will create a VM to contain your notebook and associated work. Just like all VM in Oracle Cloud, they come in various different shapes. These can be adjusted at a later time to scale up and then back down based on the work you will be performing.
The following example creates a Notebook Session using the basic VM shape. I call the Notebook ‘DS-Demo-Notebook’. I also set the Block Storage size to 50G, which is the minimum value. The VNC details have been defaulted to those assigned to the Compartment. Click Create button at the bottom of the page.
The Notebook Session VM will be created. This might take a few minutes. When created you will see a screen like the following.
3 – Open the Notebook
After completing the above steps you can now open the Notebook Session in your browser. Either click on the Open button (see above image), or copy the link and share with your data science team.
Important: There are a few important considerations when using the Notebooks. While the session is running you will be paying for it, even if the session got terminated at the browser or you lost connect. To manage costs, you may need to stop the Notebook session. More details on this in a later post.
After clicking on the Open button, a new browser tab will open and will ask you to log-in..
The uploaded Notebook will appear in the list on the left-hand side of the screen.
Data.
Sc.
#GE2020 Analysing Party Manifestos using Python
The general election is underway here in Ireland with polling day set for Saturday 8th February. All the politicians are out campaigning and every day the various parties are looking for publicity on whatever the popular topic is for that day. Each day is it a different topic.
Most of the political parties have not released their manifestos for the #GE2020 election (as of date of this post). I want to use some simple Python code to perform some analyse of their manifestos. As their new manifestos weren’t available (yet) I went looking for their manifestos from the previous general election. Michael Pidgeon has a website with party manifestos dating back to the early 1970s, and also has some from earlier elections. Check out his website.
I decided to look at manifestos from the 4 main political parties from the 2016 general election. Yes there are other manifestos available, and you can use the Python code, given below to analyse those, with only some minor edits required.
The end result of this simple analyse is a WordCloud showing the most commonly used words in their manifestos. This is graphical way to see what some of the main themes and emphasis are for each party, and also allows us to see some commonality between the parties.
Let’s begin with the Python code.
1 – Initial Setup
There are a number of Python Libraries available for processing PDF files. Not all of them worked on all of the Part Manifestos PDFs! It kind of depends on how these files were generated. In my case I used the pdfminer library, as it worked with all four manifestos. The common library PyPDF2 didn’t work with the Fine Gael manifesto document.
import io import pdfminer from pprint import pprint from pdfminer.converter import TextConverter from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfpage import PDFPage #directory were manifestos are located wkDir = '.../General_Election_Ire/' #define the names of the Manifesto PDF files & setup party flag pdfFile = wkDir+'FGManifesto16_2.pdf' party = 'FG' #pdfFile = wkDir+'Fianna_Fail_GE_2016.pdf' #party = 'FF' #pdfFile = wkDir+'Labour_GE_2016.pdf' #party = 'LB' #pdfFile = wkDir+'Sinn_Fein_GE_2016.pdf' #party = 'SF'
All of the following code will run for a given manifesto. Just comment in or out the manifesto you are interested in. The WordClouds for each are given below.
2 – Load the PDF File into Python
The following code loops through each page in the PDF file and extracts the text from that page.
I added some addition code to ignore pages containing the Irish Language. The Sinn Fein Manifesto contained a number of pages which were the Irish equivalent of the preceding pages in English. I didn’t want to have a mixture of languages in the final output.
SF_IrishPages = [14,15,16,17,18,19,20,21,22,23,24] text = "" pageCounter = 0 resource_manager = PDFResourceManager() fake_file_handle = io.StringIO() converter = TextConverter(resource_manager, fake_file_handle) page_interpreter = PDFPageInterpreter(resource_manager, converter) for page in PDFPage.get_pages(open(pdfFile,'rb'), caching=True, check_extractable=True): if (party == 'SF') and (pageCounter in SF_IrishPages): print(party+' - Not extracting page - Irish page', pageCounter) else: print(party+' - Extracting Page text', pageCounter) page_interpreter.process_page(page) text = fake_file_handle.getvalue() pageCounter += 1 print('Finished processing PDF document') converter.close() fake_file_handle.close()
FG - Extracting Page text 0 FG - Extracting Page text 1 FG - Extracting Page text 2 FG - Extracting Page text 3 FG - Extracting Page text 4 FG - Extracting Page text 5 ...
3 – Tokenize the Words
The next step is to Tokenize the text. This breaks the text into individual words.
from nltk.tokenize import word_tokenize from nltk.corpus import stopwords tokens = [] tokens = word_tokenize(text) print('Number of Pages =', pageCounter) print('Number of Tokens =',len(tokens))
Number of Pages = 140 Number of Tokens = 66975
4 – Filter words, Remove Numbers & Punctuation
There will be a lot of things in the text that we don’t want included in the analyse. We want the text to only contain words. The following extracts the words and ignores numbers, punctuation, etc.
#converts to lower case, and removes punctuation and numbers wordsFiltered = [tokens.lower() for tokens in tokens if tokens.isalpha()] print(len(wordsFiltered)) print(wordsFiltered)
58198 ['fine', 'gael', 'general', 'election', 'manifesto', 's', 'keep', 'the', 'recovery', 'going', 'gaelgeneral', 'election', 'manifesto', 'foreward', 'from', 'an', 'taoiseach', 'the', 'long', 'term', 'economic', 'three', 'steps', 'to', 'keep', 'the', 'recovery', 'going', 'agriculture', 'and', 'food', 'generational', ...
As you can see the number of tokens has reduced from 66,975 to 58,198.
5 – Setup Stop Words
Stop words are general words in a language that doesn’t contain any meanings and these can be removed from the data set. Python NLTK comes with a set of stop words defined for most languages.
#We initialize the stopwords variable which is a list of words like #"The", "I", "and", etc. that don't hold much value as keywords stop_words = stopwords.words('english') print(stop_words)
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', ....
Additional stop words can be added to this list. I added the words listed below. Some of these you might expect to be in the stop word list, others are to remove certain words that appeared in the various manifestos that don’t have a lot of meaning. I also added the name of the parties and some Irish words to the stop words list.
#some extra stop words are needed after examining the data and word cloud #these are added extra_stop_words = ['ireland','irish','ł','need', 'also', 'set', 'within', 'use', 'order', 'would', 'year', 'per', 'time', 'place', 'must', 'years', 'much', 'take','make','making','manifesto','ð','u','part','needs','next','keep','election', 'fine','gael', 'gaelgeneral', 'fianna', 'fáil','fail','labour', 'sinn', 'fein','féin','atá','go','le','ar','agus','na','ár','ag','haghaidh','téarnamh','bplean','page','two','number','cothromfor'] stop_words.extend(extra_stop_words) print(stop_words)
Now remove these stop words from the list of tokens.
# remove stop words from tokenised data set filtered_words = [word for word in wordsFiltered if word not in stop_words] print(len(filtered_words)) print(filtered_words)
31038 ['general', 'recovery', 'going', 'foreward', 'taoiseach', 'long', 'term', 'economic', 'three', 'steps', 'recovery', 'going', 'agriculture', 'food',
The number of tokens is reduced to 31,038
6 – Word Frequency Counts
Now calculate how frequently these words occur in the list of tokens.
#get the frequency of each word from collections import Counter # count frequencies cnt = Counter() for word in filtered_words: cnt[word] += 1 print(cnt)
Counter({'new': 340, 'support': 249, 'work': 190, 'public': 186, 'government': 177, 'ensure': 177, 'plan': 176, 'continue': 168, 'local': 150, ...
7 – WordCloud
We can use the word frequency counts to add emphasis to the WordCloud. The more frequently it occurs the larger it will appear in the WordCloud.
#create a word cloud using frequencies for emphasis from wordcloud import WordCloud import matplotlib.pyplot as plt wc = WordCloud(max_words=100, margin=9, background_color='white', scale=3, relative_scaling = 0.5, width=500, height=400, random_state=1).generate_from_frequencies(cnt) plt.figure(figsize=(20,10)) plt.imshow(wc) #plt.axis("off") plt.show() #Save the image in the img folder: wc.to_file(wkDir+party+"_2016.png")
The last line of code saves the WordCloud image as a file in the directory where the manifestos are located.
8 – WordClouds for Each Party
Remember these WordClouds are for the manifestos from the 2016 general election.
When the parties have released their manifestos for the 2020 general election, I’ll run them through this code and produce the WordClouds for 2020. It will be interesting to see the differences between the 2016 and 2020 manifesto WordClouds.
Demographics vs Psychographics for Machine Learning
When preparing data for data science, data mining or machine learning projects you will create a data set that describes the various characteristics of the subject or case record. Each attribute will contain some descriptive information about the subject and is related to the target variable in some way.
In addition to these attributes, the data set will be enriched with various other internal/external data to complete the data set.
Some of the attributes in the data set can be grouped under the heading of Demographics. Demographic data contains attributes that explain or describe the person or event each case record is focused on. For example, if the subject of the case record is based on Customer data, this is the “Who” the demographic data (and features/attributes) will be about. Examples of demographic data include:
- Age range
- Marital status
- Number of children
- Household income
- Occupation
- Educational level
These features/attributes are typically readily available within your data sources and if they aren’t then these name be available from a purchased data set.
Additional feature engineering methods are used to generate new features/attributes that express meaning is different ways. This can be done by combining features in different ways, binning, dimensionality reduction, discretization, various data transformations, etc. The list can go on.
The aim of all of this is to enrich the data set to include more descriptive data about the subject. This enriched data set will then be used by the machine learning algorithms to find the hidden patterns in the data. The richer and descriptive the data set is the greater the likelihood of the algorithms in detecting the various relationships between the features and their values. These relationships will then be included in the created/generated model.
Another approach to consider when creating and enriching your data set is move beyond the descriptive features typically associated with Demographic data, to include Pyschographic data.
Psychographic data is a variation on demographic data where the feature are about describing the habits of the subject or customer. Demographics focus on the “who” while psycographics focus on the “why”. For example, a common problem with data sets is that they describe subjects/people who have things in common. In such scenarios we want to understand them at a deeper level. Psycographics allows us to do this. Examples of Psycographics include:
- Lifestyle activities
- Evening activities
- Purchasing interests – quality over economy, how environmentally concerned are you
- How happy are you with work, family, etc
- Social activities and changes in these
- What attitudes you have for certain topic areas
- What are your principles and beliefs
The above gives a far deeper insight into the subject/person and helps to differentiate each subject/person from each other, when there is a high similarity between all subjects in the data set. For example, demographic information might tell you something about a person’s age, but psychographic information will tell you that the person is just starting a family and is in the market for baby products.
I’ll close with this. Consider the various types of data gathering that companies like Google, Facebook, etc perform. They gather lots of different types of data about individuals. This allows them to build up a complete and extensive profile of all activities for individuals. They can use this to deliver more accurate marketing and advertising. For example, Google gathers data about what places to visit throughout a data, they gather all your search results, and lots of other activities. They can do a lot with this data. but now they own Fitbit. Think about what they can do with that data and particularly when combined with all the other data they have about you. What if they had access to your medical records too! Go Google this ! You will find articles about them now having access to your health records. Again combine all of the data from these different data sources. How valuable is that data?
Managing. | https://oralytics.com/tag/data-science/ | CC-MAIN-2020-34 | refinedweb | 2,369 | 55.54 |
"Success is the ability to go from one failure to another with no loss of
enthusiasm."
Winston Churchill
<blog date="2002-12-05">
Yay! I passed 70-320 today and I'm now MCAD.NET. Expect the next article to
cover XML Web Services, Remoting, or Serviced Components:)
<blog date="2002-12-05">
This article is about Load Balancing. Neither "Unleashed", nor
"Defined" -- "Implemented":) I'm not going to discuss in details what load balancing
is, its different types, or the variety of load balancing algorithms. I'm not
going to talk about proprieatary software like WLBS, MSCS, COM+ Load Balancing or
Application Center either. What I am going to do in this article, is present you
a custom .NET Dynamic Software Load Balancing solution, that I've implemented in
less than a week and the issues I had to resolve to make it work. Though the
source code is only about 4 KLOC, by the end of this article, you'll see, that
the solution is good enough to balance the load of the web servers in a web
farm. Enjoy reading...
...but not everybody would understand everything. To read, and understand the
article, you're expected to know what load balancing is in general, but even if
you don't, I'll explain it shortly -- so keep reading. And to read the code, you
should have some experience with multithreading and network programming (TCP,
UDP and multicasting) and a basic knowledge of .NET Remoting. Contrarily of what
C# developers think, you shouldn't know Managed C++ to read the code. When you're
writing managed-only code, C# and MC++ source code looks almost the same with
very few differences, so I have even included a section
for C# developers which explains how to convert (most of the) MC++ code to C#.
I final warning, before you focus on the article -- I'm not a professional writer,
I'm just a dev, so don't expect too much from me (that's my 3rd article). If you
feel that you don't understand something, that's probably because I'm not a native
English speaker (I'm Bulgarian), so I haven't been able to express what I have
been thinking about. If you find a grammatical nonsense, or even a typo, report it
to me as a bug and I'll be more than glad to "fix" it. And thanks for
bearing this paragraph!
For those who don't have a clue what Load Balancing means, I'm about to give a short
explanation of clustering and load balancing. Very short indeed, because I
lack the time to write more about it, and because I don't want to waste the
space of the article with arid text. You're reading an article at, not at:) The enlightened may
skip the following paragraph, and I encourage the rest to
read it.
Mission-critical applications must run 24x7, and networks need to be able to
scale performance to handle large volumes of client requests without unwanted
delays. A "server cluster" is a group of independent servers managed as a single
system for higher availability, easier manageability, and greater scalability.
It consists of two or more servers connected by a network, and a cluster
management software, such as WLBS, MSCS or Application Center. The software
provides services such as failure detection, recovery, load balancing, and the
ability to manage the servers as a single system. Load balancing is a technique
that allows the performance of a server-based program, such as a Web server, to
be scaled by distributing its client requests across multiple servers within a
cluster of computers. Load balancing is used to enhance scalability, which
boosts throughput while keeping response times low.
I should warn you that I haven't implemented a complete clustering software,
but only the load balancing part of it, so don't expect anything more than
that. Now that you have an idea what load balancing is, I'm sure you don't know
what is my idea for its implementation. So keep reading...
How do we know that a machine is busy? When we feel that our machine is
getting very slow, we launch the Task Manager and look for a hung instance of
iexplore.exe:) Seriously, we look at the CPU utilization. If it is low, then the
memory is low, and disk must be trashing. If we suspect anything else to be the
reason, we run the System Monitor and add some performance counters to look at.
Well, this works if you're around the machine and if you have one or two machines
to monitor. When you have more machines you'll have to hire a person, and buy
him a 20-dioptre glasses to stare at all machines' System Monitor consoles and
go crazy in about a week :). But even if you could monitor your machines constantly
you can't distribute their workload manually, could you? Well, you could use some
expensive software to balance their load, but I assure you that you can do it
yourself and that's what this article is all about. While you are able to
"see" the performance counters, you can also collect their values
programmatically. And I think that if we combine some of them in a certain way,
and do some calculations, they could give you a value, that could be used to
determine the machine's load. Let's check if that's possible!
Let's monitor the \\Processor\% Processor Time\_Total and
\\Processor\% User Time\_Total performance counters. You can
monitor them by launching Task Manager, and looking at the CPU utilization in
the "Performance" tab. (The red curve shows the % Procesor time, and
the green one -- the %User time). Stop or pause all CPU-intensive applications
(WinAMP, MediaPlayer, etc.) and start monitoring the CPU utilization. You have
noticed that the counter values stay almost constant, right? Now, close Task
Manager, wait about 5 seconds and start it again. You should notice a big peak
in the CPU utilization. In several seconds, the peak vanishes. Now, if we were
reporting performance counters values instantly (as we get each counter sample),
one could think that our machine was extremely busy (almost 100%) at that moment,
right? That's why we're not going to report instant values, but we will collect
several samples of the counter's values and will report their average. That would
be fair enough, don't you think? No?! I also don't, I was just checking you:)
What about available memory, I/O, etc. Because the CPU utilization is not enough
for a realistic calculation of the machine's workload, we should monitor more
than one counter at a time, right? And because, let's say, the current number of
ASP.NET sessions is less important than the CPU utilization we will give each
counter a weight. Now the machine load will be calculated as the sum of the
weighted averages of all monitored performance counters. You should be guession
already my idea for dynamic software load balancing. However, a picture worths
thousand words, and an ASCII one worths 2 thousand:) Here' is a real sample, and
the machine load calculation algorithm. In the example below, the machine load
is calculated by monitoring 4 performance counters, each configured to collect
its next sample value at equal intervals, and all counters collect the same
number of samples (this would be your usual case):
\\Processor\% Processor Time\_Total
\\Processor\% User Time\_Total
+-----------+ +-----------+ +-----------+ +-----------+
|% Proc Time| |% User Time| |ASP Req.Ex.| |% Disk Time|
+-----------+ +-----------+ +-----------+ +-----------+
|Weight 0.4| |Weight 0.3| |Weight 0.2| |Weight 0.5|
+-----------+ +-----------+ +-----------+ +-----------+
| 16| | 55| | 11| | 15|
| 22| | 20| | 3| | 7|
| 8| | 32| | 44| | 4|
| 11| | 15| | 16| | 21|
| 18| | 38| | 21| | 3|
+-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+
| Sum | 75| | Sum | 160| | Sum | 95| | Sum | 50|
+-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+
| Avg | 15| | Avg | 32| | Avg | 19| | Avg | 10|
+-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+
| WA | 6.0| | WA | 9.6| | WA | 3.8| | WA | 5.0|
+-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+
Legend:
Sum (% Proc Time) = 16 + 22 + 8 + 11 + 18 = 75
<br />
Average (% Proc Time) = 75 / 5 = 15
<br />
Weighted Average (% Proc Time) = 15 * 0.4 = 6.0
<br />
...
<br />
MachineLoad = Sum (WeightedAverage (EachCounter))
<br />
MachineLoad = 6.0 + 9.6 + 3.8 + 5.0 = 24.4
I wondered about half a day how to explain the architecture to you. Not that it
is so complex, but because it would take too much space in the article, and I
wanted to show you some code, not a technical specification or even a DSS. So I
wondered whether to explain the architecture using a "top-to-bottom"
or "bottom-to-top" approach, or should I think out something else?
Finally, as most of you have already guessed, I decided to explain it in my own
mixed way:) First, you should learn of which assemblies is the solution comprised
of, and then you could read about their collaboration, the types they contain
and so on... And even before that, I recommend you to read and understand two
terms, I've used throughout the article (and the source code's comments).
First, I'd like to appologize about the "diagrams". I can work with only two
software products that can draw the diagrams, I needed in this article. I can't afford
the first (and my company is not willing to pay for it too:), and the second bedeviled
me so much, that I dropped out of the article one UML static structure diagram, a UML
deployment diagram and a couple of activity diagrams (and they were nearly complete).
I won't tell you the name of the product, because I like very much the company that
developed it. Just accept my appologies, and the pseudo-ASCII art, which replaced the
original diagrams. Sorry:)
The load balancing software comes in three parts: a server, that reports the
load of the machine it is running on; a server that collects such loads, no
matter which machine they come from; and a library which asks the collecting
server which is the least loaded (fastest) machine. The server that reports the
machine's load is called "Machine Load Reporting Server" (MLRS), and
the server, that collects machine loads is called "Machine Load Monitoring
Server" (MLMS). The library's name "Load Balancing Library" (LBL).
You can deploy these three parts of the software as you like. For example, you could install
all of them on all machines.
The MLRS server on each machine joins a special, designated for the purpose of
the load balancing, multicasts group, and sends messages, containing the
machine's load to the group's multicast IP address. Because all MLMS servers join
the same group at startup, they all receive each machine load, so if you run both
MLRS and MLMS servers on all machines, they will know each other's load. So what?
We have the machine loads, but what do we do with them? Well, all MLMS servers
store the machine loads in a special data structure, which lets them quickly
retrieve the least machine load at any time. So all machines now know which is
the fastest one. Who cares? We haven't really used that information to balance
any load, right? How do we query MLMS servers which is the fastest machine? The
answer is that each MLMS registers a special singleton object with the .NET
Remoting runtime, so the LBL can create (or get) an instance of that object, and
ask it for the least loaded machine. The problem is that LBL cannot ask
simultaneously all machines about this (yet, but I'm thinking on this issue), so
it should choose one machine (of course, it could be the machine, it is running
on) and will hand that load to the client application that needs the information
to perform whatever load balancing activity is suitable. As you will later see,
I've used LBL in a web application to distribute the workload between all web
servers in web farm. Below is a "diagram" which depicts in general
the collaboration between the servers and the library:
+-----+ ______ +-----+
| A | __/ \__ | B |
+-----+ __/ \__ +-----+
+-->| LMS |<--/ Multicast \-->| LMS |<--+
| | | / \ | | |
| | LRS |-->\__ Group __/ | | |
| | | \__ __/ | | |
|<--| LBL | ^ \______/ | LBL |---+
| +-----+ | +-----+
| | +-----+
| | | C |
| | +-----+
| | | |
| | | |
| +--| LRS |
| Remoting | |
+--------------------| LBL |
+-----+
MLMS, MLRS and LBL Communication
Note: You should see the strange figure between the machines as a cloud,
i.e. it represents a LAN :) And one more thing -- if you don't understand what
multicasting is, don't worry, it is explained later in the
Collaboration section.
Now look at the "diagram" again. Let me remind you that when a machine
joins a multicast group, it receives all messages sent to that group, including
the messages, that the machine has sent. Machine A receives its own load, and
the load, reported by C. Machine B receives the load of A and C (it does not
report its load, because there's no MLRS server installed on it). Machine C does
not receive anything, because it has not MLMS server installed. Because the
machine C's LBL should connect (via Remoting) to an MLMS server, and it has no
such server installed, it could connect to machine A or B and query the remoted
object for the fastest machine. On the "diagram" above, the LBL of A
and C communicate with the remoted object on machine A, while the LBL of B
communicates with the remoted object on its machine. As you will later see in
the Configuration section, there are very few
things that are hardcoded in the solution's source code, so don't worry -- you
will be able to tune almost everything.
The solution consists of 8 assemblies, but only three of them are of some
interest to us now: MLMS, MLRS, and LBL, located respectively in two console
applications (Machine<code>LoadMonitoringServer.exe and
Machine<code>LoadReportingServer.exe) and one dynamic link library
(LoadBalancingLibrary.dll). Surprisingly, MLMS and MLRS do not
contain any types. However, they use several types get their job done. You may
wonder why I have designed them in that way. Why hadn't I just implemented both
servers directly in the executables. Well, the answer is quite simple and
reflects both my strenghts and weaknesses as a developer. If you have the time
to read about it, go ahead, otherwise click here to skip
the slight detour.
Machine<code>LoadMonitoringServer
Machine<code>LoadReportingServer
LoadBalancingLibrary.dll
GUI programming is what I hate (though I've written a bunch of GUI apps). For
me, it is a mundane work, more suitable for a designer than for a developer. I
love to build complex "things". Server-side applications are my
favorite ones. Multi-threaded, asynchronous programming -- that's the
"stuff" I love. Rare applications, that nobody "sees" except
for a few administrators, which configure and/or control them using some sort of
administration consoles. If these applications work as expected the end-user will
almost never know s/he is using them (e.g. in most cases, a user browsing a web
site does not realize that an IIS or Apache server is processing her requests and
is serving the content). Now, I've written several Windows C++ services in the
past, and I've written some .NET Windows services recently, so I could easily
convert MLMS and MLRS to one of these. On the other hand I love console (CUI)
applications so much, and I like seing hundreds of tracing messages on the
console, so I left MLMS and MLRS in their CUI form for two reasons. The first
reason is that you can quickly see what's wrong, when something goes wrong (and
it will, at least once:), and the second one is because I haven't debugged .NET
Windows services (and because I have debugged C++ Windows services, I can assure
you that it's not "piece of cake"). Nevertheless, one can easily
convert both CUI applications in Windows services in less than half an hour. I
haven't implemented the server classes into the executables to make it easier for
the guy who would convert them into Windows services. S/he'll need to write just
4 lines of code in the Window Service class's to get the job done:
LoadXxxServer __gc* server;
OnStart
server = new LoadXxxServer ();
server->Start ();
OnStop
server->Stop ();
Xxx is either Monitoring or Reporting.
I'm sure you understand me now why I have implemented the servers' code in
separate classes in separate libraries, and not directly in the executables.
Xxx
Monitoring
Reporting
I mentioned above that the solution consists of 8 assemblies, but as you
remember, 2 of them (the CUIs) did not contain any types, one of them was LBL,
so what are the other 5? MLMS and MLRS use respectively the types, contained in
the libraries LoadMonitoringLibrary (LML) and
LoadReportingLibrary (LRL). On the other hand, they and LBL use
common types, shared in an assembly, named SharedLibrary (SL). So
the assemblies are now MLMS + MLRS + LML + LRL + LBL + SL = 6. The 7th is a
simple CUI (not interesting) application, I used to test the load balancing, so
I'll skip it. The last assembly, is the web application that demonstrates the
load balancing in action. Below is a list of the four most important assemblies
that contain the types and logic for the implementation of the load balancing
solution.
LoadMonitoringLibrary
LoadReportingLibrary
SharedLibrary
SharedLibary (SL) - contains common and helper types, used by LML,
LRL and/or LBL. A list of the types (explained further) follows:
SharedLibary
ServerStatus
WorkerDoneEventHandler
Configurator
CounterInfo
ILoadBalancer
IpHelper
MachineLoad
Tracer
NOTE:
CounterInfo is not exactly what C++ developers call a "struct" class,
because it does a lot of work behind the scenes. Its implementation is non-
trivial and includes topics like timers, synchronization, and performance
counters monitoring; look at the Some Implementation Details
section for more information about it.
LoadMonitoringLibrary (LML) - contains the LoadMonitoringServer (LMS) class,
used directly by MLMS, as well as all classes, used internally in the LMS
class. List of LML's types (explained further) follows:
LoadMonitoringServer
MachineLoadsCollection
LoadMapping
CollectorWorker
ReporterWorker
WorkerTcpState
WorkerUdpState
ServerLoadBalancer
NOTE: I used the ReporterWorker to implement the first version of LBL in some
faster, more lame way, but I've dropped it later; now, LMS registers a Singleton
object for the LBL requests; however, LMS is still using (the fully functional)
ReporterWorker class, so one could build another kind of LBL that connects to an
MLMS and asks for the least loaded machine using a simple TCP socket (I'm sorry
that I've overwritten the old LBL library).
LoadReportingLibrary (LRL) - contains the LoadReportingServer (LRS) class, used
directly by MLRS, as well as all classes, used internally in the LRS class.
List of LRL's types (explained further) follows:
LoadReportingServer
ReportingWorker
LoadBalancingLibrary (LBL) - contains just one class, ClientLoadBalancer, which
is instantiated by client applications; the class contains only one (public)
method, which is "surprisingly" named GetLeastMachineLoad returning the least
loaded machine:) LBL connects to LML's ServerLoadBalancer singleton object via
Remoting. For more details, read the following section.
LoadBalancingLibrary
ClientLoadBalance
GetLeastMachineLoad
In order to understand how the objects "talk" to each other within an assembly
and between assemblies (and on different machines), you should understand some
technical terms. Because they amount to about a page, and maybe most of you do
know what they mean, here's what I'll do: I'll give you a list of the terms, and
if you know them, click here to read about the collaboration,
otherwise, keep reading... The terms are: delegate, worker, TCP, UDP, (IP) Multicasting,
and Remoting.
I'll start from inside-out, i.e. I'll first explain how various classes
communicate with each other with the assemblies, and then I'll explain how the
assemblies collaborate between them.
When the LoadReportingServer and LoadMonitoringServer classes are instantiated,
and their Start methods are called, they launch respectively one or two
threads to do their job asynchronously (and to be able to respond to "Stop"
commands, of course). Well, if starting a thread is very easy, controlling it is
not that easy. For example, when the servers should stop, they should notify the
threads that they are about to stop, so the threads could finish their job and
exit appropriately. On the other hand, when the servers launch the threads, they
should be notified when the threads are about to enter their thread loops and
have executed their initialization code. In the next couple of paragraphs I'll
explain how I've solved these synchronization issues, and if you know a cooler
way, let me know (with the message board below). In the paragraphs below, I'll
refer to the instances of the LoadReportingServer and LoadMonitoringServer
classes as "(the) server".
Start
When the Start method is executed, the LMS object creates a worker class
instance, passing it a reference to itself (this), a reference to a delegate and
some other useful variables that are not interesting for this section. The
server object then creates an AutoResetEvent object in a unsignalled state. Then
the LMS object starts a new thread, passing for the ThreadStart delegate the
address of a method in the worker class. (I call a worker class' method, launched
as a thread a worker thread.) After the thread has been started, the server object
blocks, waiting (infinitely) for the event object to be signalled. Now, when the
thread's initialization code completes, it calls back the server via the server-
supplied delegate, passing a boolean parameter showing whether its initialization
code executed successfully or something went wrong. The target method of the
delegate in the server class sets (puts in signalled state) the AutoResetEvent
object and records in a private boolean member the result of the thread
initialization. Setting the event object unblocks the server: it now knows that
the thread's startup code has completed, and also knows the result of the thread's
initialization. If the thread did not manage to initialize successfully, it has
already exited, and the server just stops. If the thread succeeded to initialize, then
it enters its thread loop and waits for the server to inform it when it should
exit the loop (i.e. the server is stopping). One could argue that this
"worker thread-to-main thread" synchronization looks too complicated
and he might be right. If we only needed to know that the thread has finished the
initialization code (and don't care if it initialized successfully) we could
directly pass the worker a reference to the AutoResetEvent object,
and the thread would then set it to a signalled state, but you saw that we need
to know whether the thread has initialized successfully or not.
AutoResetEvent
ThreadStart
Now that was the more complex part. The only issue we have to solve now is how
to stop the thread, i.e. make it exit its thread loop. Well, that's what I call
a piece of cake. If you remember, the server has passed a reference to itself
(this) to the worker. The server has a Status property,
which is an enumeration, describing the state of the server (Starting, Started,
Stopping, Stopped). Because the thread has a reference to the server, in its
thread loop it checks (by invoking the Status property) whether the
server is not about to stop (Status == ServerStatus::Stopping). If
the server is stopping, so is the thread, i.e. the thread exits silently and
everything's OK. So when the server is requested to stop, it modifies its private
member variable status to Stopping and Joins
the thread (waits for the thread to exit) for a configured interval of time. If
the thread exits in the specified amount of time, the server changes its status
to Stopped and we're done. However, a thread may timeout while
processing a request, so the server then aborts the thread by calling the
thread's Abort method. I've written the thread loops in
try...catch...finally blocks and in their catch clause,
the threads check whether they die a violent death:), i.e. a
ThreadAbortException was raised by the server. The thread then
executes its cleanup code and exits. (And I thought that was easier to explain:)
this
Status
Status == ServerStatus::Stopping
status
Stopping
Join
Stopped
Abort
try...catch...finally
catch
ThreadAbortException
That much about how the server classes talk to worker classes (main thread to
worker threads). The rest of the objects in the assemblies communicate using
references to each other or via delegates. Now comes the part that explains how
the assemblies "talk" to each other, i.e. how the MLRS sends its
machine's load to the MLMS, and how LBL gets the minimum machine load from MLMS.
I'll first "talk" how the MLRS reports the machine load to MLMS. To save some
space in the article (some of your bandwidth, and some typing for me:), I'll
refer to the LoadReportingServer class as LRS and to the LoadMonitoringServer
class as LMS. Do not confuse them with the server applications, having an "M"
prefix.
LMS starts two worker threads. One for collecting machine loads, and one for
reporting the minimum load to interested clients. The former is named
CollectorWorker, and the latter -- ReporterWorker.
I've mentioned somewhere above that the ReporterWorker is not so
interesting, so I'll talk only about the CollectorWorker. In the
paragraphs below, I'll call it simply a collector. When the collector thread is
started, it creates a UDP socket, binds it locally and adds it to a multicast
group. That's the collector's initialization code. It then enters a thread loop,
periodically polling the socket for arrived requests. When a request comes, the
collector reads the incomming data, parses it, validates it and if it is a valid
machine load report, it enters the load in the machine loads
collection of the LMS class. That's pretty much everything you need to know
about how MLMS accepts machine loads from MLRS.
LRS starts one thread for reporting the current machine load. The worker's name
is ReportingWorker, and I'll refer to it as reporter. The
initialization code of this thread is to start monitoring the performance
counters, create a UDP socket and make it a member of the same multicast group
that MLMS's collector object has joined. In its thread loop, the reporter waits
a predefined amount of time, then gets the current machine load and sends it to
the multicast endpoint. A network device, called a "switch" then
dispatches the load to all machines that have joined the multicast group, i.e.
all MLMS collectors will receive the load, including the MLMS that runs on the
MLRS machine (if a MLMS has been installed and running there).
ReportingWorke
Here comes the most interesting part -- how LBL queries which is the machine
with the least load (the fastest machine). Well, it is quite simple and requires
only basic knowledge about .NET Remoting. If you don't understand Remoting, but
you do understand DCOM, assume that .NET Remoting compared to DCOM is what C++
is compared to C. You'll be quite close and at the same time quite far from what
Remoting really is, but you'll get the idea. (In fact, I've read several books
on DCOM, and some of them refered to it as "COM Remoting Infrastructure").
When MLMS starts, it registers a class named ServerLoadBalancer with
the Remoting runtime as a singleton (an object that is instantiated just once,
and further requests for its creation end up getting a reference to the same,
previously instantiated object). When a request to get the fastest machine comes
(GetLeastMachineLoad method gets called) the singleton asks the
MachineLoadsCollection object to return its least load, and then
hands it to the client object that made the remoted call.
Below is a story you would like to hear about remoted objects that need to have
parameter-less constructors. If you'd like to skip the story,
Now that all of you know that an object may be registered for remoting, probably
not many of you know that you do not have easy control over the object's
instantiation. Which means that you don't create an instance of the singleton
object and register it with the Remoting runtime, but rather the Remoting
runtime creates that object when it receives the first request for the object's
creation. Now, all server-activated objects must have a parameter-less
constructor, and the singleton is not an exception. But we want to pass our
ServerLoadBalancer class a reference to the machine loads collection.
I see only two ways to do that -- the first one is to register the object with
the Remoting runtime, create an instance of it via Remoting and call an
"internal" method Initialize, passing the machine loads
collection to it. At first that sounded like a good idea and I did it just like
that. Then I launched the client testing application first, and the server after
it. Can you guess what happened? The client managed to create the singleton
first, and it was not initialized -- boom!!! Not what we expected, right? So I
thought a bit how to find a workaround. Luckily, it occured to me how to hack
this problem. I decided to make a static member of the
LoadMonitoringServer class, which would hold the machine loads
collection. At the begining it would be a null reference, then
when the server starts, I would set it to the server's machine loads collection.
Now when our "parameter-less constructed" singleton object is
instantiated for the first time by the Remoting runtime, it would get the
machine loads via the LoadMonitoringServer::StaticMachineLoads
member variable and the whole problem has disappeared. I had to only mark the
static member variable as (private public) so it is visible only
within the assembly. I know my appoach is a hack, and if you know a better
pattern that solves my problem, I'll be happy to learn it.
Initialize
null
LoadMonitoringServer::StaticMachineLoads
private public
Here's another interesting issue. How does the client (LBL) compile against the
remoted ServerLoadBalancer class? Should it have a reference
(#using "...dll") to LML or what? Well, there is a solution to this
problem, and I haven't invented it, thought I'd like much:) I mentioned before,
that the SharedLibrary has some shared types, used by LBL, LMS and
LRS. No, it's not what you're thinking! I haven't put the
ServerLoadBalancer class there even if I wanted to, because it
requires the MachineLoadsCollection class, and the latter is located
in LML. What I consider an elegant solution, (and what I did) is defining an
interface in the SharedLibrary, which I implemented in the
ServerLoadBalancer class in LML. LBL tries to create the
ServerLoadBalancer via Remoting, but it does not explicitly try to
create a ServerLoadBalancer instance, but an instance, implementing
the ILoadBalancer interface. That's how it works. LBL
creates/activates the singleton on the LMS side via Remoting and calls its
GetLeastMachineLoad method to determine the fastest machine.
Below is a list of helper classes that are cool, reusable or worth to mention.
I'll try to explain their cool sides, but you should definitely peek at the
source code to see them:)
I like the .NET configuration classes very much, and I hate reinventing the
wheel, but this class is a specific configuration class for this solution and is
cooler than .NET configuration class in at least one point. What makes the class
cooler, is that it can notify certain objects when the configuration changes,
i.e. the underlying configuration file has been modified with some text editor.
So I've built my own configurator class, which uses the FileSystemWatcher class
to sniff for writes in the configuration file, and when the file changes, the
configurator object re-loads the file, and raises an event to all subscribers
that need to know about the change. These subscribers are only two, and they are
the Load Monitoring and Reporting servers. When they receive the event, they
restart themselves, so they can reflect the latest changes immediately.
I used to call this class a "struct" one. I wasn't fair to it :), as it is one
of the most important classes in the solution. It wraps a PerformanceCounter
object in it, retrieves some sample values, and stores them in a cyclic queue.
What is a cyclic queue? Well, I guess there's no such animal :) but as I have
"invented" it, let's explain you what it is. It is a simple queue with finite
number of elements allowed to be added. When the queue "overflows", it pops up
the first element, and pushes the new element into the queue. Here's an example
of storing the numbers from 1 to 7 in a 5-element cyclic queue:
Pass Queue Running Total (Sum)
---- ----- -------------------
[] = 0
1 [1] = 0 + 1 = 1
2 [2 1] = 1 + 2 = 3
3 [3 2 1] = 3 + 3 = 6
4 [4 3 2 1] = 6 + 4 = 10
5 [5 4 3 2 1] = 10 + 5 = 15
6 [6 5 4 3 2] = 15 - 1 + 6 = 20
7 [7 6 5 4 3] = 20 - 2 + 7 = 25
Why do I need the cyclic queue? To have a limited state of each monitored
performance counter, of course. If pass 5 was the state of the counter 3 seconds
ago, the its average was 15/5 = 3, and if now we are at pass 7, the counter's
average is 20/5 = 4. Sounds reallistic, doesn't it? So we use the cyclic queue
to store the transitory counter samples and know its average for the past N
samples which were measured for the past M seconds. You see how easy is calculated
the running sum. Now the only thing a counter should do to tell its average is ro
divide the running sum to the number of sample values it had collected. You know
that the machine load is the sum of the weigted averages of all monitored performance
counters for the given machine. But you might ask, what happens in the following
situation:
We have two machines: A and B. Both are measuring just one counter, their CPU
utilization. A Machine Load Monitoring Server is running on a third machine C,
and a load balancing client is on fourth machine D. A and B's Load Reporting
Servers are just started. Their CounterInfo classes have recorded respectively
50 and 100 (because the administrator on machine B has just launched IE:). A and
B are configured to report each second, but they should report the weighted
averages of 5 sample values. 1 second elapses, but both A and B has collected
only 1 sample value. Now D asks C which is the least loaded machine. Which one
should be reported? A or B? The answer is simple: None. No machine is allowed to
report its load unless it has collected the necessary number of sample values
for all performance counters. That means, that unless A and B has filled up
their cyclic queues for the very first time, they block and don't return their
weighted average to the caller (the LRS's reporter worker).
This class is probably more tricky than interesting. Generally, it is used to
store the loads, that one or more LRS report to LMS. That's the class' dumb
side. One cool side of the class is that it stores the loads in 3 different data
structures to simulate one, that is missing in the .NET BCL - a priority queue
that can store multiple elements with the same key, or in STL terms, something
like
std::priority_queue <std::vector <X *>, ... >
I know that C++ die-hards know it by heart, but for the rest of the audience:
std::priority_queue is. I took
the definition from MSDN, but I'd like to correct it a little bit: you should
read "which is always the largest or of the highest priority" as
"which is always what the less functor returns as largest or of
the highest priority". At the beginning, I thought to use the
priority_queue template class, and put there
"gcroot"-ed references, but then I thought that it would
be more confusing and difficult than helping me, and you, the reader. Do you know
what the "gcroot" template does? No? Nevermind then:) In
.NET BCL classes, we have something which is very similiar to a priority queue -- that's the
SortedList class in System::Collections. Because it
can store any Object-based instances, we could put ArrayList
references in it to simulate a priority queue that stores multiple elements with
the same key. There's also a Hashtable to help us solve certain
problems, but we'll get to it in a minute. Meanwhile, keep reading to understand
why I need these data structures in the first place.
std::priority_queue
priority_queue
less
"gcroot"
SortedList
System::Collections
Object
ArrayList
Hashtable
Machine loads do not enter the machine loads collection by name, i.e. they are
added to the loads collection with the key, being the machine's load. That's why
before each machine reports its load, it converts the latter to unsigned long
and then transmits it over the wire to LMS. It helps restricting the number of
stored loads, e.g. if machine A has a load of 20.1, and machine B has a load of
20.2, then the collection considers the loads as equal. When LMS "gets" the
load, it adds it in the SortedList, i.e. if we have three
machines -- "A", "B", and "C" with loads 40, 20
and 30, then the SortedList looks like:
[B:20][C:30][A:40]
If anyone asks for the fastest machine, we always return the 1st positional
element in the sorted list, (because it is sorted in ascending order).
Well, I'd like it to be so simple, but it isn't. What happens when a 4th
machine, "D" reports a load 20? You should have guessed by now why I need to
store an ArrayList for each load, so here is it in action -- it stored the loads
of machines B and D:
[D:20]
[B:20][C:30][A:40]
Now, if anyone asks for the fastest machine, we will return the first element of
the ArrayList, that is stored in the first element of the SortedList, right? It
is machine "B".
ArrayLis
But then what happens when machine "B" reports another load, equal to 40? Shall
we leave the first reported load? Of course, not! Otherwise, we will return "B"
as the fastest machine, where "D" would be the one with the least load. So we
should remove machine "B"'s older load from the first ArrayList and insert its
new load, wherever is appropriate. Here's the data structure then:
[B:40]
[D:20][C:30][A:40]
Now how did you find machine "B"'s older load in order to remove it?
Eh? I guess with your eyes. Here's where we need that Hashtable I mentioned
above. It is a mapping between a machine's older load and the list it resides in
currently. So when we add a machine load, we first check whether the machine has
reported a load before, and if it did, we find the ArrayList, where
the old load was placed, remove it from the list, and add the new load to a new
list, right? Wrong. We have one more thing to do, but first let me show you the
problem, and you'll guess what else I've done to make the collection work as expected.
Imagine that machine "D" reports a new load -- 45. Now you'll say that
the data now looks like the one below:
[B:40]
[C:30][A:40][D:45]
You wish it looks like this! But that's because I made a mistake when I was
trying to visualize the first loads. Actually the previous loads collection
looked like this:
^
|
M
A
C . . . .
H . . . .
I . . . .
N . . . .
E . . B .
S D C A .
LOAD 20 30 40 . . . -->
So you now will agree, that the collection actually looks like this:
^
|
M
A
C . . . .
H . . . .
I . . . .
N . . . .
E . . B .
S . C A D
LOAD 20 30 40 45 . . -->
Yes, the first list is empty, and when a request to find the least loaded
machine comes and you try to pop up the first element of the
ArrayList for load 20 (which is the least load), you'll get
IndexOutOfRangeException, as I got it a couple of times before I
debugged to understand what was happenning. So when we remove an old load from
an ArrayList, we should check whether it has orphaned (is now empty),
and if this is the case, we should remove the ArrayList from the
SortedList as well.
IndexOutOfRangeException
Here's the code for the Add method:
Add
void MachineLoadsCollection::Add (MachineLoad __gc* machineLoad)
{
DEBUG_ASSERT (0 != machineLoad);
if (0 == machineLoad)
return;
String __gc* name = machineLoad->Name;
double load = machineLoad->Load;
Object __gc* boxedLoad = __box (load);
rwLock->AcquireWriterLock (Timeout::Infinite);
// a list of all machines that have reported this particular
// load value
//
ArrayList __gc* loadList = 0;
// check whether any machine has reported such a load
//
if (!loads->ContainsKey (boxedLoad))
{
// no, this is the first load with this value - create new list
// and add the list to the main loads (sorted) list
//
loadList = new ArrayList ();
loads->Add (boxedLoad, loadList);
}
else
{
// yes, one or more machines reported the same load already
//
loadList = static_cast<ArrayList __gc*> (loads->get_Item (boxedLoad));
}
// check if this machine has already reported a load previously
//
if (!mappings->ContainsKey (name))
{
// no, the machine is reporting for the first time
// insert the element and add the machine to the mappings
//
loadList->Add (machineLoad);
mappings->Add (name, new LoadMapping (machineLoad, loadList));
}
else
{
// yes, the machine has reported its load before
// we should remove the old load; get its mapping
//
LoadMapping __gc* mappedLoad =
static_cast<LoadMapping __gc*> (mappings->get_Item (name));
// get the old load, and the list we should remove it from
//
MachineLoad __gc* oldLoad = mappedLoad->Load;
ArrayList __gc* oldList = mappedLoad->LoadList;
// remove the old mapping
//
mappings->Remove (name);
// remove the old load from the old list
//
int index = oldList->IndexOf (oldLoad);
oldList->RemoveAt (index);
// insert the new load into the new list
//
loadList->Add (machineLoad);
// update the mappings
//
mappings->Add (name, new LoadMapping (machineLoad, loadList));
// finally, check if the old load list is totally empty
// and if so, remove it from the main (sorted) list
//
if (oldList->Count == 0)
loads->Remove (__box (oldLoad->Load));
}
rwLock->ReleaseWriterLock ();
}
Now, for the curious, here's the get_MinimumLoad property's code:
get_MinimumLoad
MachineLoad __gc* MachineLoadsCollection::get_MinimumLoad ()
{
MachineLoad __gc* load = 0;
rwLock->AcquireReaderLock (Timeout::Infinite);
// if the collection is empty, no machine has reported
// its machineLoad, so we return "null"
//
if (loads->Count > 0)
{
// the 1st element should contain one of the least
// loaded machines -- they all have the same load
// in this list
//
ArrayList __gc* minLoadedMachines =
static_cast<ArrayList __gc*> (loads->GetByIndex (0));
load = static_cast<MachineLoad __gc*> (minLoadedMachines->get_Item (0));
}
rwLock->ReleaseReaderLock ();
return (load);
}
Well, that's prety much about how the MachineLoadsCollection class works in
order to store the machine loads, and return the least loaded machine. Now we
will see what else is cool about this class. I called it the Grim Reaper, and
that's what it is -- a method, named GrimReaper (GR), that runs
asynchronously (using a Timer class) and kills dead machines!:) Seriously,
GR knows the interval at which each machine, once reported a load, should report
it again. If a machine fails to report its load in a timely manner it is removed
from the MachineLoadsCollection container. In this way, we guarantee
that a machine, that is now dead (or is disconnected from the network) will not
be returned as the fastest machine, at least not before it reports again (it is
brought back to the load balancing then). However, in only about 30 lines of
code, I managed to made two mistakes in the GR code. The first one was very
lame -- I was trying to remove an element from a hash table while I was iterating
over its elements, but the second was a real bich! However, I found it quite
quickly, because I love console applications:) I was outputting a start (*) when
GR was executing, and a caret (^) when it was killing a machine. I then observed
that even if the (only) machine was reporting regularly its load, at some time,
GR was killing it! I was staring at the console at least for 3 minutes. The GR
code was simple, and I thought that there's no chance to make a mistake there. I
was wrong. It occured to me that I wasn't considering the fact, that the GR code
takes some time to execute. It was running fast enough, but it was taking some
interval of time. Well, during that time, GR was locking the machine loads
collection. And while the collection was locked, the collector worker was blocked,
waiting for the collection to be unlocked, so it can enter the newly received
load ther. So when the collection was finally unlocked at the end of the GR
code, the collector entered the machine's load. You can guess what happens when
the GR is configured to run in shorter intervals and the machines report in
longer intervals. GR locks, and locks and locks, while the collector blocks, and
blocks and blocks, until a machine is delayed by the GR itself. However, because
GR is oblivious to the outer world, it thinks that the machine is a dead one, so
it removes the machine from the load balancing, until the next time it reports a
brand new load. My solution for this issue? I have it in my head, but I'll
implement it in the next version of the article, because I really ran out of
time. (I couldn't post the article for the November's contest, because I
couldn't finish this text in time. It looks that writing text in plain English is
more difficult than writing Managed C++ code, and I don't want to miss December's
contest too:)
GrimReaper
Timer
If anyone is interested, here is Grim Reaper's code:
void MachineLoadsCollection::GrimReaper (Object __gc* state)
{
// get the state we need to continue
//
MachineLoadsCollection __gc* mlc = static_cast<MachineLoadsCollection __gc*> (state);
// temporarily suspend the timer
//
mlc->grimReaper->Change (Timeout::Infinite, Timeout::Infinite);
// check if we are forced to stop
//
if (!mlc->keepGrimReaperAlive)
return;
// get the rest of the fields to do our work
//
ReaderWriterLock __gc* rwLock = mlc->rwLock;
SortedList __gc* loads = mlc->loads;
Hashtable __gc* mappings = mlc->mappings;
int reportTimeout = mlc->reportTimeout;
rwLock->AcquireWriterLock (Timeout::Infinite);
// Bring out the dead :)
//
// enumerating via an IDictionaryEnumerator, we can't delete
// elements from the hashtable mappings; so we create a temporary
// list of machines for deletion, and delete them after we have
// finished with the enumeration
//
StringCollection __gc* deadMachines = new StringCollection ();
// walk the mappings to get all machines
//
DateTime dtNow = DateTime::Now;
IDictionaryEnumerator __gc* dic = mappings->GetEnumerator ();
while (dic->MoveNext ())
{
LoadMapping __gc* map = static_cast<LoadMapping __gc*> (dic->Value);
// check whether the dead timeout has expired for this machine
//
TimeSpan tsDifference = dtNow.Subtract (map->LastReport);
double difference = tsDifference.TotalMilliseconds;
if (difference > (double) reportTimeout)
{
// remove the machine from the data structures; it is
// now considered dead and does not participate anymore
// in the load balancing, unless it reports its load
// at some later time
//
String __gc* name = map->Load->Name;
// get the old load, and the list we should remove it from
//
MachineLoad __gc* oldLoad = map->Load;
ArrayList __gc* oldList = map->LoadList;
// remove the old mapping (only add it to the deletion list)
//
deadMachines->Add (name);
// remove the old load from the old list
//
int index = oldList->IndexOf (oldLoad);
oldList->RemoveAt (index);
// finally, check if the old load list is totally empty
// and if so, remove it from the main list
//
if (oldList->Count == 0)
loads->Remove (__box (oldLoad->Load));
}
}
// actually remove the dead machines from the mappings
//
for (int i=0; i<deadMachines->Count; i++)
mappings->Remove (deadMachines->get_Item (i));
// cleanup
//
deadMachines->Clear ();
rwLock->ReleaseWriterLock ();
// resume the timer
//
mlc->grimReaper->Change (reportTimeout, reportTimeout);
}
I've built a super simple .NET Web application (in C#), that uses LBL to perform
a load balancing in a web farm. Though the application is very little, it is
interesting and deserves some space in this article, so here we go. First, I've
written a class that wraps the load balancing class ClientLoadBalancer
from LBL, named it Helper, and implemented it as a singleton so the
Global class of the web application and the web page classes could
see one instance of it. Then I used it in the Session_OnStart method
of the Global class to redirect every new session's first HTTP
request to the most available machine. Furthermore, in the sample web page, I've
used it again to dynamically build URLs for further processing, replacing the
local host again with the fastest machine. Now one may argue (and he might be
right) that a user can spend a lot of time reading that page, so when he
eventually clicks on the "faster" link, the previously faster machine
could not be the fastest one at that time. Just don't forget that hitting another
machine's web application will cause its Session_OnStart trigger
again, so anyway, the user will be redirected to the fastest machine. Now, if
you don't get what am I talking about, that's because I haven't shown any code
yet. So here it its:
ClientLoadBalancer
Helper
Global
Session_OnStart
protected void Session_Start (object sender, EventArgs e)
{
// get the fastest machine from the load balancer
//
string fastestMachineName = Helper.Instance.GetFastestMachineName ();
// we should check whether the fastest machine is not the machine,
// this web application is running on, as then there'll be no sence
// to redirect the request
//
string thisMachineName = Environment.MachineName;
if (String.Compare (thisMachineName, fastestMachineName, false) != 0)
{
// it is another machine and we should redirect the request
//
string fasterUrl = Helper.Instance.ReplaceHostInUrl (
Request.Url.ToString (),
fastestMachineName);
Response.Redirect (fasterUrl);
}
}
And here's the code in the sample web page:
private void OnPageLoad (object sender, EventArgs e)
{
// get the fastest machine and generate the new links with it
//
string fastestMachineName = Helper.Instance.GetFastestMachineName ();
link.Text = String.Format (
"Next request will be processed by machine '{0}'",
fastestMachineName);
// navigate to the same URL, but the host being the fastest machine
//
link.NavigateUrl = Helper.Instance.ReplaceHostInUrl (
Request.Url.ToString (),
fastestMachineName);
}
If you think that I hardcoded the settings in the Helper class,
you are wrong. First, I hate hardcoded or magic values in my code (though you
may see some in an article like this). Second, I was testing the solution on
my coleagues' computers, so writing several lines of code in advance, helped
me to avoid the inevitable otherwise re-compilations. I just deployed the
web application there. Here's the trivial C# code of the Helper
class (note that I have hardcoded the keys in Web.config file ;-)
Web.config
class Helper
{
private Helper ()
{
// assume failure(s)
//
loadBalancer = null;
try
{
NameValueCollection settings = ConfigurationSettings.AppSettings;
// assume that MLMS is running on our machine and the web app
// is configured to create its remoted object using the defaults;
// if the user has configured another machine in the Web.config
// running MLMS, try to get its settings and create the remoted
// object on it
//
string machine = Environment.MachineName;
int port = 14000;
RemotingProtocol protocol = RemotingProtocol.TCP;
string machineName = settings ["LoadBalancingMachine"];
if (machineName != null)
machine = machineName;
string machinePort = settings ["LoadBalancingPort"];
if (machinePort != null)
{
try
{
port = int.Parse (machinePort);
}
catch (FormatException)
{
}
}
string machineProto = settings ["LoadBalancingProtocol"];
if (machineProto != null)
{
try
{
protocol = (RemotingProtocol) Enum.Parse (
typeof (RemotingProtocol),
machineProto,
true);
}
catch (ArgumentException)
{
}
}
// create a proxy to the remoted object
//
loadBalancer = new ClientLoadBalancer (
machine,
protocol,
port);
}
catch (Exception e)
{
if (e is OutOfMemoryException || e is ExecutionEngineException)
throw;
}
}
public string GetFastestMachineName ()
{
// assume that the load balancing could not be created or it will fail
//
string fastestMachineName = Environment.MachineName;
if (loadBalancer != null)
{
MachineLoad load = loadBalancer.GetLeastMachineLoad ();
if (load != null)
fastestMachineName = load.Name;
}
return (fastestMachineName);
}
public string ReplaceHostInUrl (string url, string newHost)
{
Uri uri = new Uri (url);
bool hasUserInfo = uri.UserInfo.Length > 0;
string credentials = hasUserInfo ? uri.UserInfo : "";
string newUrl = String.Format (
"{0}{1}{2}{3}:{4}{5}",
uri.Scheme,
Uri.SchemeDelimiter,
credentials,
newHost,
uri.Port,
uri.PathAndQuery);
return (newUrl);
}
public static Helper Instance
{
get { return (instance); }
}
private ClientLoadBalancer loadBalancer;
private static Helper instance = new Helper ();
} // Helper
If you wonder how the servers look like when running, and what a great
look and feel I've designed for the web application, here's a screenshot to
disappoint you:)
There's a little trick you need to do, in order to load the solution file.
Open your IIS administration console (Start/Run... type inetmgr) and
create a new virtual directory LoadBalancingWebTest. when you're asked
about the folder, choose X:\Path\To\SolutionFolder\LoadBalancingWebTest.
You can now open the solution file (SoftwareLoadBalancing.sln) with no
problems. Load it in Visual Studio .NET, build the SharedLibrary project
first, as the others depend on it, then build LML and LRS, and then the whole solution.
Note that the setup projects won't build automatically so you should select and build
them manually.
inetmgr
LoadBalancingWebTest
X:\Path\To\SolutionFolder\LoadBalancingWebTest
SoftwareLoadBalancing.sln
Note:
When you compile the solution, you will get 15 warnings. All of them state:
warning C4935: assembly access specifier modified from 'xxx', where
xxx could be private or public. I don't know
how to make the compiler stop complaining about this. There are no other warnings
at level 4. Sorry if these embarass you.
warning C4935: assembly access specifier modified from 'xxx'
xxx
private
public
That's it if you have VS.NET. If you don't, you can compile only the web application,
as it is written in C# and can be compiled with the free C# compiler, coming with the
.NET framework. Otherwise, buy a copy of VS.NET, and become a CodeProject (and
Microsoft) supporter :) BTW, I realized right now, that I should write my next
articles in C#, so the "poor" guys like me can have some fun too. I'm sorry
guys! I promise to use C# in most of the next articles I attempt to write.
If you look at the Common.h header, located in the SharedFiles
folder in the solution, you'll notice that I've copied and pasted the meaning of
all configuration keys from that file. However, because I know you won't look at
it until you've liked the article (and it's high time do so, as it is comming to
its end:), here's the explanation of the XML configuration file, and various
macros in Common.h.
Common.h
SharedFiles
This header file is used by almost all projects in the solution. It has several
(helpful) macros I'm about to discuss, so if you're in the mood to read about them,
go ahead. Otherwise, click here to read only about the
XML configuration file.
First, I'm going to discuss the .NET member access modifiers. There are 5 of
them, though you may use only four of them, unless you are writing IL code.
Existing languages refer to them in a different way, so I'll give you a
comparison table of their names and some explanations.
Because I like most the C# keywords, I #defined and used thoughout
the code four macros to avoid typing the double keywords in MC++:
#define
#define PUBLIC public public
#define PRIVATE private private
#define PROTECTED public protected
#define INTERNAL private public
Here comes the more interesting "stuff". You have three options for
communication between a load reporting and monitoring servers: via UDP +
multicasting, UDP-only, or TCP. BTW, if I was writing the article in C#, you
wouldn't have them. Really! C# is so lame in preprocessing, and the compiler
writers were so wrong that they did not include some real preprocessing
capabilities in the compiler, that I have no words! Nevertheless, I wrote the
article in MC++, so I have the cool #define directives I needed so
badly, when I started to write the communication code of the classes. There are
two macros you can play with, to make the solution use one communication protocol
or another, and/or disable/enable multicasting. Here are their definitions:
#define USING_UDP 1
#define USING_MULTICASTS 1
Now, a C# guru:) will argue that I could still write the protocol-independent
code with several pairs of #ifdef and #endif directives.
To tell you the truth, I'm not a fan of this coding style. I'd rather define a
generic macro in such an #if block, and use it everywhere I need it.
So that's what I did. I've written macros that create TCP or UDP sockets, connect
to remote endpoints, and send and receive data via UDP and TCP. Then I wrote
several generic macros that follow the pattern below:
#ifdef
#endif
#if
#if defined(USING_UDP)
# define SOCKET_CREATE(sock) SOCKET_CREATE_UDP(sock)
#else
# define SOCKET_CREATE(sock) SOCKET_CREATE_TCP(sock)
#endif
You get the idea, right? No #ifdefs inside the real code.
I just write SOCKET_CREATE (socket); and the preprocessor
generates the code to create the appropriate socket. Here's another good macro,
I use for exception handling, but before that I'll give you some rules (you
probably know) about .NET exception handling:
SOCKET_CREATE (socket);
ArgumentNullException
ArgumentOutOfRangeException
OutOfMemoryException
ExecutionEngineException
Because I'm not writing production code here, I allowed myself to catch
(in most of the source code) all possible exceptions, when I don't need to handle
them except to know that something went bad. So I catch the base class
Exception. This violates all rules, I've written above, but I
wrote some code to fit into the second and third one -- if I catch an
OutOfMemoryException or ExecutionEngineException, I
re-throw it immediately. Here's the macro I call, after I catch the generic
Exception class:
Exception
#define TRACE_EXCEPTION_AND_RETHROW_IF_NEEDED(e) \
System::Type __gc* exType = e->GetType (); \
if (exType == __typeof (OutOfMemoryException) || \
exType == __typeof (ExecutionEngineException)) \
throw; \
Console::WriteLine ( \
S"\n{0}\n{1} ({2}/{3}): {4}\n{0}", \
new String (L'-', 79), \
new String ((char *) __FUNCTION__), \
new String ((char *) __FILE__), \
__box (__LINE__), \
e->Message);
And finally, a word about assertions. C has assert macro, VB had
Debug.Assert method, .NET has a static method Assert
in the Debug class too. One of the overloads of the method takes
a boolean expression, and a string, describing the test. C's assert
is smarter. It just needs an expression, and it builds the string, containing the
expression automatically by stringizing the expression. Now, I really hate the
fact, that C# lacks some real preprocessing features. However, MC++ (thanks God!)
was not slaughtered by the compiler writers (long live legacy code support), so
here's my .NET version of the C's assert macro:
assert
Debug.Assert
Assert
Debug
#define DEBUG_ASSERT(x) Debug::Assert (x, S#x)
If I was writing in C# the code for this article, I should have typed
Debug.Assert (null != objRef, "null != objRef");
DEBUG_ASSERT (0 != objRef);
Debug::Assert (0 != objRef, S"0 != objRef");
__LINE__
__FILE__
__FUNCTION__
DEBUG_ASSERT
I know you're all smart guys (otherwise what the heck are you doing on
CodeProject?:), and smart guys don't need lengthy explanations, all they need is
to take a look at an example. So here it is -- the XML configuration file, used
by both the Machine Load Monitoring and Reporting servers. The explanation of all
elements is given below the file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<<code>LoadReportingServer</code>>
<IpAddress>127.0.0.1</IpAddress>
<Port>12000</Port>
<ReportingInterval>2000</ReportingInterval>
</<code>LoadReportingServer</code>>
<<code>LoadMonitoringServer</code>>
<IpAddress>127.0.0.1</IpAddress>
<CollectorPort>12000</CollectorPort>
<CollectorBacklog>40</CollectorBacklog>
<ReporterPort>13000</ReporterPort>
<ReporterBacklog>40</ReporterBacklog>
<MachineReportTimeout>4000</MachineReportTimeout>
<RemotingProtocol>tcp</RemotingProtocol>
<RemotingChannelPort>14000</RemotingChannelPort>
<PerformanceCounters>
<counter alias="cpu"
category="Processor"
name="% Processor Time"
instance="_Total"
load-
<-- ... -->
</PerformanceCounters>
</<code>LoadMonitoringServer</code>>
</configuration>
Even though you're smart, I know that some of you have some questions, I am
about to answer. First, I'm going to explain the purpose of all elements and
their attributes, and I'll cover some wierd settings, so read on...
(to save some space, I'll refer to the element LoadReportingServer
as LRS, and I'll write LMS instead of
LoadMonitoringServer).
LRS
LMS
LRS/IpAddress
LMS/IpAddress
LRS/Port
LRS/ReportingInterval
ReportingInterval
counter
interval
LMS/CollectorPort
LMS/CollectorBacklog
LMS/ReporterPort
GetLeastLoadedMachine
ReporterWorker.h/.cpp
LMS/ReporterBacklog
LMS/MachineReportTimeout
MachineReportTimeout
LMS/RemotingProtocol
LMS/RemotingChannelPort
LMS/PerformanceCounters
counter/alias
counter/category
Processor
Memory
counter/name
% Processor Time
Page reads/sec
counter/instance
instance
counter/load-weight
Processor\% Processor Time\_Total
Processor\% User Time\_Total
counter/interval
counter/maximum-measures
maximum-measures
Which is "the other configuration file"? Well, it is the
Web.config file in the sample load-balanced web application. It
has 3 vital keys defined in the appSettings section. They are the
machine on which MLMS runs, and the Remoting port and protocol where the machine
has registered its remoted object.
appSettings
<appSettings>
<add key="LoadBalancingMachine" value="..." />
<add key="LoadBalancingPort" value="..." />
<add key="LoadBalancingProtocol" value="..." />
</appSettings>
You can figure out what the keys mean, as you have seen the code in the
Helper class of the web application. The last key accepts a string,
which can be either "TCP" or "HTTP" and nothing else.
There are 7 ways to deploy the solution onto a single machine. That's right -- seven.
To shorten the article and lengthen my life, I'll refer to the Machine Load Monitoring
Server as LMS, to the Machine Load Reporting Server as LRS, and the Load Balancing
Library as LBL. Here're the variations:
It is you, who decide what to install and where. But is me, who developed the
setup projects, so you have to pay some attention to what I'm about to tell you.
There are 4 setups. The first one is for sample load-balanced web application.
The second one is for the server part of the solution, i.e. the Machine Load
Monitoring and Reporting Servers. They're bundled in one single setup, but it's
your call which one you run, once you've installed them. The 3rd setup contains
only the load balancing library and the 4th one contains the entire source code
of the solution, including the source for the setups.
Here is a simple scenario to test whether the code works: (you should have setup
a multicast group on your LAN or ask an admin to do that). We'll use 2 machines --
A and B. On machine A, build the SharedLibrary project first, then
build the whole solution (you may skip the setup projects). Deploy the web
application. Modify the XML configuration file for MLMS and MRLS. Run the servers.
Deploy the web application, modify its Web.config file and launch it.
Click on the web page's link. It should work, and the load balancing should
redirect you to the same machine (A). Now deploy only MLRS, and the web
application to machine B. Modify the configuration files, but this time, in
Web.config, set the LoadBalancingMachine key to
"A". You've just explained to B's LBL to use machine A's remoted
load balancing object. Run MLRS on machine B. It should start to report B's
load to A's MLMS. Now do some CPU-intensive operation (if < WinXP, right-click
the Desktop and drag your mouse behind the Task Bar; this should give you about
100% CPU utilization) on machine A. Its web application should redirect you to
the web app on machine B. Now stop the B's MLRS server. Launch B's web
application. It should redirect you to A's one. I guess that's it. Enjoy playing
around with all possible deployment scenarios:)
LoadBalancingMachine
There's nothing easier than converting pure managed C++ code to C#. Just press
Ctrl-H in your mind and replace the following sequences (this will work only for
my source files, as other developers may not use the whitespace in the same way
I use it).
MC++ C#
---- ----
:: .
-> .
__gc*
__gc
__sealed __value
using namespace using
: public :
S" "
__box (x) x
While the replacements above will translate 85% of the code, there're several
things you should do manually:
#if !defined (...) ... #define ... #endif
static_cast<SomeType __gc*> (expression) to
((SomeType) expression) or (expression as SomeType)
PUBLIC:
... Method1 (...) {...}
... Variable1;
PRIVATE:
... Method3 (...) {...}
public ... Method1 (...) {...}
public ... Variable1;
private ... Method3 (...) {...}
It is really frustrating that MC++ does not have an equivalent of C#'s
readonly fields (not properties). In C# one could write the following
class:
public class PerfCounter
{
public PerfCounter (String fullPath, int sampleInterval)
{
// validate parameters
//
Debug.Assert (null != fullPath);
if (null == fullPath)
throw (new ArgumentNullException ("fullPath"));
Debug.Assert (sampleInterval > 0);
if (sampleInterval <= 0)
throw (new ArgumentOutOfRangeException ("sampleInterval"));
// assign the values to the readonly fields
//
FullPath = fullPath;
SampleInterval = sampleInterval;
}
// these are marked public, and make a great replacement of
// read-only (getter) properties
//
public readonly String FullPath;
public readonly int SampleInterval;
}
You see that the C# programmer doesn't have to implement read-only properties,
because the readonly fields are good enough. In Managed C++, you can simulate
the readonly fields, by writing the following class:
public __gc class PerfCounter
{
public:
PerfCounter (String __gc* fullPath, int sampleInterval) :
FullPath (fullPath),
SampleInterval (sampleInterval)
{
// validate parameters
//
Debug::Assert (0 != fullPath);
if (0 == fullPath)
throw (new ArgumentNullException (S"fullPath"));
Debug::Assert (sampleInterval > 0);
if (sampleInterval <= 0)
throw (new ArgumentOutOfRangeException (S"sampleInterval"));
// the values have been assigned in the initialization list
// of the constructor, we have nothing more to do -- COOL!>
//
}
public:
const String __gc* FullPath;
const int SampleInterval;
};
So far, so good. You're probably wondering why I am complaining about MC++.
It looks like the MC++ version is even cooler than the C# one. Well, the example
class was too simple. Now, imagine that when you find an invalid parameter, you
should change it to a default value, like in the C# class below:
public class PerfCounter
{
public PerfCounter (String fullPath, int sampleInterval)
{
// validate parameters
//
Debug.Assert (null != fullPath);
if (null == fullPath)
throw (new ArgumentNullException ("fullPath"));
Debug.Assert (sampleInterval > 0);
// change to a reasonable default value
//
if (sampleInterval <= 0)
sampleInterval = DefaultSampleInterval;
// you can STILL assign the values to the readonly fields
//
FullPath = fullPath;
SampleInterval = sampleInterval;
}
public readonly String FullPath;
public readonly int SampleInterval;
private const int DefaultSampleInterval = 1000;
}
Now, the corresponding MC++ code will not compile, and you'll see why below:
public __gc class CrashingPerfCounter
{
public:
CrashingPerfCounter (String __gc* fullPath, int sampleInterval) :
FullPath (fullPath),
SampleInterval (sampleInterval)
{
// validate parameters
//
Debug::Assert (0 != fullPath);
if (0 == fullPath)
throw (new ArgumentNullException (S"fullPath"));
Debug::Assert (sampleInterval > 0);
// the second line below will cause the compiler to
// report "error C2166: l-value specifies const object"
//
if (sampleInterval <= 0)
SampleInterval = DefaultSampleInterval;
// the values have been assigned in the initialization list
// of the constructor, and that's the only place we can
// initialize non-static const members -- NOT COOL!
//
}
public:
const String __gc* FullPath;
const int SampleInterval;
private:
static const int DefaultSampleInterval = 1000;
};
Now, one may argue, that we could initialize the const member SampleInterval
in the initialization list of the constructor like this:
SampleInterval (sampleInterval > 0 ? sampleInterval : DefaultSampleInteval)
and he would be right. However, if we need to connect to a database first, in
order to do the check, or we need to perform several checks for the parameter I
can't figure out how to do this in the initialization list. Do you? That's why
MC++ sucks compared to C# for readonly fields. Now, the programmer is forced to
make the const fields non-const and private, and write code to implement read-only
properties, like this:
public __gc class LamePerfCounter
{
public:
LamePerfCounter (String __gc* fullPath, int sampleInterval)
{
// validate parameters
//
Debug::Assert (0 != fullPath);
if (0 == fullPath)
throw (new ArgumentNullException (S"fullPath"));
Debug::Assert (sampleInterval > 0);
if (sampleInterval <= 0)
sampleInterval = DefaultSampleInterval;
// assign the values to the member variables
//
this->fullPath = fullPath;
this->sampleInterval = sampleInterval;
}
__property String __gc* get_FullPath ()
{
return (fullPath);
}
__property int get_SampleInterval ()
{
return (sampleInterval);
}
private:
String __gc* fullPath;
int sampleInterval;
static const int DefaultSampleInterval = 1000;
};
John Robins
"I trust that I and my colleagues will use my code correctly. To avoid bugs,
however, I verify everything. I verify the data that others pass into my code, I
verify my code's internal manipulations, I verify every assumption I make in my
code, I verify data my code passes to others, and I verify data coming back from
calls my code makes. If there's something to verify, I verify it. This obsessive
verification is nothing personal against my coworkers, and I don't have any
psychological problems (to speak of). It's just that I know where the bugs come
from; I also know that you can't let anything by without checking it if you want
to catch your bugs as early as you can."
John Robins
I do what John preaches in his book, and you should do it too. Trust me, but
verify my code. I think I have debugged my code thoroughly, and I haven't met
bugs in it since the day before yesterday (when I started to write the article).
However, if you see one of those nasty creatures, let me know. My e-mail is
stoyan_damov[at]hotmail.com.
Though I think I don't have bugs (statistically, I should have 8 bugs in the
4 KLOC) I'd love to share an amazing Microsoft bug with you. It
caused me quite some time to find it, but unfortunatelly, I was not able to
reproduce it, when it disappeared (yes! it disappeared) later. I've wrapped all
of my classes in the namespace SoftwareLoadBalancing. So far so good. Now I
have several shared classes in the SharedLibrary assembly. The Load Monitoring
Library uses one of these classes to do its job, so it is #using the SharedLibrary.
I was able to build LML several times, and then suddenly, the linker complained
that it cannot find the shared class I was using in the namespace
SoftwareLoadBalancing. I'll name that class X to save myself some typing. I
closed the solution, went to the Debug folder of the shared library, deleted
everything, deleted all files in the common Bin folder and tried again. Same
result! I let the linker grumble for three more tries and then launched the ILDAsm
tool. When I looked at the SharedLibrary.dll, I found that the class X was
"wrapped" twice in the namespace SoftwareLoadBalancing, i.e. it was now
SoftwareLoadBalancing::SoftwareLoadBalancing::X. Because I wanted to do some
tests and had no time to deal with the bug, I tried to alias the namespace in
LML like this:
SoftwareLoadBalancing
#using
Bin
SharedLibrary.dll
SoftwareLoadBalancing::SoftwareLoadBalancing::X
using namespace SLB = SoftwareLoadBalancing;
Then, I tried to access the X class, using the following construct:
SLB::SLB::X __gc* x = new SLB::SLB::X ();
Maybe I don't understand C++ namespace aliasing very well, or maybe the
documentation does not explain it, but what happened this time was that the
linker complained again, that it can't find SoftwareLoadBalancing::SLB::X
class!!! The compiler "replaced" SLB with SoftwareLoadBalancing only once.
Needless to say, I was quite embarassed. Not only the compiler put my class
wrapped in two namespaces, but it was not helping me to work around the
problem!:) Do you know what I did then? I aliased the namespace in a way the
linker or compiler should understand:
SoftwareLoadBalancing::SLB::X
using namespace SLB = SoftwareLoadBalancing::SoftwareLoadBalancing;
Then, I tried to instantiate the X class like this:
SLB::X __gc* x = new SLB::X ();
I'm sure you don't know what happened then, because I was hiding a simple fact
from you. I was rebuilding each time. Now are you able to guess what happened?
The linker complained again that it cannot find class X in the namespace
SoftwareLoadBalancing::SoftwareLoadBalancing. WTF?! I was furious! I gone crazy!
I launched ILDasm once again, and looked at the SharedLibrary. The class
was properly wrapped once in the namespace SoftwareLoadBalancing. Now, I don't
know if this is a bug in the compiler or in the linker or in my mind. What I
know is that when I have such a problem next time, I won't go to chase
unexisting bugs in my source files, but will launch my love ILDasm and see
whether I'm doing something wrong, or Microsoft are trying to drive me crazy:)
SoftwareLoadBalancing::SoftwareLoadBalancing
(So what the heck have you done, when there're so much TODOs?!)
cpu * 0.2 + ((sessions < 10) * 0.2 + (sessions >= 10) * 0.5) * sessions
Thank you for reading the article! It was the longest article I've written in
my entire life (I started writing articles several months ago:) I'm really
impressed how patient you are! Now that I thanked you, I should also say
"Thanks!" to Microsoft, which brought us the marvelous .NET technology.
If .NET did not exist, I doubt if I would write such an article, and even if I
did, it wouldn't include the C++ source code. The .NET framework makes
programming so easy! It just forces you to write all day long:) I feel like I'm
not programming, but rather prototyping. It is easier than VB was once. Really!
Now let's see what you've learned (or just read) from the article:
AaaaaaaaaaaaaI forgot to tell you! Please do not post messages in the message
board below that teach me to not use __gc*, when I could just type
*. I just love the __gc keyword, that's it:)
__gc*
*
__gc
Below, there are two books, I've read once upon a time, that served me well to
write this article's source code. You'll be surprised that they are no .NET
books. I'm not joking -- there're maybe over 250 .NET books, and I've read 10 or
so, that's why I can't recommend you any .NET book, really. It wouldn't be fair
if I say "Book X is the best on topic Y" because I haven't read at least 1/2 of
the .NET books to give you an (authoritive) advice. The books below are not just
a "Must-Have" and "Must-Have-Read":) ones. They are priceless for the Windows
developer. Stop reading this article, and go buy them now! :)
Programming Server-Side Applications for Microsoft Windows 2000 (ISBN 0-7356-0753-2)
by Jeffrey Richter, Jason D. Clark
"We developers know that writing error-tolerant code is what we should do, but
frequently we view the required attention to detail as tedious and so omit it.
We've become complacent, thinking that the operating system will 'just take care
of us.' Many developers out there actually believe that memory is endless, and
that leaking various resources is OK because they know that the operatingm
system will clean up everything automatically when the process dies. Certainly
many applications are implemented in this way, and the results are not
devastating because the applications tend to run for short periods of time and
then are restarted. However, services run forever, and omitting the proper
error-recovery and resource-cleanup code is catastrophic!"
Debugging Applications (ISBN 0-7356-0886-5), by John Robins
"Bugs suck. Period. Bugs are the reason you endure death-march projects with
missed deadlines, late nights, and grouchy coworkers. Bugs can truly make your
life miserable because if enough of them creep in to your software, customers
will stop using your product and you could lose your job. Bugs are serious
business... As I was writing this book, NASA lost a Mars space probe because of
a bug that snuck in during the requirements and design phase. With computers
controlling more and more mission-critical systems, medical devices, and
superexpensive hardware, bugs can no longer be laughed at or viewed as something
that just happens as a part of development."
And the best text on Managed Extentions for C++ .NET (besides the specification
and the migration guide), which is not a book, but a Microsoft Official
Curriculum (MOC) course: "Programming with Managed Extensions for Microsoft
Visual C++ .NET" (2558). You should definitely visit this course if you're
planning to do any .NET development using Managed C++.
Many of you are probably wondering why I have implemented this solution in Managed C++,
and not in C# since I'm writing only managed code. I know that most of the .NET developers are on the C# bandwagon. So am I.
I'm programming in C# all day long. That's my job. However, I love C++ so much,
that I prefer to write in Managed C++. There are probably hundreds of reasons I prefer
MC++ to C#, and IJW (and unmanaged code in general) is the probably the last on the list. C# has
nothing to do with C or C++, except for some slight similarities in the syntax, no matter
that Microsoft are trying to convince us in the opposite. It is way closer to Java, than
to C/C++. Do I sound extreme? Well, a C/C++ die-hard coleague of mine
(Boby --) forced himself to learn and use VB.NET in order
to not forget C++ when he was developing a .NET application. Now who's extreme?:)
Microsoft are pushing us very badly to forget C++, so they and some open-source C++
die-hards are the only ones who use it:) Haven't you noticed? As of today, the ATL list
generates a couple of unique posts each day, compared to at least 10-20, several months
ago, before Microsoft suddenly decided to drop it, and put it back in a week, when
catcalled by the ATL community. And what does Microsoft say about this, eh? COM is not
dead! COM is here to stay! ATL lives (somewhere in time). Blah, blah:) I adore
.NET, but I don't want to search for the "The C Programming Language"
and "The C++ Programming Language" books in the dusty bookshelves in 3
or 4 years, when it will be replaced by some even-cooler technology. Long live
C++!:) Anyway, I was tempted to implement the solution in C#, because the monthly
prizes for it were better-looking:)
This software comes "AS IS" with all faults and with no warranties whatsoever.
If you find the source code or the article useful, wish me a Merry Christmas:)
Wishing you the merriest Christmas, and looking forward to seeing you next year:)
Stoyan
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
OnPageLoad
link.NavigateUrl = Helper.Instance.ReplaceHostInUrl (
Request.Url
...
link.NavigateUrl = Helper.Instance.ReplaceHostInUrl (
link.NavigateUrl
...
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/3338/NET-Dynamic-Software-Load-Balancing?msg=1487967 | CC-MAIN-2017-34 | refinedweb | 13,200 | 60.65 |
07 July 2008 03:58 [Source: ICIS news]
DUBAI (ICIS news)--Construction of Saudi International Petrochemical Co’s acetyls complex in Al-Jubail, Saudi Arabia, has reached 94% completion, Sipchem CEO Ahmad A al-Ohali said on Sunday.
?xml:namespace>
The commissioning of the project is expected to start by the end of this year, while production from acetic plant and vinyl acetate monomer will start in the second quarter of 2009.
The plant was originally planned to come on-stream in the first quarter of 2009 but experienced manpower shortage during the course of construction, said Al-Ohali about the slight delay of the project.
The Al-Jubail plant will produce about 340,000 tonnes/year of carbon monoxide making it the largest such plant in the world, and about 460,000 tonnes/year of acetic acid/acetic anhydride and 330,000 tonnes/year of VAM.
Technology for the complex was secured from US producers Eastman Chemicals for acetic acid and DuPont for VAM.
For more on acetyl | http://www.icis.com/Articles/2008/07/07/9138049/sipchem-al-jubail-acetyl-project-nears-completion.html | CC-MAIN-2014-35 | refinedweb | 169 | 62.51 |
* Raspberry Pi
– 1 * Breadboard
– 1 * Network cable (or USB wireless network adapter)
– 1 * Dual-color Common-Cathode LED module
– 1 * Photo-interrupter module
– Several jumper wires
Experimental Principle
Basically a photo-interrupter consists of two parts: transmitter and receiver. The transmitter (e.g., an LED or a laser) emits light and then the light goes to the receiver. If that light beam between the transmitter and receiver is interrupted by an obstacle, the receiver will detect no incoming light even for a moment and the output level will change. In this experiment, we will turn an LED on or off by using this change.
Experimental Procedures
Step 1: Build the circuit
Photo-interrupter Raspberry Pi
S ———————————– GPIO0
+ ———————————- 3.3V
– ———————————- GND
Dual-color LED module connection: connect pin R on dual-color LED module to GPIO1 of the Raspberry Pi; GND to GND
Step 2: Edit and save the code (see path/Rpi_SensorKit_code/14_lightBreak/lightBreak.c)
Step 3: Compile
gcc lightBreak.c -lwiringPi
Step 4: Run
./a.out
Block incident light with a piece of paper. The LED will light up and a string “led on” will be printed on the screen. Remove the paper and the LED will be off and a string “led off” will be printed on the screen.
lightBreak.c
#include <wiringPi.h> #include <stdio.h> #define LightBreakPin 0 #define LedPin 1(LightBreakPin, INPUT); pinMode(LedPin, OUTPUT); while(1){ if(digitalRead(LightBreakPin) == HIGH){ printf("led on !\n"); digitalWrite(LedPin, HIGH); //led on } else{ printf("led off !\n"); digitalWrite(LedPin, LOW); } } return 0; }
Python Code
#!/usr/bin/env python import RPi.GPIO as GPIO LightBreakPin = 11 LedPin = 12 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output GPIO.setup(LightBreakPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(LedPin, GPIO.LOW) # Set LedPin low to off led def swLed(channel): status = GPIO.input(LightBreakPin) print "LED: on" if status else "LED: off" GPIO.output(LedPin,status) def loop(): GPIO.add_event_detect(LightBreakPin, GPIO.BOTH, callback=swLed) # wait for falling while True: pass def destroy(): GPIO.output(LedPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy() | https://learn.sunfounder.com/lesson-13-photo-interrupter/ | CC-MAIN-2021-39 | refinedweb | 383 | 50.84 |
Network Working Group M. Mealling Request for Comments: 3404 VeriSign Obsoletes: 2915, 2168 October 2002 Category: Standards Track Dynamic Delegation Discovery System (DDDS) Part Four: The Uniform Resource Identifiers (URI) Resolution Mealling Standards Track [Page 1]
RFC 3404 DDDS Based URI Resolution October 2002] for background on the Knoxville framework and for additional information on the context and purpose of this proposal. Mealling Standards Track [Page 2]
RFC 3404 DDDS Based URI Resolution October 2002, the Domain Name System DDDS. This document describes URI Resolution as an application of the DDDS and specifies the use of at least one Database based on DNS. 3403 [3]. 3. The Distinction Between URNs and URIs. Mealling Standards Track [Page 3]
RFC 3404 DDDS Based URI Resolution October 2002 Therefore, this document specifies two DDDS Applications. One is for URI Resolution and the other is for URN Resolution. Both are technically identical but by separating the two URN Resolution can still proceed without the dependency. " Mealling Standards Track [Page 4]
RFC 3404 DDDS Based URI Resolution October 2002 flag an indicator of a terminal lookup but this would be incorrect since a "terminal" Rule is a DDDS concept and this flag indicates that anything after this rule does not adhere to DDDS concepts at all.. Mealling Standards Track [Page 5]
RFC 3404 DDDS Based URI Resolution October 2002 [11]. Examples of some of these services are: I2L: given a URI return one URI that identifies a location where the original URI can be found. I2Ls: given a URI return one or more URIs [6] for examples of why.) 4.4.2 Protocols The protocol identifiers that are valid for the 'protocol' production MUST be defined by documents that are specific to URI resolution. At present the THTTP [10]. Mealling Standards Track [Page 6]
RFC 3404 DDDS Based URI Resolution October 2002 4]. Mealling Standards Track [Page 7]
RFC 3404 DDDS Based URI Resolution October 2002 3404 [8], . Mealling Standards Track [Page 8]
RFC 3404 DDDS Based URI Resolution October 2002 The service fields say that if we speak [9] for the interpretation of the fields above.) There is opportunity for significant optimization here. RFC 3404 Mealling Standards Track [Page 9]
RFC 3404 DDDS Based URI Resolution October 2002 (Note that this example is chosen for pedagogical purposes, and does not conform to the CID URI scheme.) The first step in the resolution process is to find out about the CID scheme. The scheme is extracted from the URI, prepended to '.uri.arpa.', and the NAPTR for 'cid.uri.arpa.' looked up in the DNS. It might return records of the form: cid.uri.arpa. ;; order pref flags service regexp replacement IN NAPTR 100 10 "" "" "!^cid:.+@([^\.]+\.)(.*)$!. Mealling Standards Track [Page 10]
RFC 3404 DDDS Based URI Resolution October 2002. Mealling Standards Track [Page 11]
RFC 3404 DDDS Based URI Resolution October 2002 6. Notes o Registration procedures for the 'urn.arpa.' and 'uri.arpa.' DNS zones are specified in "Dynamic Delegation Discovery System (DDDS) Part Five: URI.ARPA Assignment Procedures" (RFC 3405 [5]..].. Mealling Standards Track [Page 12]
RFC 3404 DDDS Based URI Resolution October 2002. 9. Acknowledgments The editors would like to thank Keith Moore for all his consultations during the development of this document.y, October 2002. [6] Sollins, K. and L. Masinter, "Functional Requirements for Uniform Resource Names", RFC 1737, December 1994. Mealling Standards Track [Page 13]
RFC 3404 DDDS Based URI Resolution October 2002 2000. Mealling Standards Track [Page 14]
RFC 3404 DDDS Based URI Resolution October 2002; Mealling Standards Track [Page 15]
RFC 3404 DDDS Based URI Resolution October 2002 } // At this point we have a successful rewrite and we will // know how to speak the protocol and request a known // resolution service. Before we do the next lookup, check // (SRV record) { // in order of preference try contacting srv[j].target using the protocol and one of the resolution service requests from the "services" field of the last NAPTR record. if (successful) return (target, protocol, service); // Actually we would probably return a result, but this Mealling Standards Track [Page 16]
RFC 3404 DDDS Based URI Resolution October 2002 // code was supposed to just tell us a good host to talk to. } die with an "unable to find a host" error; } Author's Address Michael Mealling VeriSign 21345 Ridgetop Circle Sterling, VA 20166 US EMail: michael@neonym.net URI: Mealling Standards Track [Page 17]
RFC 3404 DDDS Based URI Resolution 18] | http://zinfandel.tools.ietf.org/html/rfc3404 | CC-MAIN-2020-40 | refinedweb | 740 | 62.48 |
Squares Of A Sorted Array
March 6, 2020
The simple solution first computes the squares, then sorts:
> (sort < (map square '(-4 -1 0 3 10))) (0 1 9 16 100)
That solution requires time O(n log n) because of the sort. An O(n) solution exploits the fact that the input is already sorted, using two pointers
lo and
hi to scan from opposite ends of the input array:
(define (sq-sort xv) (let loop ((lo 0) (hi (- (vector-length xv) 1)) (xs (list))) (if (= lo hi) (cons (square (vector-ref xv lo)) xs) (if (< (abs (vector-ref xv lo)) (abs (vector-ref xv hi))) (loop lo (- hi 1) (cons (square (vector-ref xv hi)) xs)) (loop (+ lo 1) hi (cons (square (vector-ref xv lo)) xs))))))
> (sq-sort '#(-4 -1 0 3 10)) (0 1 9 16 100)
You can run the program at.
Nifty little drill. Here is my take on it using Julia:
Clearly, whoever was the original poster of this exercise 1. had a moderate command of the English language, and 2. opted for a more interesting approach than just squaring the list and then sorting it. This solution adheres to the 2nd assumption.
Have a nice weekend!
PS – a more elegant way of saying “non-decreasing order” is “increasing order” or “ascending order”. Why confuse people needlessly?
The sort method in Python is a mergesort, that tries to find runs of increasing and decreasing numbers and then merges those runs. So, for this problem Python sorting is not O(nlogn), but a lot faster, as the squares form a run of decreasing numbers and a run of increasing numbers. The method below works faster, than the method proposed by PP in Python.
Here’s a solution in C.
Example:
@Zack, “non-decreasing” may have been used to suggest that the input and output arrays can have duplicates. “increasing” could be interpreted to suggest otherwise.
…analogous to how “non-negative” is used to include positive numbers and zero, whereas “positive” used alone would exclude zero.
Here’s a solution in Python.
Output:
Python solution:
import numpy as np
Get user input
arr = np.array(input(“Type an array of integers in increasing order (a b c x y z): “).split())
arr_ints = []
Create new array of integers and sort by increasing order
for i in range(len(arr)):
arr_ints.append(int(arr[i]))
Append each square value to a new array
squares = []
for num in arr_ints:
squares.append(num ** 2)
Print final array
print(np.sort(squares))
===================
OUTPUT
Type an array of integers in increasing order (a b c x y z): -4 -1 0 3 10
[ 0 1 9 16 100]
Racket: | https://programmingpraxis.com/2020/03/06/squares-of-a-sorted-array/2/ | CC-MAIN-2020-40 | refinedweb | 447 | 62.27 |
Are you still dependent on Python 2 for your applications? Then you must know that meeting security and compliance standards is a long and complicated process. ActiveState can help you secure your legacy applications, achieve compliance and even migrate to Python 3! Learn more about ActiveState’s extended Python 2 support.
It’s always fun to update applications on your phone or laptop – you get to use all the new features! But it’s not so fun when you need to update your application.
In my case, I had a bunch of machine learning models written in Python 2 that I had to migrate over to Python 3. Since Python 2 is no longer supported by the Python Software Foundation, it was critical that I migrate, but the process was still a chore.
Why Migrate from Python 2 to 3?
The most pressing reason to migrate is that the Python Software Foundation will no longer issue security fixes for vulnerabilities, or even performance updates.
However, migrating over to Python 3 can be an annoying task! It’s not a simple “push button” upgrade because Python 3 is not backward compatible with Python 2. You will have to make code-level changes once you update, but if you intend to keep supporting your application, you don’t really have a choice.
Also keep in mind that, while most of the open source libraries you used to build your application on Python 2 also support Python 3, just importing them directly will likely result in faulty behavior – even in production environments – causing unnecessary hindrances to your users.
Finally, Python 3 is so much more modern and compatible with the world we live in now. It has great support for unicode characters, does floating point operations better, and finally fixes that wretched print statement! (Don’t come at me with pitchforks now.)
So now that you’ve decided to migrate to Python 3, how do you do it?
Python 3 Migration Guidelines
The strategy you use for migration largely depends on the age of your application, and the version of Python 2 that it uses. Different strategies involve doing a direct migration and single push to production; using a bridge version such as v2.7; or migrating each service one by one (in the case of microservices).
As a rule-of-thumb, if you’re already using Python v2.7 in your code base, you’re in a good position. If you’re using Python v2.6 or previous, you’re better off first doing a migration tov 2.7, ensuring everything is working, and then moving to Python 3.
Another popular strategy is to write any new code to be compatible with Python 3. To ensure that this does not break when interfacing to Python 2 code, you can add the following statements at the top of any new modules you create:
from __future__ import absolute_import from_future_import division from_future_import print_function
It’s also a good idea to utilize staging servers, and push a build there to ensure everything works before moving to production.
When I migrated my code base, I followed some general guidelines that included:
- Learn What’s New in Python 3
This one’s obvious, but it has to be mentioned. I made the grave mistake of following a “tutorial” for my migration. I quickly realized that every code base is unique and you might run into issues that aren’t exactly covered in a tutorial. Make sure you read through the change logs of Python 3, and the version that you’re migrating to before you start. A great place that has everything covered is the Python docs page.
- Test Coverage
I’m sure you’ve written quite a few automated tests for your application. Though you can technically migrate without tests, you will most certainly shorten your migration process with them.But this always brings up the question, how many tests is enough? A good way to measure your test coverage is to use the Coverage library. It works with v2.7, v3.x and bleeding edge versions of Python, as well. Coverage is a simple tool that analyses how many executable lines of code you have vs how many lines of code your tests execute. It then gives you a test coverage percentage. Obviously, the higher the number the better.When you start the migration make sure you do it in parts, and use tests to validate each step. You’ll be able to catch bugs much better this way. Another tool to help you with the process is Tox. With Tox, you can run tests in different versions of Python. This helps you quickly identify breaking points in your application.
- Identify Breaking Syntax and Libraries
Python 3 brings with it many syntax changes. The most popular being “print” function changes. Ideally, your codebase shouldn’t have print statements, but if it does, consider migrating them first.Basically, print statements in Python 2 did not need to be enclosed with brackets, but now they do:
# Python 2 syntaxWhile most popular Python libraries/packages have been ported over to Python 3, you can never be sure. Any mismatch can cause your application to fail migration. To detect all unsupported libraries, use the caniusepython3 package.You can also use the Pylint library to weed out all syntactic issues.
print "Hello World!"
# Python 3 syntax
print("Hello World!")
- Automatic Conversion Tools
Breathe: you don’t have to do everything manually in this migration because help is on the way!There are a number of tools that can automate much of your migration effort’s heavy lifting. The following libraries can comb through your code base and make changes to improve its Python 3 compatibility. While they don’t hit all the requirements for a complete migration, they do chew up a major portion of the work you need to do.For large applications that have dependencies all over the place (making it impossible for you to test in silos), consider the six library. This tool migrates your codebase to a limbo state that is compatible with both Python 2 and 3. From there, you can use other tools to migrate completely over to Python 3.Otherwise, you can use any of the below libraries to automatically migrate syntax level changes:
- 2to3 – reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code.
- Modernize – attempts to generate a codebase compatible with Python 3. Note that the code it generates has a runtime dependency on six.
- Python-future – passes Python 2 code through all the appropriate fixers to turn it into valid Python 3 code.While they all essentially do the same thing, they take different approaches. Refer to the documentation for each to determine which might be best for your code base.Once you’re done, make sure to run your tests once again in order to ensure nothing is broken. And remember that these tools are not foolproof: sometimes they require you to do a little manual digging.
- Manual Checks
Unfortunately, there’s only so much that automatic tools can do for you. There are a few manual checks that you’ll have to perform to ensure smooth delivery:
- Division
Python 3 division supports floating point out of the box. This means that anywhere you have divided by an integer and expected a whole number as the output, that will no longer be the case.# Python 2 syntax
9 / 2 = 4# Python 3 syntax
9 / 2 = 4.5
- CSV Parsing
In Python 2, CSV files for parsing should be opened in binary mode. However, in Python 3, text mode is required. Furthermore, you will now need to specify the newline argument.
- Iterable objects, not lists
Many Python 3 built-in functions now return an iterator instead of a list. This is because iterators have better and more efficient memory consumption than lists.Though this should not cause breaking changes in most scenarios, if your codebase does require a list to be returned, consider manually converting an iterator to a list first.
- Relative Imports
Relative imports are no longer supported in Python 3. Any code that used relative imports in Python 2 now has to be modified to support absolute imports.
Conclusions
When I prepared for my migration, I read a lot about Python 3. I was surprised to find that it has been in development since 2005! The first release was way back in 2008. Ever since then the Python community has been pushing for developers to make the jump. However, after an unsuccessful deadline in 2016, the community decided to do a hard stop in 2020.
Well, here we are 12 years later and according to recent surveys and pypistats.org, many of us are still using Python 2. Hopefully, that’s only because you’re in the midst of a migration because, sooner or later, your Python 2 application will become riddled with bugs and security vulnerabilities.
But if you’re stuck on Python 2 because a key library or vendor hasn’t migrated yet, or perhaps you just can’t justify the opportunity cost of migration, there’s still hope. ActiveState continues to offer support for Python 2 beyond EOL, including security fixes to core language and standard libraries.
- Read more about ActiveState’s Python 2 EOL Support Offering.
- Get the Python 2-to-3 runtime, which contains all the conversion libraries from this post, including
modernize,
2to3,
sixand
python-future. | https://www.activestate.com/blog/python-2-to-3-migration-guidelines/ | CC-MAIN-2022-05 | refinedweb | 1,584 | 63.9 |
This analysis was conducted for April 27, 2019 story "How California’s faltering high-speed rail project was ‘captured’ by costly consultants."
It found that outside consultants have provided more than 3,000 environmental statements, business documents and other reports to the California High-Speed Rail Authority. Altogether they contain more than 152,000 pages.
Import Python tools
import os import PyPDF2 import pathlib import requests import pandas as pd from bs4 import BeautifulSoup from urllib.request import urlretrieve
Set output directory where documents will be saved.
output_dir = pathlib.Path(os.getenv("OUTPUT_DIR") or "./output")
Read in a list of all the URLs on the rail authority's site that contain consultant reports.
page_list = open("./input/urls.csv").read().split("\n")
Request each page and parse out all of its PDF links
def parse_page(url): """ Parse all the PDF urls from the provided URL's HTML. """ r = requests.get(url) soup = BeautifulSoup(r.text) a_list = soup.find_all("a") pdf_list = [a['href'] for a in a_list if a['href'].endswith(".pdf")] return [f"{href}" for href in pdf_list]
pdf_list = []
for page in page_list: pdfs = parse_page(page) pdf_list.extend(pdfs)
How many total PDF urls were found?
f"{len(pdf_list):,}"
'3,410'
Remove all of the duplicates.
pdf_set = set(pdf_list)
How many URLs remain?
f"{len(pdf_set):,}"
'3,168'
Download them all.
def download_pdf(url): """ Download a PDF url to the output folder. """ filename = url.split("/")[-1] path = output_dir.joinpath(filename) if path.exists(): return try: print(f"Downloading {filename}") urlretrieve(url, path) except Exception: print(f"Failed to download {url}")
for url in pdf_set: download_pdf(url)
Get their page counts.
def get_page_count(path): """ Get the page count of the provided PDF path. """ with open(path, 'rb') as f: try: pdfReader = PyPDF2.PdfFileReader(f) return pdfReader.numPages except: return pd.np.NaN
path_list = list(output_dir.glob('*.pdf'))
Count the total number of documents again to check out many we actually downloaded.
f"{len(pdf_path_list):,}"
'3,129'
Loop through all the documents and tally pages.
page_counts = dict((p, get_page_count(p)) for p in path_list)
df = pd.DataFrame(pdf_page_counts.items(), columns=["pdf", "page_count"])
df.sort_values("page_count", ascending=False).head()
len(df)
3129
f"{df.page_count.sum():,}"
'151,703.0' | https://nbviewer.jupyter.org/github/datadesk/hsr-document-analysis/blob/master/notebook.ipynb | CC-MAIN-2019-43 | refinedweb | 365 | 53.07 |
In "Make Room for JavaSpaces, Part 2: Build a compute server with JavaSpaces" you saw how to build a simple general-purpose compute server using the JavaSpaces technology. Recall that a compute server is a powerful, all-purpose computing engine that accepts tasks, computes them, and returns results. In that design, a master process breaks down a large, compute-intensive problem into smaller tasks -- entries that describe the task and contain a method to perform the necessary computation -- and writes them into a space. In the meantime, worker processes watch the space and retrieve tasks as they become available, compute them, and write the results back to the space, from which the master will retrieve them at some point..
Adding transactions to the worker.
You can make the worker more robust by using transactions. (The complete code for the compute server that has been reworked with transactions can be found in Resources and forms the
javaworld.simplecompute2 package.) First you'll modify the worker's constructor to obtain a
TransactionManager proxy object and assign it to the variable
mgr, and you'll define a
getTransaction method that creates and returns new transactions:
public class Worker { private JavaSpace space; private TransactionManager mgr; . . . public Worker() { space = SpaceAccessor.getSpace(); mgr = TransactionManagerAccessor.getManager(); } public Transaction getTransaction(long leaseTime) { try { Transaction.Created created = TransactionFactory.create(mgr, leaseTime); return created.transaction; } catch(RemoteException e) { e.printStackTrace(); return null; } catch(LeaseDeniedException e) { e.printStackTrace(); return null; } } }
Most of the
getTransaction method should be familiar to you after you have read Make Room for JavaSpaces, Part 4. Note that the method has a
leaseTime parameter, which indicates the lease time that you'd like the transaction to have.
Now let's modify the
startWork method to add support for transactions:
public void startWork() { TaskEntry template = new TaskEntry(); for (;;) { // try to get a transaction with a 10-min lease time Transaction txn = getTransaction(1000*10*60); if (txn == null) { throw new RuntimeException("Can't obtain a transaction"); } try { try { // take the task under a transaction TaskEntry task = (TaskEntry) space.take(template, txn, Long.MAX_VALUE); // perform the task Entry result = task.execute(); // write the result into the space under a transaction if (result != null) { space.write(result, txn, 1000*60*10); } } catch (Exception e) { System.out.println("Task cancelled:" + e); txn.abort(); } txn.commit(); } catch (Exception e) { System.out.println("Transaction failed:" + e); } }
Each time
startWork iterates through its loop, it calls
getTransaction to attempt to get a new transaction with a lease time of 10 minutes. If an exception occurs while creating the transaction, then the call to
getTransaction returns
null, and the worker throws a runtime exception. Otherwise, the worker has a transaction in hand and can continue with its work.
First, you call
take (passing it the transaction) and wait until it returns a task entry. Once you have a task entry, you call the task's
execute method and assign the returned value to the local variable
result. If the result entry is non-
null, then you write it into the space under the transaction, with a lease time of 10 minutes.
In this scenario, three things could happen. One possibility is that the operations complete without throwing any exceptions, and you attempt to commit the transaction by calling the transaction's
commit method. By calling this method, you're asking the transaction manager to commit the transaction. If the commit is successful, then all the operations invoked under the transaction (in this case, the
take and
write) occur in the space as one atomic operation.
The second possibility is that an exception occurs while carrying out the operations. In this case, you explicitly ask the transaction manager to abort the transaction in the inner
catch clause. If the abort is successful, then no operations occur in the space -- the task still exists in the space as if it hadn't been touched.
A third possibility is that an exception occurs in the process of committing or aborting the transaction. In this case, the outer catch clause catches the exception and prints a message, indicating that the transaction failed. The transaction will expire when its lease time ends (in this case after 10 minutes), and no operations will take place. The transaction will also expire if this client unexpectedly dies or becomes disconnected from the network during the series of calls.
Now that you've made the worker code robust, let's turn to the master code and show how you can improve it as well.
Adding transactions to the master
Recall the
Master code from the compute server example, which calls the
generateTasks method to generate a set of tasks and then calls the
collectResults method to collect results:; } } }
You'll notice in
writeTask that the
write occurs under a
null transaction. If the
write returns without throwing an exception, then you can trust that the entry was committed to the space. But if a problem occurs during the operation and an exception is thrown, you can't know for sure whether or not the task entry was written to the space. If a
RemoteException is thrown (which can occur whenever a space operation communicates with the remote JavaSpace service), the task entry may or may not have been written. If any other type of exception is thrown, then you know the entry wasn't written to the space.
The master isn't very fault tolerant, since you never know for sure whether or not a task is written successfully into the space. And if some of the tasks don't get written, the compute server isn't going to be able to completely solve the parallel computation on which it's working. To make
Master more robust, you'll first add the convenient
getTransaction method that you saw previously. You'll also modify the
writeTask to make use of transactions and to return a Boolean value that indicates whether or not it wrote the task:
private boolean writeTask(Command task) { // try to get a transaction with a 10-min lease time Transaction txn = getTransaction(1000*10*60); if (txn == null) { throw new RuntimeException("Can't obtain a transaction"); } try { try { space.write(task, txn, Lease.FOREVER); } catch (Exception e) { txn.abort(); return false; } txn.commit(); return true; } catch (Exception e) { System.err.println("Transaction failed"); return false; } }
First,
writeTask tries to obtain a transaction with a 10-minute lease by calling
getTransaction, just as you did in the worker code. With the transaction in hand, you can retrofit the
write operation to work under it. This time when you call
write, you supply the transaction as the second argument.
Again, three things can happen as this code runs. If the
write completes without throwing an exception, you attempt to commit the transaction. If the commit succeeds, then you know the task entry has been written to the space, and you return a status of
true. On the other hand, if the
write throws an exception, you attempt to abort the transaction. If the abort succeeds, you know that the task entry was not written to the space (if it was written, it's discarded), and you return a status of
false.
The third possibility is that an exception is thrown in the process of either committing or aborting the transaction. In this case, the outer catch clause prints a message, the transaction expires when its lease time is up, and the
write operation doesn't occur, so you return a status of
false. | http://www.javaworld.com/article/2076112/learn-java/make-room-for-javaspaces--part-5.html | CC-MAIN-2016-40 | refinedweb | 1,249 | 53.1 |
On Sun, Nov 04, 2007 at 12:30:14AM +0100, Roel Kluin wrote: > I am less certain about this one, so please review > -- > Iounmap when EFI won't switch to virtual mode > > Signed-off-by: Roel Kluin <12o3l@tiscali.nl> > --- > diff --git a/arch/ia64/kernel/efi.c b/arch/ia64/kernel/efi.c > index 3f7ea13..af925ab 100644 > --- a/arch/ia64/kernel/efi.c > +++ b/arch/ia64/kernel/efi.c > @@ -585,6 +585,8 @@ efi_enter_virtual_mode (void) > efi_desc_size, ia64_boot_param->efi_memdesc_version, > ia64_boot_param->efi_memmap); > if (status != EFI_SUCCESS) { > + if ((md->attribute & EFI_MEMORY_UC) || (md->attribute & EFI_MEMORY_WC)) > + iounmap(md->virt_addr); > printk(KERN_WARNING "warning: unable to switch EFI into virtual mode " > "(status=%lu)\n", status); > return; > - > To unsubscribe from this list: send the line "unsubscribe linux-ia64" in > the body of a message to majordomo@vger.kernel.org > More majordomo info at Hi Roel, I'm not really sure what the intention of this patch is. But I'm pretty sure its not doing what you want it to do. I guess that you wish to reverse all the calls to ioremap() that are made in efi_enter_virtual_mode(). ioremap() is called during iterating through efi_map_start, but you only seem to call iounmap on whatever md happens to be set to at the end of the iteration. Surely you need to run through efi_map_start again? The next thing that I wonder about is weather calling iounmap() actually reverses ioremap() in this case. Though now that I look at it and see that basically iounmap() will do nothing in this case, which seems appropriate as in this case ioremap() ends up being: return (void __iomem *) (__IA64_UNCACHED_OFFSET | phys_addr) Its probably not to much of a bother that all the md->virt_addr have been mangled and stay mangled. Though if we are concerned about such things, perhaps it would be cleaner to zero them on error? Some other issues that aren't part of your patch but are related. 1. Without the phys_efi patches that I posted to the linux-ia64 about a year ago, if EFI fails to switch to virtual mode then all SAL calls will fail. Which in turn means that the kernel will fail to boot (unless I am mistaken and some machines don't make SAL calls directly from the kernel). This is because currently the kernel doesn't have any mechanism to make SAL calls in physical mode. My patches fixed this and introduced a switch, to force efi to stay in physical mode, for testing purpuses. But there was no interest in the code. Actually there were some suggestions that some machines simply couldn't perform some opperations with EFI in physical mode. Basically this means that the will fail to boot. That is, unless I am mistaken and some machines don't make SAL calls directly from the kernel. Given that the kernel can't function with EFI in physical mode (without the phys_efi patches), I really have to conclude that in fact EFI never fails to switch itself into virtual mode. Otherwise there would be machines out there that simply wouldn't boot. This being the case, there doesn't seem to be a whole lot of point in making sure the error path cleans up correctly. In fact, perhaps the error path should be removed all together or just changed to BUG("unable to switch EFI into virtual mode"); 2. It seems to me that the loop in efi_enter_virtual_mode() could be rewritten as the following without changing its behaviour, other than debugging output. I have not tested this theory. for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) { md = p; if (! (md->attribute & EFI_MEMORY_RUNTIME)) continue; md->virt_addr = (u64) ioremap(md->phys_addr, 0); } -- Horms H: W: - To unsubscribe from this list: send the line "unsubscribe linux-ia64" in the body of a message to majordomo@vger.kernel.org More majordomo info at on Mon Nov 05 13:03:23 2007
This archive was generated by hypermail 2.1.8 : 2007-11-05 13:03:41 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0711/21374.html | CC-MAIN-2020-16 | refinedweb | 661 | 61.87 |
Created on 2012-11-14 04:32 by chris.jerdonek, last changed 2019-08-29 08:15 by rhettinger. This issue is now closed.
This issue is to ensure that argparse.ArgumentParser() accepts objects that support the "in" operator for the "choices" argument to ArgumentParser.add_argument().
As observed by Terry in the comments to issue 16418:
the argparse module does not in general support "choices" values that support the "in" operator, even though the argparse documentation says it does:
"Any object that supports the in operator can be passed as the choices value, so dict objects, set objects, custom containers, etc. are all supported."
(from )
For example, passing a user-defined type that implements only self.__contains__() yields the following error message when calling ArgumentParser.parse_args():
File ".../Lib/argparse.py", line 1293, in add_argument
raise ValueError("length of metavar tuple does not match nargs")
(The error message also gives the wrong reason for failure. The swallowed exception is "TypeError: '<class>' object is not iterable.")
For the record, choices types implementing only __contains__ never worked in any cases. (I should have said ArgumentParser.add_argument() raises a ValueError in the above.)
So I wonder if we should classify this as an enhancement and simply document the restriction in maintenance releases to iterable types. Clearly the module was written under the assumption (in multiple places) that choices are iterable.
Also, if we do change this, perhaps we should fall back to displaying the metavar in help messages when naming the container rather than using repr(). A message like the following, for example, wouldn't be very helpful or look very good:
invalid choice: 0 (choose from <__main__.Container object at 0x10555efb0>)
I think we should avoid letting Python creep into help and usage text..
Adding a failing test. I will supply a patch shortly.
Attaching patch. With this patch, passing a non-iterable choices argument to parser.add_argument() raises (for example):
Traceback (most recent call last):
...
File ".../Lib/argparse.py", line 558, in _metavar_formatter
choice_strs = [str(choice) for choice in action.choices]
TypeError: 'MyChoices' object is not iterable
instead of the incorrect:
File ".../Lib/argparse.py", line 1333, in add_argument
raise ValueError("length of metavar tuple does not match nargs")
ValueError: length of metavar tuple does not match nargs
Is it okay to change this exception type in maintenance releases? The other option is to keep the error as a ValueError but to change the error message, though I think TypeError is the correct exception to allow through. Note that the existing ValueError is preserved for other code paths. Indeed, there are several tests checking for this ValueError and its error message, which the attached patch does not break.
If we want to consider accepting non-iterable choices for 3.4, we can still have that discussion as part of a separate patch.
Slight doc tweak: s/container/sequence/.
Since the line between a type error and a value error is fuzzy anyway, I'd be in favor of maintaining the backward compatibility here. We don't consider exception message content part of the API (though we do occasionally work to preserve it when we know people are depending on it), but the exception *types* generally are.
Sounds fine. Does that mean a test should still be added for the message? I was never clear on this because on the one hand we want to be sure we use the right message (and that we're actually fixing the issue), but on the other hand we don't want the message to be part of the API. By the way, to make things slightly less brittle, I could be clever and trigger a TypeError to get the right message.
I guess another option would be to mark the test CPython-only.
CPython only would not be appropriate, as it is not.
What I usually do in such cases is use AssertRaisesRegex looking for some critical part of the message that represents the functionality we are looking for rather than the exact text. In this case, it would be looking for the type name of the problem value in the message, since that is how we are identifying the specific source of the error.
The exception question is messy, but I think it is the wrong question. The doc is correct in that it says what the code should be doing. To test whether an argument is in a collection of choices, the code should just say that: 'arg in choices' (as far as I know, it does -- for the actual check). In other words, I think the original intent of this issue is correct.
"Clearly the module was written under the assumption (in multiple places) that choices are iterable." I think it should not. We implement 'in' with '__contains__', rather than forcing the use of iteration, for good reason. I discussed some examples in msg175520.
As far as I know, the reason argparse iterates is to bypass the object's representation methods and produce custom, one-size-fits-all, usage and error messages. As discussed in #16418, this supposed user-friendliness may not be. To me, restricting input for this reason is a tail-wags-dog situation. If the object is not iterable, just use repr for the messages instead of exiting. Let the app writer be responsible for making them user-friendly and not absurdly long.
I don't disagree that this feature could be useful. I'm just not sure it should go into a maintenance release. It feels like an enhancement to me because to use this feature, the user will have to use the API in a way they haven't before, and we will probably have to do things like add documentation and examples for this new use case (e.g. explaining that users passing non-iterable choices will need to implement a user-friendly repr() for help to render nicely).
Also, it introduces new questions like: if we're going to be using repr() for that case, then why wouldn't we allow repr() to be used for iterable choices if the user would like to better control the behavior (e.g. for very long lists)? Why not have a unified way to deal with this situation (e.g. something like __argparse_repr__ with a better name, or else provide or document that certain formatters should be used)? These don't seem like bug-fix questions.
> As far as I know, the reason argparse iterates is to bypass the object's representation methods and produce custom, one-size-fits-all, usage and error messages.
Another possibility is that it was the most helpful message for the use case the writers originally had in mind. Certainly, for example, seeing the available choices '0, 1, 2, 3, 4' is more useful than seeing 'xrange(5)'.
Note that we would also have to deal with not just the error text but also the usage string. From the docs:
>>> parser.parse_args('11'.split())
usage: PROG [-h] {5,6,7,8,9}
PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
I took a good look at the 3.3 code. With respect to the main purpose of choices -- checking user input -- argparse does not require that choices be iterable, as it *does* use 'in', as it should. Line 2274:
if action.choices is not None and value not in action.choices:
So unless the usage message is generated even when not needed (I did not delve that far), non-iterables should work now as long as the user does not request the usage message or make an input mistake.
If that is so, then this issue is strictly about the string representation of non-iterable choices. A mis-behaving tail is not a reason to kill the dog ;-). The easy answer, and the only sensible one I see, is to use either str() or repr(). But how to do that? I think this and #16418 have to be fixed together.
The current format-by-iteration method, used for both usage and exceptions, works well for small iterable collections. But it is obnoxious for non-small collections. As I mentioned before, it will just hang for infinite iterables, which is even worse. So the method needs to be changed anyway. And to do that, it should be factored out of the three places where it is currently done in-line.
At 557:
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
To match the code below, so it can be factored out into a function,
change the last two lines to
choices_str = ','.join(str(c) for c in action.choices)
result = '{%s}' % choices_str
At 597: (note that 'params' is adjusted action.__dict__)
if params.get('choices') is not None:
choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str
The intermediate list in the 2nd line is not needed
choices_str = ', '.join(str(c) for c in params['choices'])
I am aware of but do not understand ',' versus ', ' as joiner. I also do not understand why both versions of choices_str are needed. Are there two different usage messages?
At 2276:
'choices': ', '.join(map(repr, action.choices))}
or, replacing map with comprehension
choices_str = ', '.join(repr(c) for c in action.choices)
'choices': choices_str}
Now define choices_str(src, joiner, rep), delete 559 and 598, and modify
559: ... result = '{%s}' % choices_str(action.choices, ',', str)
599: ... params['choices'] = choices_str(param['choices'], ', ', str)
2276: ... 'choices': choices_str(action.choices, ', ', repr}
(I am assuming that the two joiners are really needed. If not, delete.)
Now we should be able to write choices_str to solve all 3 problems in the two issues. My coded suggestion:
from itertools import islice
N = 21 # maximum number (+1) of choices for the current nice string.
# This is just an illustrative value, experiment might show better #.
def choices_str(src, joiner, rep):
prefix = list(islice(src, N))
if len(prefix) < N: # short iterables
return joiner.join(rep(c) for c in prefix) # current string
else:
try: # non-short sliceable finite sequences
head = joiner.join(rep(c) for c in src[:N//2])
tail = joiner.join(rep(c) for c in src[N//4:])
return head + ' ..., ' + tail
except AttributeError: # no __getindex__(slice), everything else
return repr(src)
> argparse does not require that choices be iterable, as it *does* use 'in', as it should. Line 2274:
> if action.choices is not None and value not in action.choices:
There are cases where it's incorrect for argparse to being using "in" instead of sequence iteration, which again leads me to think that iteration is what was intended. See issue 16977.
> So unless the usage message is generated even when not needed (I did not delve that far), non-iterables should work now as long as the user does not request the usage message or make an input mistake.
As I said in the second comment of this issue, this doesn't work in any case because the ValueError is raised on add_argument(). So I don't see how the lack of this option can be affecting any users.
_Actions_container(object) [1198 in 3.3.0 code] .add_argument() [1281] does not directly check for choices.__iter__ ('__iter__' is not in the file). Nor does it use the 3.x-only alternative isinstance(choices, collections) ('Iterable' is also not in the file). Rather it formats the help string for each argument as added.
The complete statement that raises the error is (now at 1321):
try:
self._get_formatter()._format_args(action, None)
except TypeError:
raise ValueError("length of metavar tuple does not match nargs")
def _get_formatter is part of
class ArgumentParser(_AttributeHolder, _ActionsContainer):
so 'self' has to be an ArguementParser for the above exception.
_format_args calls get_metavar, which is returned by _metavar_formatter. The last contains the first of the three choices iterations that I propose to factor out and revise. So that proposal should eliminate the particular exception from add_argument.
The docstring for class Action mirrors the doc:
'''
- choices -- A container of values that should be allowed. If not None,
after a command-line argument has been converted to the appropriate
type, an exception will be raised if it is not a member of this
collection.
'''
This directly translates to the code line
if action.choices is not None and value not in action.choices:
Trying to prettily format messages peripheral to the main goal should not take indefinitely or infinitely long, nor make the message worse, nor raise an exception.
I have a new suggestion that I hope will satisfy Terry.
After looking at the code more, I noticed that add_argument() does currently work for non-iterable choices provided that metavar is passed. This was also noted in the report for the duplicate issue 16697.
On reflection, this makes sense because that's what metavar is for -- providing a replacement string for the usual formatting in the help text. The only thing that doesn't work in this case is error message formatting.
With that, I'd like to propose the following:
(1) Change the add_argument() error raised for non-iterable choices from:
ValueError("length of metavar tuple does not match nargs")
to something like:
ValueError("metavar must be provided for non-iterable choices")
This provides the help string representation for non-iterable choices (in the spirit of "Explicit is better than implicit").
(2) Make the error text the following for non-iterable choices (the error message currently breaks for non-iterable choices):
PROG: error: argument FOO: invalid choice: 'xxx'
compared with (for iterable choices)--
PROG: error: argument FOO: invalid choice: 'xxx' (choose from ...)
I think this is preferable to inserting the str() or repr() (especially for maintenance releases) because str() and repr() may not be meant for displaying to the end-users of a script. The instructions/description of such choices is already in the add_argument() "help" string. We could consider appending that to provide substantive guidance.
Actually, let me relax (1). We can just use what the argparse code calls the "default_metavar" in that case (which it constructs from the argument name).
The important thing for me is not displaying the str/repr when it might not be intended.
If you can somewhat solve the problem by better using the existing api, good. I am not 'stuck' on reusing str/repr*. If metavar is non-optional for non-iterable choices, the doc should say so in the entry for choices. (Does the test suite already have a testcase already for non-iterable choices + metavar?)
If you can solve it even better and remove that limitation by extending the 'default_metaver' idea from positional and optional args to choices ('choiced' args), even better.
I think the refactoring may still be needed, especially for #16418, but that is that issue.
* My main concern is that the attempt to provide helpful info to end users not hang or kill a program. IDLE used to sometimes quit while attempting to provide a nice calltip (#12510). It currently quits on Windows when attempting to warn users about bad custom configuration (#14576).
Here is a patch for discussion that allows non-iterable choices with or without metavar. It refactors as suggested. However, the patch does not yet have tests.
> Does the test suite already have a testcase already for non-iterable choices + metavar?
No, not that I saw. Also, to answer a previous question, the three places in which the choices string is used are: in the usage string (separator=','), in the help string when expanding "%(choices)s" (separator=', '), and in the error message text (separator=', ' with repr() instead of str()).
I think we have converged on the right solution. The patch looks good as far as it goes, assuming that it passes the current + unwritten new tests. It will also be a good basis for reconsidering what to do with long/infinite iterables in #16418.
I think the doc patch should recommend passing a metavar arg with non-iterable choices. With that, using default metavars, whatever they end up being, is fine as long as no exception is raised. So I would make the tests of non-iterable with no metavar passed as general as possible. App writers who do not like the defaults should override them ;-).
If I understand correctly, if choices is not iterable and the user enters an invalid choice, the choice part of the error message (passed to ArgumentError) will just be 'invalid choice: <value>'.
Minor nit: .join does not need a temporary list as arg and works fine with genexp:
choices_str = sep.join(to_str(choice) for choice in choices)
> the choice part of the error message (passed to ArgumentError) will just be 'invalid choice: <value>'.
That's right. With the patch it looks like this:
>>> p = argparse.ArgumentParser(prog='test.py')
>>> p.add_argument('--foo', choices=c)
>>> p.parse_args(['--foo', 'bad'])
usage: test.py [-h] [--foo FOO]
test.py: error: argument --foo: invalid choice: 'bad'
> With that, using default metavars, whatever they end up being
argparse's default metavar is just to capitalize the "dest" if the argument is optional, otherwise it is the dest itself (which is always or usually lower-case):
def _get_default_metavar_for_optional(self, action):
return action.dest.upper()
def _get_default_metavar_for_positional(self, action):
return action.dest
So the patch uses that. You can see the former case in the above usage string. Also, with the patch the current tests pass, btw.
chris.jerdonek wrote:
"Also, to answer a previous question, the three places in which the choices string is used are: in the usage string (separator=','), in the help string when expanding "%(choices)s" (separator=', '), and in the error message text (separator=', ' with repr() instead of str())."
In the usage string, the ',' is used to make a compact representation of the choices. The ', ' separator is used in the help line, where space isn't as tight.
This 'choices formatting' is called during 'add_argument()' simply as a side effect of checking for valid parameters, especially 'nargs' (that it, is an integer or an acceptable string). Previously 'nargs' errors were not caught until 'parse_args' was used. This is discussed in Argparse needs better error handling for nargs argparse: bad nargs value raises misleading message
On the issue of what error type to raise, my understanding is that 'ArgumentError' is the preferred choice when it affects a particular argument. parse_args() nearly always raises an ArgumentError. Once add_argument has created an action, it too can raise an ArgumentError. ArgumentError provides a standard way of identifying which action is giving the problem.
While testing 'metavar="range(0,20)"', I discovered that the usage formatter strips off parenthesis. A regex expression that removes
excess 'mutually exclusive group' notation is responsible for this. The simple fix is to modify the regex so it distinguishes between ' (...)' and 'range(...)'. I intend to create a new issue for this, since it affects any metavar the includes ().
I'd suggest not worrying about the default metavar in the _expand_help() method. The formatted choice string created in that method is only used if the help line includes a '%(choices)s' string. The programmer can easily omit that if he isn't happy with the expanded list.
TestHelpVariableExpansion is the only test in test_argparse.py that uses it.
Sig('--foo', choices=['a', 'b', 'c'],
help='foo %(prog)s %(default)s %(choices)s')
This patch generally deals with the choices option, and specifically the
problems with formatting long lists, or objects that have __contains__
but not __iter__. But it also incorporates issues 9849 (better add_argument testing) and 9625 (choices with *). It may be too broad for this issue, but the changes all relate to 'choices'.
As noted by other posters, there are 3 places where choices is formatted with a comprehension. I have refactored these into one _format_choices function.
_format_choices() is a utility function that formats the choices by
iteration, and failing that using repr(). It raises an error if choices does not even have a __contains__. It also has a summarize option ({1,2,3,...,19,20}). I did not make this an action method because it only uses the choices object.
_metavar_formatter() - calls _format_choices for Usage with the default compact form. Its use of metavar gives the user full control of the choices display.
_expand_help() - calls _format_choices with the looser format. This form is used only if the user puts '%(choices)s' in the help string. This is not documented, and only appears a few times in the test file. Again the user has ultimate control over the contents.
_check_value() - calls _format_choices with a 'summarize=15' option. Normally this error message appears with the usage message. So it does not need to use the metavar.
The MetavarTypeHelpFormatter subclass is an example of how formats can be customized without changing normal behavior. Such a subclass could even be used to set custom parameters, or modify any of the above methods.
--------------------
other changes:
formatter _format_actions_usage() - I tweaked the regex that trims excess notation from mutually exclusive groups. This removed '()' from other parts of the usage line, for example a metavar like 'range(20)'. Issue 18349.
formatter _format_args() - I included issue 9849 changes which improve
testing for nargs, and array metavars. This calls the _metavar_formatter. Thus any errors in formatting choices pass back through this.
Issue 9849 also changes container add_argument() to call the parser
_check_argument(). This in turn calls _format_args() to test action
options like nargs, metavars, and now choices. If there are problems
it raises an ArgumentError.
parser _get_values() - issue 9625 changes this to correctly handle choices when nargs='*'.
parser _check_value() - I rewrote this to give better errors if there
are problems with __contains__. If choices is a string (e.g. 'abc') it
converts it to a list, so __contains__ is more consistent. For example,
'bc' in 'abc' is True, but 'bc' in ['a','b','c'] is False (issue 16977)
----------------------
test_argparse
change examples with string choices to lists
class TestAddArgumentMetavar
change EXPECTED_MESSAGE and EXPECTED_ERROR to reflect issue 9849 changes
class TestMetavarWithParen
tests 'range(n)' choices
makes sure () in the metavar are preserved
tests that metavar is used in Usage as given
tests summarized list of choices in the error message
tests the %(choices)s help line case
class TestNonIterableChoices
tests a choices container that has __contains__ but not __iter__
tests that repr() is used as needed
class TestBareChoices
tests a class without even __contains__
tests for an add_argument error
class TestStringChoices
tests the expansion of 'abc' to ['a','b','c']
I just submitted a patch to which rewrites _format_actions_usage(). It now formats the groups and actions directly, keeping a list of these parts. It no longer has to cleanup or split a usage line into parts. So it is not sensitive to special characters (space, [] or () ) in the choices metavar.
This issue has sat idle for six years. Meanwhile, the docs are still incorrect, giving every user wrong information about how the module works. Can we consider just changing the documentation instead of worrying about what the behavior should be or what the rationale is?
But see
for a discussion of whether 'container' is as good a descriptor as 'iterable'.
I think this should be dropped. IMO it is a pedantic nit. There is the everyday usage of the word "container" which has a reasonable plain meaning. There is also an ABC that was unfortunately called Container (with a capital C) that means anything the defines __contains__. IMO, we don't have to change all uses for the former just because the latter exists.
AFAICT, this "issue" for the argparse has never been a real problem for a real user ever in the entire history of the module.
So, unless there are strong objections, I would like to close this and we can shift our attention to matters of actual importance.
Here is an example of someone who cares about the behavior and/or the documentation (and still cares enough to check up on their StackOverflow question six years later): .
The issue is not the use of the word "container". The docs literally say "Any object that supports the `in` operator can be passed as the choices value" and that is not true. In fact, changing it to say "any container type" would be an improvement as that is at least arguably correct, whereas the current documentation is unambiguously incorrect.
Okay, that makes sense. Go ahead with the edit.
New changeset 84125fed2a45a9e454d7e870d8bbaf6ece3d41e8 by Raymond Hettinger in branch 'master':
bpo-16468: Clarify which objects can be passed to "choices" in argparse (GH-15566)
New changeset 0d45d50e421b46b56195821580c3760b43813106 by Raymond Hettinger (Miss Islington (bot)) in branch '3.8':
bpo-16468: Clarify which objects can be passed to "choices" in argparse (GH-15566) (GH-15587) | https://bugs.python.org/issue16468 | CC-MAIN-2019-43 | refinedweb | 4,103 | 64.51 |
Wireless Network
Last updated: Apr 22, 2020
IMAGE GALLERY (1)
Network Interface
container networking / virtual ethernet devices1 / bridges / iptables2
- Connects computer, to a protocol stack (TCP/IP) to enable communication
- Types
- Ethernet
- Token Ring
- FDDI
- SONET
- wireless wi-fi
- bluetooth networks
How to create NEW network namespace
sudo ip netns add ns1
How to run a command inside network namespace
sudo ip netns exec ns1 bash
How to add a new VLAN?
ip link add link eth0 name eth0.2 type vlan id 2 ip link add link eth0 name eth0.3 type vlan id 3 ip link set dev <interface> up ip link set dev <interface> down
What does bring interface up/down so in system?
Sets a flag on the driver that the state of the interface is up or down. The NIC is still powered on and can participate in WOL (Wake on LAN) etc.
nc
Common uses include:
- simple TCP proxies
- shell-script based HTTP clients and servers
- network daemon testing
a SOCKS or HTTP ProxyCommand for ssh(1)
# TCP server listening on port 8900 nc -l 8900
Modes
Promiscuous mode
Packet sniffing
sends all n/w packets to CPU If you want to do it in
/etc/network/interfaces, check out this configuration:
iface eth0 static address 192.168.2.1 up /sbin/ifconfig eth0 promisc on # PRomiscous mode ip link set dev wlp5s0 promisc on/off # interface up/down ip link set wlp5s0 down/up # multicaste # assign ip ip addr add/del 10.73.31.123 dev wlp5s0 # routing table ip route show
Bring wlan0 in monitor mode at startup
#/etc/network/interfaces.d/wlan0 auto wlan0 iface wlan0 inet manual wireless-mode monitor
iw phy phy1 interface add mon1 type monitor iw dev wlan1 del ifconfig mon1 up iw dev mon1 set freq put_the frequency_here
Aircracck)
- determine your wireless chipset
lspic
- `lspci -vv -s 05:00.0
- Ralink, Atheros, Qualcomm`
- Decide, you want to use tool only to listen to traffic or inject packets as well
- Wireless card has a chipset
- Tutorials
- Patches
rfkill list
- Tool for enabling and disabling wireless devices
Open System Authentication:
Ask the AP for authentication. The AP answers: OK, you are authenticated.` Ask the AP for association The AP answers: OK, you are now connected.
This is the simplest case, BUT there could be some problems if you are not legitimate to connect:
WPA/WPA2 is in use, you need EAPOL authentication. The AP will deny you at step 2. Access Point has a list of allowed clients (MAC addresses), and it lets no one else connect. This is called MAC filtering. Access Point uses Shared Key Authentication, you need to supply the correct WEP key to be able to connect. (See the How to do shared key fake authentication? tutorial for advanced techniques.)
Tools
- Xeroxploit
- Aircrack-ng
- Metasploit_Project
- Airsnort | https://avimehenwal.in/security/wireless-networks/ | CC-MAIN-2020-45 | refinedweb | 472 | 58.62 |
.)
You need to do two things: the script file’s mode must be executable and the first line must begin with #! followed by the path of the Python interpreter.
The first is done by executing chmod +x scriptfile or perhaps chmod 755 scriptfile.
The second can be done in a number of ways. The most straightforward way is to write
#!.): .... Your program should have almost all functionality encapsulated in either functions or class methods – and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.
The “global main logic” of your program may be as simple as
if __name__ == "__main__": main_logic()
at the bottom of the main module of your program.
Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite can be associated with each module which automates a sequence of tests. This sounds like a lot of work, but since Python is so terse and flexible it’s surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.
“Support modules” that are not intended to be the main module of a program may include a self-test of the module.
if __name__ == "__main__": self_test()
Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python..
Be sure to use the threading module and not the _thread module. The threading module builds convenient abstractions on top of the low-level primitives provided by the _thread module.
Aahz has a set of slides from his threading tutorial that are helpful; see.
As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:
import threading, time def thread_task(name, n): for i in range(n): print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) # <---------------------------!
But now (on many platforms) the threads don’t run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn’t start a new thread until the previous thread is blocked.
A simple fix is to add a tiny sleep to the start of the run function:
def thread_task(name, n): time.sleep(0.001) # <--------------------! for i in range(n): print(name, i) for i in range(10): T = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10)
Instead of trying to guess how long a time.sleep() delay will be enough, it’s better to use some kind of semaphore mechanism. One idea is to use the queue module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are(),)> running with argument 5 ...
Consult the module’s documentation for more details; the Queue class provides a featureful interface.
A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via sys.setswitchs, lists, dicts,!?
Use os.remove(filename) or os.unlink(filename); for documentation, see the os module. The two functions are identical; unlink() is simply the name of the Unix system call for this function.
To remove a directory, use os.rmdir(); use os.mkdir() to create one. os.makedirs(path) will create any intermediate directories in path that don’t exist. os.removedirs(path) will remove intermediate directories as long as they’re empty; if you want to delete an entire directory tree and its contents, use shutil.rmtree().
To rename a file, use os.rename(old_path, new_path).
To truncate a file, open it using f = open(filename, "rb+"), and use f.truncate(offset); offset defaults to the current seek position. There’s also os.ftruncate(fd, offset) for files opened with os.open(), where fd is the file descriptor (a small integer).
The shutil module also contains a number of functions to work on files including copyfile(), copytree(), and rmtree().
The shutil module contains a copyfile() function. Note that on MacOS 9 it doesn’t copy the resource fork and Finder info.
To read or write complex binary with open(filename, "rb") as f: s = f.read(8) x, y, z = struct.unpack(">hhl", s)
The ‘>’ in the format string forces big-endian data; the letter ‘h’ reads one “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the string.
For data that is more regular (e.g. a homogeneous list of ints or. This also happens automatically in f‘s destructor, when f becomes garbage.
But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C. Running sys.stdout.close() marks the Python-level file object as being closed, but does not close the associated C.
See the chapters titled Internet Protocols and Support and Internet Data Handling in the Library Reference Manual. Python has many modules that will help you build server-side and client-side web systems.
A summary of available frameworks is maintained by Paul Boddie at .
Cameron Laird maintains a useful set of pages about Python web technologies at.
I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily?
Yes. Here’s a simple example that uses = input("From: ") toaddrs = input("To: ").split(',') print("Enter message, end with ^D:") msg = '' while True: line = sys.stdin.readline() if not line: break msg += line # The actual mail send server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit()
A Unix-only alternative uses -i" % SENDMAIL, "w") p.write("To: receiver@example.com\n") p.write("Subject: test\n") p.write("\n") # blank line separating headers from body p.write("Some text\n") p.write("some more text\n") sts = p.close() if sts != 0: print("Sendmail exit status", sts)
The select module is commonly used to help with asynchronous I/O on sockets.
To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you do the connect(), you will either connect immediately (unlikely) or get an exception that contains the error number as .errno..
Yes.
Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python. There is also the sqlite3 module, which provides a lightweight disk-based relational database.
Support for most relational databases is available. See the DatabaseProgramming wiki page for details. may take less than a third of a second. This often beats doing something more complex and general such as using gdbm with pickle/shelve... | http://docs.python.org/3.1/faq/library.html | CC-MAIN-2013-48 | refinedweb | 1,238 | 66.13 |
This is the mail archive of the libstdc++@sources.redhat.com mailing list for the libstdc++ project.
FYI I've now enabled -fno-builtin for libstdc++-v3, until this gets sorted out. Disabling namespaces is now out of the question. >. The shadow header work will take care of making sure the C library functions are in std:: ... the patches from Steven yeterday make this much closer to usable. I suspect that's a better way of going about this than the additional classes thing. The builtins, however, have completely stumped me. I believe libstdc++-v3 will actually need compiler support for these. I see no reason builtins should work in a different way than extern "C" functions, as far as namespaces go. -benjamin | http://gcc.gnu.org/ml/libstdc++/2000-09/msg00110.html | crawl-001 | refinedweb | 123 | 68.26 |
closedir()
Close a directory
Synopsis:
#include <dirent.h> int closedir( DIR * dirp );
Since:
BlackBerry 10.0.0
Arguments:
- dirp
- A directory pointer for the directory you want to close.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The closedir() function closes the directory specified by dirp, and frees the memory allocated by opendir().
The result of using a directory stream after calling one of the exec*() or spawn*() family of functions is undefined. After a call to the fork() function, either the parent or the child (but not both) may continue processing the directory stream using the readdir() and rewinddir() functions. If both the parent and child processes use these functions, the result is undefined. Either or both processes may call the closedir() function.
Errors:
- EBADF
- The dirp argument doesn't refer to an open directory stream.
- EINTR
- The closedir() call was interrupted by a signal.
Examples:
Get a list of files contained in the directory /home/kenny:
#include <stdio.h> #include <dirent.h> #include <stdlib.h> int main( void ) { DIR *dirp; struct dirent *direntp; dirp = opendir( "/home/kenny" ); if( dirp != NULL ) { for(;;) { direntp = readdir( dirp ); if( direntp == NULL ) { break; } printf( "%s\n", direntp->d_name ); } closedir( dirp ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/c/closedir.html | CC-MAIN-2014-42 | refinedweb | 236 | 59.6 |
I've got a bunch of OpenStreetMap content that I'm trying to label (ArcGIS Pro 2.2.4) based on whether content is found in the other_tags field. Here's what I'm trying to do in the expression editor (Python):
def FindLabel ( [other_tags] ):
import re
ls = [other_tags]
slabel = re.search('"name:en"=>"(.*?)","', ls)
return slabel.group(1)
It says "NameError: name 'FindLabel' is not defined
Which is weird because if I remove the "," from the regex operation and do this:
def FindLabel ( [other_tags] ):
import re
ls = [other_tags]
slabel = re.search('"name:en"=>"(.*?)"', ls)
return slabel.group(1)
it renders as valid, although it prints out everything beyond the "name:en"=>" string.
I have also tried this, which validates but returns nothing:
def FindLabel ( [other_tags] ):
ss = [other_tags]
ls = ss[ss.find('"name:en"=>"')+1:ss.find('"')]
return ls
Here is a bit of the sort of substring someone could expect to find in OSM's other_tags:
"int_name"=>"Dubai","is_in:continent"=>"Asia","is_in:country_code"=>"AE","name:en"=>"Dubai","population"=>"1984000"....
Can anyone help me to get this label expression working?
Eric,
I was curious about this one and using ArcGIS Pro 2.3 I see the following:
seems to work?
2.3 will be available soon.
Mark | https://community.esri.com/thread/227390-why-isnt-this-label-code-working | CC-MAIN-2019-22 | refinedweb | 207 | 58.38 |
Re: Session Fixation Vulnerability in Web Based Apps
I think he means higher level frameworks, web programming libraries, toolkits, and web page builder stuff; not hooks into SSL sessions. Not to say that a hook into an SSL session is not a good place to get an application sessions identifier from -- it would be, presuming that you can't trick a
Re: traffix analysis
Re: why are CAs charging so much for certs anyway? (Re: End of the line for Ireland's dotcom star)
On Wed, Sep 24, 2003 at 05:40:38PM -0700, Ed Gerck wrote: Yes, there is a good reason for CAs to charge so much for certs. I hope this posting is able to set this clear once and for all. [zero risk, zero cost, zero liability, zero regulatory burden] 9. Product Price: At Will. There is no
efficiency?? vs security with symmetric crypto? (Re: Tinc's response to Linux's answer to MS-PPTP)
What conceivable trade-offs could you have to make to get acceptable performance out of symmetric crypto encrypted+authenticated tunnel? All ciphers you should be using are like 50MB/sec on a 1Ghz machine!! If you look at eg cebolla (more anonymity than VPN, but it's a nested forward-secret VPN
Re: Protection against offline dictionary attack on static files
Yes this is a good idea, and some people thought of it before also. Look for paper secure applications of low entropy keys or something like that by Schnieir, Wagner et al. (on counterpane labs page I think). Also the PBKDF2 function defined in PKCS#5 used to convert the password into a key
Re: Microsoft publicly announces Penny Black PoW postage project
://news.bbc.co.uk/2/hi/technology/3324883.stm Adam Back is part of this team, I think. Similar approach to Camram/hahscash. Memory-based approaches have been discussed. Why hasn't Camram explored them? steve
Re: Microsoft publicly announces Penny Black PoW postage project
applications. Adam On Fri, Dec 26, 2003 at 09:37:18PM -0500, Adam Back wrote: I did work at Microsoft for about a year after leaving ZKS, but I quit a month or so ago (working for another startup again). But for accuracy while I was at Microsoft I was not part of the microsoft research/academic team
Re: Brands' private credentials
On Wed, Apr 28, 2004 at 07:54:50PM +, Jason Holt wrote: Last I heard, Brands started a company called Credentica, which seems to only have a placeholder page (although it does have an info@ address). I also heard that his credential system was never implemented, It was implemented at
chaum's patent expiry? (Re: Brands' private credentials)
approach of Wagner's protocol. But I obviously am not a patent lawyer, and have avoided reading and participating in the writing of patents. Adam On Sun, May 09, 2004 at 05:08:09AM -0400, Adam Back wrote: [...] I looked at Camenisch protocol briefly a couple of years ago and it is not based Brands
Re: Brands' private credentials
[copied to cpunks as cryptography seems to have a multi-week lag these days]. OK, now having read: and seeing that it is a completely different proposal essentially being an application of IBE, and extension
Re: Brands' private credentials
On Mon, May 10, 2004 at 02:42:04AM +, Jason Holt wrote: However can't one achieve the same thing with encryption: eg an SSL connection and conventional authentication? How would you use SSL to prove fulfillment without revealing how? You could get the CA to issue you a patient or
blinding BF IBE CA assisted credential system (Re: chaum's patent expiry?)
On Mon, May 10, 2004 at 03:03:56AM +, Jason Holt wrote: [...] Actually, now that you mention Chaum, I'll have to look into blind signatures with the BF IBE (issuing is just a scalar*point multiply on a curve). I think you mean so that the CA/IBE server even though he learns pseudonyms
more hiddencredentials comments (Re: Brands' private credentials)
On Mon, May 10, 2004 at 08:02:12PM +, Jason Holt wrote: Adam Back wrote: [...] However the server could mark the encrypted values by encoding different challenge response values in each of them, right? Yep, that'd be a problem in that case. In the most recent (unpublished) paper, I
Re: blinding BF IBE CA assisted credential system (Re: chaum's patent expiry?)
But if I understand that is only half of the picture. The recipient's IBE CA will still be able to decrypt, tho the sender's IBE CA may not as he does not have ability to compute pseudonym private keys for the other IBE CA. If you make it PFS, then that changes to the recipient's IBE CA can get
Re: 3. Proof-of-work analysis mention this in the
Re: Reusable hashcash for spam prevention
FYI Richard amended the figures in the paper which makes things 10x more favorable for hashcash in terms of being an ecomonic defense against spammers. Richard wrote on asrg: | we're grateful (albeit a little embarrassed) for the consideration | given to one of our figures by Ted Wobber (MS
should you trust CAs? (Re: dual-use digital signature vulnerability)
The difference is if the CA does not generate private keys, there should be only one certificate per email address, so if two are discovered in the wild the user has a transferable proof that the CA is up-to-no-good. Ie the difference is it is detectable and provable. If the CA in normal
Re: should you trust CAs? (Re: dual-use digital signature vulnerability)
On Wed, Jul 28, 2004 at 10:00:01PM -0700, Aram Perez wrote: As far as I know, there is nothing in any standard or good security practice that says you can't multiple certificate for the same email address. If I'm willing to pay each time, Verisign will gladly issue me a certificate with my
Re: RPOW - Reusable Proofs of Work
It's like an online ecash system. Each recipient sends the RPOW back to the mint that issued it to ask if it has been double spent before accepting it as valid. If it's valid (not double spent) the RPOW server sends back a new RPOW for the receiving server to reuse. Very like Chaum's online
finding key pairs with colliding fingerprints (Re: How thorough are the hash breaks, anyway?)
You would have to either: - search for candidate collisions amongst public keys you know the private key for (bit more expensive) - factorize the public key after you found a collision the 2nd one isn't as hard as it sounds because the public key would be essentially random and have
anonymous IP terminology (Re: [anonsec] Re: potential new IETF WG on anonymous IPSec (fwd from [EMAIL PROTECTED]))
Joe Touch [EMAIL PROTECTED] wrote: The point has nothing to do with anonymity; The last one, agreed. But the primary assumption is that we can avoid a lot of infrastructure and impediment to deployment by treating an ongoing conversation as a reason to trust an endpoint, rather than a
Re: anonymous IP terminology (Re: [anonsec] Re: potential new IETF WG on anonymous IPSec (fwd from [EMAIL PROTECTED]))
On Sat, Sep 11, 2004 at 11:38:00AM -0700, Joe Touch wrote: Although anonymous access is not the primary goal, it is a feature of the solution. The access is _not_ anonymous. The originator's IP, ISP call traces, phone access records will be all over it and associated audit logs. And you
Brands credential book online (pdf)
Stefan Brands book on his credential / ecash technology is now downloadable in pdf format from credentica's web site: (previously it was only available in hardcopy, and only parts of the content was described in academic papers). Also the
Re: The Pointlessness of the MD5 attacks
, 2004 at 11:21:13PM +, Ben Laurie wrote:
Re: The Pointlessness of the MD5 attacks. Adam On Tue, Dec
Re: The Pointlessness of the MD5 attacks
and change surrepticiously with C'. Adam On Wed, Dec 15, 2004 at 08:44:03AM +, Ben Laurie wrote: Adam Back wrote: Well the people doing the checking (a subset of the power users) may say I checked the source and it has this checksum, and another user may download that checksum
pgp global directory bugged instructions
So PGP are now running a pgp key server which attempts to consilidate the inforamtion from the existing key servers, but screen it by ability to receive email at the address. So they send you an email with a link in it and you go there and it displays your key userid, keyid, fingerprint and email
and constrained subordinate CA costs? (Re: SSL Cert prices ($10 to $1500, you choose!))
The URL John forwarded gives survey of prices for regular certs and subdomain wildcard certs/super certs (ie *.mydomain.com all considered valid with respect to a single cert). Does anyone have info on the cost of sub-ordinate CA cert with a name space constraint (limited to issue certs on
Re: and constrained subordinate CA costs?
On Fri, Mar 25, 2005 at 04:02:36PM -0600, Matt Crawford wrote: There's an X.509v3 NameConstraints extension (which the higher CA would include in the lower CA's cert) but I have the impression that ends system software does not widely support it. And of course if you don't flag it
Re: Microsoft info-cards to use blind signatures?
Yes but the other context from the related group of blog postings, is Kim Cameron's (microsoft) laws of identity [1] that this comment is made in the context of. It is relatively hard to see how one could implement an identity system meeting the stated laws without involving blind signatures of
Re: use KDF2 / IEEE1363a (Re: expanding a password into many keys)
I suppose I should also have note that the master key going into KDF2 would be derived with PBKDF2 from a password if this is a password derived set of keys, to get the extra features of a salt and iterator to slow down brute force. Adam On Tue, Jun 14, 2005 at 04:21:39AM -0400, Adam Back wrote
Re: mother's maiden names...
I think in the UK check signatures are not verified below £30,000 (about US $53,000). I presume it is just economics ... cost of infrastructure to verify vs value of verifying given the fraud rate. Adam On Fri, Jul 15, 2005 at 01:42:08PM +0100, Ben Laurie wrote: My bank doesn't even bother to
locking door when window is open? (Re: solving the wrong problem)
Single picket fence -- doesn't work without a lot of explaining. The one I usually have usually heard is the obvious and intuitive locking the door when the window is open. (ie fixating on quality of dead-bolt, etc on the front door when the window beside it is _open_!) Adam On Sat, Aug 06,
Re: How many wrongs do you need to make a right?
Not to defend PKI, but what about delta-CRLs? Maybe not available at time of the Navy deployment? But certainly meaning that people can download just changes since last update. Steven writes: [alternatives] such as simply publishing the hash of revoked certificates, Well presumably you mean
e2e all the way (Re: Another entry in the internet security hall of shame....)
On Fri, Aug 26, 2005 at 11:41:42AM -0400, Steven M. Bellovin wrote: In message [EMAIL PROTECTED], Adam Back writes: Thats broken, just like the WAP GAP ... for security you want end2end security, not a secure channel to an UTP (untrusted third party)! What is security? What are you
e2e security by default (Re: e2e all the way)
OK summing up: I think e2e secure, and secure by default. On Fri, Aug 26, 2005 at 04:17:32PM -0400, Steven M. Bellovin wrote: On the contrary -- I did say that I support and use e2e security. I simply said that user-to-server security solves a lot of many -- most? -- people's security
Re: Defending users of unprotected login pages with TrustBar 0.4.9.93
I would think it would be safer to block the site, or provide a warning dialog. (This is what I was expecting when I started reading the head post; I was bit surprised at the interventionism to actually go ahead and fix the site, maybe that would be a better default behavior). btw Regarding
Re: OpenSSL BIGNUM vs. GMP
On Tue, Jan 03, 2006 at 10:10:50PM +, Ben Laurie wrote: Jack Lloyd wrote: Some relevant and recent data: in some tests I ran this weekend [gmp faster than openssl] AFAIK blinding alone can protect against all (publicly known) timing attacks; am I wrong about this? Yes, you are -
Re: long-term GPG signing key
There are a number of differences in key management priorities between (communication) signature and encryption keys. For encryption keys: - you want short lived keys - you should wipe the keys after at first opportunity - for archiving you should re-encrypt with storage keys - you can't detect
conservative choice: encrypt then MAC (Re: general defensive crypto coding principles)
Don't forget Bleichenbacher's error channel attack on SSL implementations, which focussed on the mac then encrypt design of SSL... web servers gave different error for malformed padding vs plaintext MAC failure. The lesson I drew from that is the conservative choice is encrypt then MAC. I dont
Re: Your secrets are safe with quasar encryption
How many suitable quasars are there? You'd be damn lucky if its a cryptograhic strength number. Now you might think there are limits to how many signals you can listen to and that would be some protection, however you still have brute force guess a signal, and probability of guessing the right
Re: Unforgeable Blinded Credentials
On Sat, Apr 01, 2006 at 12:35:12PM +0100, Ben Laurie wrote: However, anyone I show this proof to can then masquerade as a silver member, using my signed nonce. So, it occurred to me that an easy way to prevent this is to create a private/public key pair and instead of the nonce use the hash of
Re: Unforgeable Blinded Credentials
On Tue, Apr 04, 2006 at 06:15:48AM +0100, Ben Laurie wrote: This illustrates a problem with multi-show credentials, that the holder could share his credential freely, and in some cases even publish it, and this would allow non-authorized parties to use it. To avoid this, more complicated
Re: Unforgeable Blinded Credentials
On Sat, Apr 08, 2006 at 07:53:37PM +0100, Ben Laurie wrote: Adam Back wrote: [about Brands credentials] I think they shows are linkable, but if you show more than allowed times, all of the attributes are leaked, including the credential secret key and potentially some identifying
encrypted filesystem integrity threat-model (Re: Linux RNG paper)
I think an encrypted file system with builtin integrity is somewhat interesting however the threat model is a bit broken if you are going to boot off a potentially tampered with disk. I mean the attacker doesnt have to tamper with the proposed encrypted+MACed data, he just tampers with the boot
Re: Hamiltonian path as protection against DOS.
On Mon, Aug 14, 2006 at 12:23:03PM +1000, mikeiscool wrote: But you're imaging an attack with a distributed bot net DDoS'ing you, correct? Couldn't they then also use their botnet to process the messages faster then normally? They already have the computering power. Just a minor addon to the
Re: IGE mode is broken (Re: IGE mode in OpenSSL)
On Sat, Sep 09, 2006 at 09:39:04PM +0100, Ben Laurie wrote: There is some more detail here: Interesting. In fact, Gligor et al appear to have proposed IGE rather later than this date
Re: TPM disk crypto
So the part about being able to detect viruses, trojans and attest them between client-server apps that the client and server have a mutual interest to secure is fine and good. The bad part is that the user is not given control to modify the hash and attest as if it were the original so that he
Re: TPM disk crypto
has serious potential problems when most machine owners do not understand security). Does anyone know the current state of affairs on this issue within the Trusted Computing Group (and the marketed products of its members)? Adam Back wrote: So the part about being able to detect viruses
secure CRNGs and FIPS (Re: How important is FIPS 140-2 Level 1 cert?)
Anoymous wrote: [criticizing FIPS CRNGs] You can make a secure CRNG that you can obtain FIPS 140 certification on using the FIPS 186-2 appendix 3.1 (one of my clients got FIPS 140 on an implementation of the FIPS 186-2 RNG that I implemented for general key generation and such crypto use.) You
see also credentica announcement about U-prove (Re: IBM donates new privacy tool to open-source)
Related to this announcement, credentica.com (Stefan Brands' company) has released U-Prove, their toolkit SDK for doing limited-show, selective disclosure and other aspects of the Brands credentials. (Also on Stefans blog
announce: credlib library with brands and chaum credentials (Re: see also credentica announcement about U-prove)
Hi I implemented Chaumian and Brands credentials in a credential library (C code, using openSSL). I implemented some of the pre-computation steps. Have not made any attempt so far to benchmark it. But thought I could take this opportunity to make it public. I did not try to optimize so far.
private credential/ecash thread on slashdot (Re: announce: credlib library with brands and chaum credentials)
faced in deploying this stuff. Cant deploy what people dont understand! Adam -- On Fri, Feb 16, 2007 at 11:14:39AM -0500, Adam Back wrote: Hi I implemented Chaumian and Brands credentials in a credential library (C code, using openSSL). I implemented some
Re: New digital bearer cash site launched
I read some of the docs and ecache appears to be based on HMAC tickets, plus mixes. The problem I see is that you have to trust the mix. Now the documentation does mention that they anticipate 3rd party mixes, but still you have to trust those mixes also. And as we know from mixmaster etc.,
remote-attestation is not required (Re: The bank fraud blame game)
I do not believe the mentioned conflict exists. The aim of these calculator-like devices is to make sure that no malware, virus etc can create unauthorized transactions. The user should still be able to debug, and inspect the software in the calculator-like device, or virtual software
Re: remote-attestation is not required (Re: The bank fraud blame game)
I think you misread what I said about BIOS jumper required install. Ie this is not a one click install from email. It is something one user in 10,000 would even install at all! It would be more like people who program and install custom BIOSes or something, people who reverse-engineer security
Re: open source digital cash packages
credlib provides Brands' and Chaum credentials, both of which can be used for ecash. Adam On Mon, Sep 17, 2007 at 01:46:04PM -0400, Steven M. Bellovin wrote: Are there any open source digital cash packages available? I need one as part of another
Re: Password hashing
I would have thought PBKDF2 would be the obvious, standardized (PKCS #5 / RFC 2898) and designed for purpose method to derive a key from a password. PBKDF2 would typically be based on HMAC-SHA1. Should be straight-forward to use PBKDF2 with HMAC-SHA-256 instead for larger key sizes, or for
Re: Against Rekeying
Re: Against Rekeying
Seems people like bottom post around here. On Tue, Mar 23, 2010 at 8:51 PM, Nicolas Williams nicolas.willi...@sun.com wrote: On Tue, Mar 23, 2010 at 10:42:38AM -0500, Nicolas Williams wrote: On Tue, Mar 23, 2010 at 11:21:01AM -0400, Perry E. Metzger wrote: Ekr has an interesting blog post up
Re: [Cryptography] RSA equivalent key length/strength
On Sat, Sep 14, 2013 at 12:56:02PM -0400, Perry E. Metzger wrote: | requirement | Symmetric | RSA or DH| DSA subgroup | | for attack | key size | modulus size | size | +-+---+--+--+ |100
Re: [Cryptography] prism proof email, namespaces, and anonymity
On Fri, Sep 13, 2013 at 04:55:05PM -0400, John Kelsey wrote: The more I think about it, the more important it seems that any anonymous email like communications system *not* include people who don't want to be part of it, and have lots of defenses to prevent its anonymous communications from
[Cryptography] forward-secrecy =2048-bit in legacy browser/servers? (Re: RSA equivalent key length/strength)
On Wed, Sep 25, 2013 at 11:59:50PM +1200, Peter Gutmann wrote: Something that can sign a new RSA-2048 sub-certificate is called a CA. For a browser, it'll have to be a trusted CA. What I was asking you to explain is how the browsers are going to deal with over half a billion (source: Netcraft
Re: [Cryptography] TLS2
On Mon, Sep 30, 2013 at 11:49:49AM +0300, ianG wrote: On 30/09/13 11:02 AM, Adam Back wrote: no ASN.1, and no X.509 [...], encrypt and then MAC only, no non-forward secret ciphersuites, no baked in key length limits [...] support soft-hosting [...] Add TOFO for self-signed keys. Personally
Re: [Cryptography] TLS2
If we're going to do that I vote no ASN.1, and no X.509. Just BNF format like the base SSL protocol; encrypt and then MAC only, no non-forward secret ciphersuites, no baked in key length limits. I think I'd also vote for a lot less modes and ciphers. And probably non-NIST curves while we're at
[Cryptography] three crypto lists - why and which)
[Cryptography] are ECDSA curves provably not cooked? (Re: RSA equivalent key length/strength)
Re: [Cryptography] are ECDSA curves provably not cooked? (Re: RSA equivalent key length/strength)
On Tue, Oct 01, 2013 at 08:47:49AM -0700, Tony Arcieri wrote: On Tue, Oct 1, 2013 at 3:08 AM, Adam Back [1]a...@cypherspace.org wrote: But I do think it is a very interesting and pressing research question as to whether there are ways to plausibly deniably symmetrically weaken
[Cryptography] was this FIPS 186-1 (first DSA) an attemped NSA backdoor?
Some
[Cryptography] please dont weaken pre-image resistance of SHA3 (Re: NIST about to weaken SHA3?)
On Tue, Oct 01, 2013 at 12:47:56PM -0400, John Kelsey wrote: The actual technical question is whether an across the board 128 bit security level is sufficient for a hash function with a 256 bit output. This weakens the proposed SHA3-256 relative to SHA256 in preimage resistance, where SHA256
Re: A security bug in PGP products?
What they're saying is if you change the password, create some new data in the encrypted folder, then someone who knew the old password, can decrypt your new data. Why? Well because when you change the password they dont change the symmetric key used to encrypt the data. The password is used to | https://www.mail-archive.com/search?l=cryptography@metzdowd.com&q=from:%22Adam+Back%22 | CC-MAIN-2021-21 | refinedweb | 3,891 | 65.25 |
panda3d.core.MouseAndKeyboard¶
from panda3d.core import MouseAndKeyboard
- class
MouseAndKeyboard¶
Reads the mouse and/or keyboard data sent from a GraphicsWindow, and transmits it down the data graph.
The mouse and keyboard devices are bundled together into one device here, because they interrelate so much. A mouse might be constrained by the holding down of the shift key, for instance, or the clicking of the mouse button might be handled in much the same way as a keyboard key.
Mouse data is sent down the data graph as an x,y position as well as the set of buttons currently being held down; keyboard data is sent down as a set of keypress events in an EventDataTransition. To throw these events to the system, you must attach an EventThrower to the MouseAndKeyboard object; otherwise, the events will be discarded.
Inheritance diagram | https://docs.panda3d.org/1.10/python/reference/panda3d.core.MouseAndKeyboard | CC-MAIN-2020-29 | refinedweb | 141 | 56.89 |
Run checks on services like databases, queue servers, celery processes, etc.
Project description
This project checks for various conditions and provides reports when anomalous behavior is detected.
The following health checks are bundled with this project:
- cache
- database
- storage
- disk and memory utilization (via psutil)
- AWS S3 storage
- Celery task queue
Writing your own custom health checks is also very quick and easy.
We also like contributions, so don’t be afraid to make a pull request.
Use Cases
We officially only support the latest version of Python as well as the latest version of Django and the latest Django LTS version.
Note
The latest version to support Python 2 is 2.4.0
Installation.celery', # requires celery 'health_check.contrib.psutil', # disk and memory utilization; requires psutil 'health_check.contrib.s3boto_storage', # requires boto and S3BotoStorage backend ]
Setting up monitoring
If you want machine readable status reports you can request the /ht/ endpoint with the Accept HTTP header set to application/json." }
Writing a custom health check
Writing a health check is quick and easy:
from health_check.backends import BaseHealthCheckBackend class MyHealthCheckBackend(BaseHealthCheckBackend):'), ]
Other resources
- django-watchman is a package that does some of the same things in a slightly different way.
- See this weblog about configuring Django and health checking with AWS Elastic Load Balancer.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-health-check/3.5.0/ | CC-MAIN-2019-13 | refinedweb | 241 | 54.93 |
Hi,
I have written this run length encoding program to compress files. However when it is run, it is outputting each individual character with the occurrence, therefore making the file size larger!.
For example:
1. Original file - aaaaa
Compressed File - 5a
( this works like it should)
2. Original File - This is a test.
Compressed File - 1T1h1i1s1 1i1s1 1a1 1t1e1s1t1.1
(This doesn't, it makes the file larger! such be something such as: -16This is a test.)
Can anyone help me on getting strings such as these to output to the correct values.
Public String encode is where the conversion happens
Thanks
Scott
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; import java.io.*; public class RunLengthEncoding{ public String encode(String source) { StringBuffer dest = new StringBuffer(); for (int i = 0; i < source.length(); i++) { int runLength = 1; while( i+1 < source.length() && source.charAt(i) == source.charAt(i+1) ) { runLength++; i++; } dest.append(runLength); dest.append(source.charAt(i)); } return dest.toString(); } public static void main(String[] args) { Scanner dinp = new Scanner(System.in); String ufile; // the program asks the user to input the equation they would like to calculate System.out.println("Enter a file to compress "); // the input is received on the next line ufile = dinp.nextLine(); String fileName = ufile + ".txt"; Scanner inputStream = null; try { inputStream = new Scanner(new File(ufile)); } catch(FileNotFoundException e) { System.out.println("Error"); System.exit(0); } while (inputStream.hasNextLine()) { String line = inputStream.nextLine(); RunLengthEncoding RLE = new RunLengthEncoding(); String enc = (RLE.encode(line)); System.out.println(enc); try { FileWriter writer = new FileWriter(ufile + "-Compressed.txt",true); writer.write(enc + "\n"); writer.close(); } catch(IOException e) { System.out.println("nn"); } } inputStream.close(); } } | http://www.javaprogrammingforums.com/file-i-o-other-i-o-streams/2676-run-length-encoding-problem.html | CC-MAIN-2014-52 | refinedweb | 283 | 54.9 |
Introduction: Measuring Water Level With Ultrasonic Sensor methods are optical method, radar and ultrasonic method. Because we didn’t want to affect the quality of water in tank we implement one of the contactless methods.
What method to choose? All contactless methods work on same principle: we send a signal and we measure time that send signal needs to come back. Optical method uses optical signals. Optical method can be very accurate, but sensors can get dirty over time and we are not able to make measurement at all. Radar method uses radar signals. Because of that (radar signals are high RF signals) it is not suitable for DIY. Ultrasonic method is similar to radar. Instead of radar wave we are sending ultrasonic wave. This procedure is ideal for our needs because ultrasonic sensors are accessible and low priced.
We made water level meter with Arduino platform (we used Arduino Mega2560, but any arduino will work).
For damage occurred during reproduction I am not hold responsible.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Parts and Materials
Parts:
- Arduino (Uno, Mega 2560,...)
- ultrasonic sensor HC SR04
Materials:
- wires for connecting censor to Arduino
- acrylic glass for housing (optional)
Step 2: Theory Behind Ultrasonic Level Sensor
First, let us talk about some theory behind ultrasonic method of fluid lever measuring. The idea behind all contactless methods is to measure distance between transceiver and fluid. As said before, we transmit short ultrasonic pulse and we measure travel time of that pulse from transceiver to liquid and back to transceiver. Ultrasonic pulse will bounce from liquid level since because change of density of ultrasonic pulse travel medium (ultrasonic pulse first travel through air and bounce of liquid with higher density than air). Because water has higher density, majority of pulse will bounce off.
Two disadvantages exist with ultrasonic method:
- 1st: because of pulse length there is small window that we cannot receive pulse with transceiver because transceiver is transmitting. This problem is simple to solve: we placed our sensor higher from maximum water level for few centimeters allowing receiver to start receiving.
- 2nd: because of the beam width we are limited with tank diameter. If tank diameter is too small, signal could bounce of tank’s walls and could cause false readings.
Before installing sensor in tank we tested it for those two disadvantages. We established that we could have stable measurements from minimum distance of 5 cm from sensor. That means, we must install our sensor 5 cm higher then maximum water level. We also established that we didn’t have any problems with signal bouncing from tank’s walls with 7.5 cm diameter tank (tank’s length was 0.5 m). We complied these two results at construction of water tank and at the setting up of ultrasonic sensor.
Step 3: Water Tank pipe end cap as water tank cover. On end cap we mounted ultrasonic sensor. For larger stability we added wooden base, which will also house electronics and battery pack.
Here comes the mathematical specification of the tank. This part is essential, because we want to codify fluid height measurement in %. Starting point of codifying is measurement alone. Measurement can be between 6 and 56 cm (6 cm offset). This is codified into 0 to 100 %. It comes down to simple cross calculus.
We chose homogeneous tank because of easier calculations of volume (we are using pipe – cylindrical shape). Diameter of pipe is the same through the length of the pipe. We have also made equation whit which we can measure volume of water still in the tank. We didn’t implement this because there was no need for it. For now!
Step 4: Ultrasonic Sensor, Schematics
We soldered wires to ultrasonic sensor (we used FTP or UTP cable; it can be one of them). Then we installed sensor in small custom made housing from acrylic glass. Casing with sensor in it was sealed off and mounted on tank’s cover. Housing was a bit improvised and it is not essential. Because of that, there are no picture and no plans for it. You can figure it out somehow by yourself.
We connected sensor on Arduino board following schematic in picture.
Step 5: Program
We converted program for measuring distance to program for measuring water level. Program for measuring distance is not of our making but was found on internet in this tutorial we cannot find anymore.
First we transmit signal and then we wait and measure time between transmitted signal and received signal. This time is then converted to centimeter and centimeters are then converted to % and send via serial connection to computer. We could also calculate water volume that is still in the tank.
Attachments
Step 6: Testing
Because in the future we wish to implement automatic watering system with two stages regulator, we must measure tank’s flow characteristic. Question is why we must do that? You see, outgoing flow in the tank depends on hydrostatic pressure inside of the tank. With basic knowledge of physics anybody see that hydrostatic pressure id decreasing with falling water level in tank. Because we want to feed plants every time with same amount of water, we must adjust valve opening time. With tank’s flow characteristic we can calculate how much water can flow out of tank at any time and with that we can determine how long valve must stay in open position.
Also we wanted to test our level meter. We filled up water tank to maximum height. Then we opened a valve and let all the water run out. Because drain pipe is mounted to prevent sucking out sediments, tank was emptied to 2%. In picture is presented response to step function. From this response we can approximate function on which water level is changing (with Excel, Matlab, or other powerful mathematical tool).
We can conclude that sensor works in accordance with expectations.
Step 7: What's Next?
Implemented water level meter serves as a concept of principle. If we would want to use this meter in DIY project and in semi industrial or other applications we would have to make test of sensor endurance and resistance to water splattering. After that test we would be able to see if sensor is appropriate for use in DIY projects or any other environments. Right now I can only say that sensor is working fine within this short period of time.
Because sensor is measuring water level with contactless method water can stay unspoiled. Implemented meter is also cheap and accessible and because of this it is very suitable for DIY.
Please feel free to comment and let me know if I made any grammar mistakes (english is not my first language).
5 People Made This Project!
See 1 More
Recommendations
62 Discussions
4 days ago
Hi,
Thanks for the inspiration !
I made some adjustments to send the data on mqtt. The pins you use do not work together with an Ethernet Shield W5100. I used pins 8 and 9 for this setup.
the code ;):
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient = "192.168.1.16";
// Ethernet and MQTT related objects
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
//Begin Water Measuring
// fill in you're measurements
int heightwell = 200; //inside height of the well in cm
int diameter = 235; //inside diameter of the wel in cm
int volume = 8760; //total volume of the well (measuring from the bottom to the lower edge of the overflow)(volume of cilinder = pi*r²*height)
long WaterVolume = "WaterVolume"; //mqtt topic for the volume
long WaterVolumePercent = "WaterVolumePercent"; //mqtt topic for the %
int trigPin = 9; // Trigger
int echoPin = 8; // Echo
float restvolume;
int liters;
int restdistance;
int radius;
int percent;
long duration, distance;
//End Water Measuring
void setup()
{
Serial.begin (9600);
//Begin Water Measuring
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//End Water Measuring
//...");
}
}
void loop()
{
//Begin Water Measuring
//
distance = (duration / 2) / 29.1; // Divide by 29.1 or multiply by 0.0343
restdistance = heightwell - distance;
radius = diameter / 2;
restvolume = (3.14 * (radius * radius) * restdistance) / 1000;
percent = (restvolume / volume) * 100;
Serial.print("distance: ");
Serial.print(distance);
Serial.print("cm ");
Serial.print("restvolume: ");
Serial.print(restvolume);
Serial.print("L ");
Serial.print("percent: ");
Serial.print(percent);
Serial.print("%");
Serial.println();
//Message String
char distString[5];
dtostrf(restvolume, 4, 0, distString);
char percString[5];
dtostrf(percent, 4, 0, percString);
//End Water Measuring
//MQTT Begin
// Ensure that we are subscribed to the topic
mqttClient.subscribe(WaterVolume);
// Attempt to publish a value to the topic
if(mqttClient.publish(WaterVolume, distString))
{
Serial.println("Publish Volume success");
}
else
{
Serial.println("Could not send Volume :(");
}
// Ensure that we are subscribed to the topic
mqttClient.subscribe(WaterVolumePercent);
// Attempt to publish a value to the topic
if(mqttClient.publish(WaterVolumePercent, percString))
{
Serial.println("Publish VolumePercent success");
}
else
{
Serial.println("Could not send VolumePercent :(");
}
// Dont overload the server!
delay(4000);
}
void subscribeReceive(char* topic, byte* payload, unsigned int length)
{
// Print the topic
Serial.print("Topic: ");
Serial.println(topic);
// Print the message
Serial.print("Message: ");
for(int i = 0; i < length; i ++)
{
Serial.print(char(payload[i]));
}
// Print a newline
Serial.println("");
}
//MQTT End
kind regards
1 year ago
Great use of ultrasonics!
Refering to your comments regarding the longevity of the system. Past work experience with the cheap readily available ultrasonic transducers has taught me that they do not like water. The aluminium case and grille corrode and the internals of the piezo electric transducer eventually gives up. There are water proof versions as used on car reversing devices but their sesitivity is much lower than the cheap common open versions. The reduced sensitivity may be OK for shorter range and larger targets that produce larger echo.
A few tips for increasing the life of these open transducers.
1/ Prevent water spray onto the transducer. In the past I have used barrier materials to take the energy out of spray and prevent the majority of direct water contact. Utrasonics have strange properties and what may look opaque to you may be perfectly transparent to utrasonics. The coarse nylon material that pan scrubbers are made from produces a good barrier that drains easily and the transducer simply "sees" straight through.
2/ Humidity. The interior of a water tank gets very humid under the right conditions and that humidity will make short work of your tranducers. Try to provide ventilation arround your tranducers to keep the humidity low, vent to the outside. Your transducers can "look" in through a well placed hole while enjoying the fresh dry air outside the tank.
Ultrasonics may pick up features that you do not wish them to see. Features on a tank wall or the rim of a hole for example. The beam shape from ultrasonic transducers can be shaped to prevent this. Similarly as you can with light, reflectors and baffles may be applied to tranducers to shape / limit the beam. Trial & error is the only easy method for the home inventor for getting this right.
Minimum detection range. When attempting to detect in the coser ranges, problems can be encountered due to cross-talk directly between the tranducers. Software can be modified to include a "dead zone" an echo time interval below which the readings are ignored. Isolating the transmitter and receiver sound can also help with this problem.
Keep inventing.
Reply 14 days ago
Hello
You have displayed vast knowledge of the project. I am researching on building a fuel level remote sensing system. Is this sensor suitable or can you suggest a better sensor for the project? Secondly, if you have any other aid or advice you can render to my successful completion of the project, kindly share with me. WHATSAPP +2348149830651
Reply 12 days ago
I would advise against the use of this system in a fuel environment. I personally would look into approved technologies such as those used in vehicle fuel tanks and adapt to suit your own application. Inventing is fun but all engineering comes with a responsibility for safety. Good luck with your project.
6 weeks ago
HC-SR04 measures distances of 2cm to 400cm
9 months ago
I'm trying this for my school project, please help me whit code.I can't download the code.please can anyone help me with code for this project?
Question 11 months ago
Hello, can this same procedure be used to determine the level of gas in a gas bottle,? instead of placing the transducer above the liquid level guess it will be placed at the bottom
3 years ago
can this sensor pass sound wave through arcylic sheet ? or you need to make two holes for each sensor ?
reply at
look4ursoul@live.com
thanks
Reply 1 year ago
The acrylic will reflect part of the ultrasonic and the rest will go further and get detected when it comes back. You may need to ignore this time by including it into dead zone as @andytechdude mentioned.
1 year ago
does this applicable for bigger tanks like water tanks.
Question 1 year ago
Loved this! Thankyou.
Quick question. Can i measure the volume of an irregular shaped tank?
Thanks Ben.
Question 1 year ago
What is the maximum depth that we can measure using this sensor ?
Question 2 years ago
Using Port : COM17
Using Programmer : arduino
Overriding Baud Rate : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x68
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x68
avrdude done.
I facing this kinda error. Help me. Thanks.
5 years ago
Excellent idea! I suspect the sensors could be covered with food-wrap film to splash proof them without interfering too much with their operation.
I'll be trying it!
Reply 5 years ago on Introduction
Hmm... Food foil could work but I am a bit skeptical! Ultrasonic (or ultrasound) wave are same as sound just frequency is to high for you to hear it. Ultrasonic waves are mechanical waves of presure. Because of that, foil can interupt with measurment! This is why radar method is better in industry because it use high frequency electromagnetic waves which can penetrate some materials and waterproofing a transceiver is not so hard.
Reply 5 years ago
I was thinking of the thin plastic film ("cling film" in the UK).
It's very thin and flexible, and I think it would vibrate with the ultrasound to transmit the vibrations if it was stretched over the sensors.
The calibration may need some adjustment, but I think it might work.
I'll try it and report back. :)
Reply 5 years ago on Introduction
Let me know about the results! I am very curious if this foil you are talking about will work! =)
Reply 5 years ago
It does. :)
I tried it.... You need stretch the film over each sensor individually to avoid vibration transfer between the two, but otherwise it seems fine.
I just stretched film across the front of the sensors, folded it back along the sensor bodies and held it in place with rubber bands.
I couldn't see any difference in readings between the sensor with or without the film.
I suspect it would work with thin polythene as well, but I haven't tried that yet.
Reply 2 years ago
Waw thats nice.. That was something I was also looking for. Since you already tried it, I have no worries. Out of a curiosity can you find any difference in result after wrapping it in film.
I made a similar one at my home water tank. but at summer when water getting vaporized and it getting on the sensor.
Reply 5 years ago on Introduction
Awesome! =D
Thanks for update! | https://www.instructables.com/id/Measuring-water-level-with-ultrasonic-sensor/ | CC-MAIN-2020-16 | refinedweb | 2,775 | 65.01 |
The C# Data Types and Programming Constructs
Boxing and Unboxing
The conversion of a value type into a reference type is termed as boxing; the conversion of a reference type into a value type is termed as unboxing. Verify the code in Listing 3:
Listing 3
// Value type int X = 100; // x boxed to a object type which is reference based, // no explicit cast required object Y = X; // y unboxed to an integer type, explicit cast required // while unboxing int Z = (int)Y
Programming Constructs
If - Else
This is one of the popular decision-making statements, which is similar to that of its C++ and Java counterparts. Its usage is given below.
Usage
if(Condition) { Statements } else { Statements }
If the condition satisfies, the statements inside the if block will be executed; otherwise, statements inside the else part will execute as shown in Listing 4:
Listing 4
using System;
class Fund
{
public static void Main()
{
int x1 = 50;
int x2 = 100;
if(x1>x2)
{
Console.WriteLine("X1 is greater");
{
else
{
Console.WriteLine("X2 is greater")
}
}
}
Switch - Case
This is also one of the decision-making statements which is regarded as an alternative to if - else. Its usage is given below.
Usage
switch(expression) { case 10: Number is 10;break case 20: Number is 20;break case else: Illegal Entry;break }
When the expression matches with a case value, the corresponding statements would be printed. Listing 5 explains the usage of Switch - Case statement.
Listing 5
using System; class Switchexample { public static void Main() { int wday = 2; switch(wday) { case 1: Console.WriteLine("Monday");break; case 2: Console.WriteLine("Tuesday");break; } } }
Looping Statements
For loop
This loop is used to iterate a value fixed number of times. Its usage is given below:
Usage
for(Initial Value, Condition, Incrementation / Decrementation) { Statements }
You have to specify Incrementation and Decrementation using ++ and - operators. Listing 6 examines the working of the for loop. Here, numbers from 1 to 10 will be printed as output. 10 will also be printed because we have used <= operator. Try using only the +< operator and observe the result.
Listing 6
using System; class Forexample { public static void Main() { for(int I = 1; I<=10;I++) { Console.WriteLine(I); } } }
While loop
This loop is similar to the for loop, except that condition is specified first and is used to repeat a statement as long as a particular condition is true. The usage of while loop is given below:
while(Condition) { Statements }
If the condition is false, statements within the loop will not be executed. Listing 7 examines the working of while loop:
Listing 7
using System; class Whileexample { public static void Main() { int I = 1; while(I <=10) { console.WriteLine(I); } } }
Do - While
This looping statement is also similar to that of the previous one but the condition is specified last. Its usage is given below:
Usage
do { Statements }while(Condition)
In this case, the condition is tested at the end of the loop. Hence, the statements within the loop are executed at least once, even if the condition is false. Let's verify an example:
Listing 8
using System; class Whileexample { public static void Main() { do { int I = 1; } while(I<=10); Console.WriteLine(I); } }
Foreach
If you had used Visual Basic, you would be familiar with the foreach statement. C# also supports this statement. Listing 9 illustrates the usage of this statement:
Listing 9
using System; using System.Collections; class Foreachdemo { public ArrayList numbers; Foreachdemo() { numbers = new ArrayList(); numbers.Add("One"); numbers.Add("Two"); numbers.Add("Three"); numbers.Add("Four"); numbers.Add("Five"); } public static void Main() { Foreachdemo fed = new Foreachdemo(); foreach(string num in fed.numbers) { Console.WriteLine("{0}",num); } }
In the above example, an object of type ArrayList is created and values are added to it using the Add method of the ArrayList class. Try removing the second using directive and observe the result.
Break statement
This statement is used to terminate a loop abruptly. We have seen the usage of this statement while discussing decision-making statements. Listing 10 examines the working of this statement.
Listing 10
using System; class Whileexample { public static void Main() { for(int I = 1; I<=10; I++) { Console.WriteLine(I); if(I==5) { break; } } } }.
# # #
Page 2 of 2
| http://www.developer.com/net/csharp/article.php/10918_1466421_2/The-C-Data-Types-and-Programming-Constructs.htm | CC-MAIN-2015-18 | refinedweb | 706 | 54.22 |
Python Event Tutorial
The Python interface to Rocket exposes a DOM API in a very similar way to Javascript. Python code can be attached to any event in the RML definition which in turn can dynamically update any part of the document, including opening new documents. Full source code to the final PyInvaders application can be found in the samples folder once the Python plugin has been installed.
Step 1: Setting up the Python environment
Make sure you've got the required Python support packages installed. For more information, see this page.
The first thing we need to do is initialise Python in our application. Once we have done this we can start executing scripts. We're going to make a PythonInterface class that will hide all the Python intricacies.
/** Creates and maintains the Python interface to Invaders. */ class PythonInterface { public: static bool Initialise(); static void Shutdown(); private: PythonInterface(); ~PythonInterface(); };
We then implement these methods.
NOTE: Its a good idea to forcibly import the libRocket Python module. This ensures all Boost bindings have been done and that you can proceed to expose your own classes that rely on these bindings having taken place.
NOTE: For more information Python initialisation and shutdown please see the Python documentation at
bool PythonInterface::Initialise() { Py_Initialize(); // Pull in the Rocket Python module. Py_XDECREF(PyImport_ImportModule("rocket")); return true; } void PythonInterface::Shutdown() { Py_Finalize(); }
PythonInterface::Initialise should be called before Rocket is initialised. This ensures the Python bindings are available when Rocket starts up.
PythonInterface::Shutdown should be called after you've released all contexts but before you call Rocket::Shutdown(). This ensures all Python objects are released before Rocket does its final cleanup.
At this point you'll need to add the relevant Python and Boost::Python build paths to your project and then compile and link your project.
Step 2: Replacing the Event System
We can now completely remove the existing event system from RocketInvaders as the Python bindings will do all the event management for us. Remove all source and header files that begin with Event. You'll also need to comment out some code in GameElement.cpp and Game.cpp that call the EventManager directly. We'll get back to those later.
Also remove all the EventManager initialisation from main.cpp as we'll replace it with a new Python script. I suggest you name it autoexec.py and place it in a python subfolder. It should look something like this:
import rocket context = rocket.GetContext('main') context.LoadDocument('data/background.rml').Show() context.LoadDocument('data/main_menu.rml').Show()
To run this script, we simply need to import it at application start up. Add an import helper to the PythonInterface and call it just before the main shell loop.
bool PythonInterface::Import(const EMP::Core::String& name) { PyObject* module = PyImport_ImportModule(name.CString()); if (!module) { PyErr_Print(); return false; } Py_DECREF(module); return true; }
PythonInterface::Import("autoexec"); Shell::EventLoop(GameLoop);
At this point the RocketInvaders will now run, however you'll get a script import error because autoexec cannot be found. To fix this we'll need to add the python folder to our Python search path.
NOTE: On Windows this error will go to stdout, which will not be visible. I suggest you grab a copy of DoAllocConsole() from the pyinvaders sample and drop it into your project. Call DoAllocConsole() at the start of your main function and you'll get a console for reading Python error messages.
My PythonInterface::Initialise now looks like this:; return true; }
This will get us further, you should see the main menu load, however you'll notice a Python error on your console when Python attempts to execute the old onload event in mainmenu.rml. Update the onload and onunload events to use Python script which will correctly display and hide the logo.
<body template="window" onload="document.context.LoadDocument('data/logo.rml').Show()" onunload="document.context.logo.Close()">
You will now have to go through each event defined in RML updating it with equivalent Python calls.
RocketPython parses any semi-colons in an event as a delimiter. So you can place multiple Python statements on a single line, semi-colon separated. This comes in useful when you want to execute two statements at once, for example you probably want to do the following for the Start Game button.
document.context.LoadDocument('data/start_game.rml').Show(); document.Close()
I've simplified this further by by placing a LoadMenu function in the shared template window.rml, that loads a new document, closing the existing one.
Step 3: Exposing Game Functions
The above takes care of most of the menu flow, except for a couple items, including the starting of the actual game and exiting. Lets tackle exiting first as that the easier of the two.
Our Python interface class will now have to expose a Python module (with the help of boost::python - for full documentation see).
BOOST_PYTHON_MODULE(game) { python::def("Shutdown", &Shell::RequestExit); }
This creates a module called game and places a Shutdown method within it. We now update the Initialise function to initialise this module at startup.; // Define our game specific interface initgame(); return true; }
We can now call the Shutdown function from main_menu.rml as follows
<button onclick="import game;game.Shutdown()">Exit</button>
If you have a lot of functions that call game, you can place the import game in the document header, or in one of your template files.
Using the above code we can extrapolate this throughout the game and have a complete functioning menu system. You will however need to expose more of the GameDetails class to Python so that the start_game screen can save the difficulty and colour selection.
Your game module should look something like this:
BOOST_PYTHON_MODULE(game) { python::def("Shutdown", &Shell::RequestExit); python::def("SetPaused", &GameDetails::SetPaused); python::def("SetDifficulty", &GameDetails::SetDifficulty); python::def("SetDefenderColour", &GameDetails::SetDefenderColour); python::enum_<GameDetails::Difficulty>("difficulty") .value("HARD", GameDetails::HARD) .value("EASY", GameDetails::EASY) ; }
Step 4: Custom Elements
The next problem we'll hit when converting RocketInvaders is the ElementGame does not have a Python interface. Thus we can't give it focus when we start the game which means the defender cannot be moved until the user clicks the game with the mouse. To fix this, we need to define ElementGame to Python and register the Python instancer with Rocket::Factory instead of the C++ instancer.
Let's define a static method on ElementGame to do this and call it from our game module's initialisation.
void ElementGame::InitialisePythonInterface() { PyObject* object = python::class_<ElementGame, Rocket::Core::Python::ElementWrapper<ElementGame>, python::bases<Rocket::Core::Element>, boost::noncopyable >("ElementGame", python::init<const char*>()) .ptr(); Rocket::Core::Factory::RegisterElementInstancer("game", new Rocket::Core::Python::ElementInstancer(object))->RemoveReference(); }
Step 5: Key and end game bindings
We can now get into the game, however the game will never finish as there's no key bindings for processing the ESCAPE key and nothing will make the game exit when the game is over. Fixing the key binding is easy, simply drop in a 'onkeydown' handler and make it launch the pause menu.
The game over event is a bit more tricky, as the old Invaders would call EventManager::LoadWindow directly from C++. We're going to have to add a game_over flag to game and make the GameElement check this state every update and fire a custom 'gameover' event.
// Updates the game. void ElementGame::OnUpdate() { game->Update(); if (game->IsGameOver()) DispatchEvent("gameover", EMP::Core::Dictionary(), false); }
Step 6: Python Data Formatters
We're still using C++ data formatters for the high scores, these can be moved into Python for simplicity.
Here's my name formatter:
class NameDataFormatter(rocket.DataFormatter): def __init__(self): rocket.DataFormatter.__init__(self, "name") def FormatData(self, raw_data): """ Data format: raw_data[0] is the name. raw_data[1] is a bool - True means the name has to be entered. False means the name has been entered already. """ formatted_data = "" if (raw_data[1] == "1"):" else: formatted_data = raw_data[0] return formatted_data
A lot more code could be moved from C++ into Python, for example the HighScore system. Its just a matter of taking the principles described here and applying them. | http://librocket.com/wiki/documentation/tutorials/PythonEventSystem | CC-MAIN-2014-15 | refinedweb | 1,359 | 55.13 |
Date: Thu, 6 Aug 1998 10:43:19 +1000 From: Richard Gooch <Richard.Gooch@atnf.CSIRO.AU> I hope you don't feel I'm a fanatic. Yes, I strongly believe in the correctness of the idea. And I've not yet heard of practical solutions to all of the problems devfs fixes.No, but certain devfs "cheerleaders" have been responsible for at least20 or 30 messages to linux-kernel just in the last 18 hours. Most ofthe messages say the same thing over and over again, as they feelcomprelled to reply to any argument that might say anything vaguelynegative about devfs, even if they've already tried to make theidentical point twenty times before. This is why I had originally givenup trying to debate the issue on linux-kernel, and why think devfs is alot like GGI in terms of the type of discussion it inspires. 1) devfs doesn't have to be mounted onto /dev if you don't like. The essential thing is that devfs provides a unique, logical namespace. You can always mount devfs elsewhere and make symlinks to it if you don't like the namesWe already have a unique, logical namespace; it's called minor and majordevice numbers. I know you (and others) don't like them, but many ofthe arguments against them are strawman arguments --- such as assumingthat you will create all possible device files in /dev, whether or notthe devices exist, and then complaining about the speed problem. Or bydismissing the reality that the dcache really does make the speed lookupproblem pretty much irrelevant. (Yet in the last 18 hours, I can'tcount how many times I've just hit 'd' to messages which made the sameflawed arguments over and over again.) 2) which hacks are these? You mean using tar to save and restore the permissions? Would you prefer a C programme (something I'm contemplating doing)Precisely. In Unix we have a very well developed abstraction for savingthis kind of state: permissions, user/group ownership, modtimes, etc.It's called a filesystem. Tar is an unmitigated hack; using a C programhelps hide the fact that what you're doing is a hack, but it's still ahack. What about the problem of when we move to 16 bit majors and the major table is dropped and we go to searching a list when we open a device node? How do you suggest we solve that?Going to 32-bit device numbers can be easily done during Linux 2.3; theglibc interface already supports it. We know where to store the 32-bitdevice in the ext2 filesystem, and how to do so in a backwardscompatible way; we have abstractions in place that should make it moreor less painless to go to using 32-bit device numbers. It's a merematter of programming, and it isn't a lot of programming at that.As far as searching a list when we open a major number, again this is aextremely flawed and weak argument. First of all, the vast majority ofsystems out there will only have less than 16 major devices. A typicalsystem has less than 10 major devices. (cat /proc/devices and see!) Sosearching the list is simply not a problem. If searching the list werean issue, there are plenty of ways of solving this problem internal tothe kernel, without needing to make any user-visible changes --- suchusing hash table. We use hash tables for searching the inode cache --- you're not going totell me that inode caches are bad just because a stupid implementationwould have to sequentially search the entire list, are you?!? :-) Thisis what I call a strawman argument, and many of the devfs cheerleedershave been using such strawmans to argue their case. - Ted-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.rutgers.eduPlease read the FAQ at | https://lkml.org/lkml/1998/8/6/139 | CC-MAIN-2016-22 | refinedweb | 649 | 62.38 |
These are the wikipages to discuss and plan the localization (L10N) and translation of MeeGo.
The Localization working group defines the strategy for using crowd-sourcing for translating MeeGo into multiple languages, and observes its implementation. Using transifex.net as the tool, our goal is to build a community of dedicated translators, editors, reviewers, and testers in multiple languages.
(Note: This list might be partially outdated.)
The main areas within the scope of the working group are (in no particular order):
MeeGo uses Transifex for translating.
If you would like to have a language specific wikipage for your team, please create it under the namespace "Localization". Example: For the language with the language code xy, please create and link to it from Language specific working groups.
(Note: Content in this list might be outdated.)
MeeGo members interested in taking an active role in this working group. Please detail your interests and what you can contribute to the group:
A complete list of the pages in this space can be found in the localization category. | http://wiki.meego.com/index.php?title=Localization_team&diff=39698&oldid=39691 | CC-MAIN-2013-20 | refinedweb | 174 | 54.02 |
"records" and the columns are "fields". Sometimes you want to add an additional field to the dbf file to capture some new type of information not originally included.
Today's example shows you how to use pyshp to add a new field to an existing shapefile. This operation is a two-step process. You must first update the dbf header to define the new field. Then you must update each record to account for a new column in the database so everything is balanced.
In the past, I've demonstrated modifying existing shapefiles for other reasons including merging shapefiles and deleting features in shapefiles. In every case you are actually reading in the existing shapefile, creating a new shapefile in memory and then writing out the new file either separately or on top of the old one. Even in really high-end GIS packages that's basically all you're doing. Some packages will use a temporary file in between.
Here's the example. We'll create a counter that gives us unique sample data to append to each record just so we can see the changes clearly. In the real world, you'd probably just insert a blank palce holder.
import shapefile # Read in our existing shapefile r = shapefile.Reader("Mississippi") # Create a new shapefile in memory w = shapefile.Writer() # Copy over the existing fields w.fields = list(r.fields) # Add our new field using the pyshp API w.field("KINSELLA", "C", "40") # We'll create a counter in this example # to give us sample data to add to the records # so we know the field is working correctly. i=1 # Loop through each record, add a column. We'll # insert our sample data but you could also just # insert a blank string or NULL DATA number # as a place holder for rec in r.records(): rec.append(i) i+=1 # Add the modified record to the new shapefile w.records.append(rec) # Copy over the geometry without any changes w._shapes.extend(r.shapes()) # Save as a new shapefile (or write over the old one) w.save("Miss")
So there you have it. Overall it's a pretty simple process that can be extended to do some sophisticated operations. The sample Mississippi shapefile can be found here. But this shapefile only has one record so it's not that interesting. But it's lightweight and easy to examine the dbf file in your favorite spreadsheet program. | http://geospatialpython.com/2013_04_01_archive.html | CC-MAIN-2017-26 | refinedweb | 408 | 66.44 |
Automatic Bird Identification: Part II
May 10, 2020, 2 p.m. by Avery Uslaner directories BASE_PATH = "/ML/Birds" # based on the base path, derive the images path IMAGES_PATH = path.sep.join([BASE_PATH, "DATA"]) LABELS_PATH = "/bird_ml/dataset.csv" MX_OUTPUT = BASE_PATH TRAIN_MX_LIST = path.sep.join([MX_OUTPUT, "lists/train.lst"]) VAL_MX_LIST = path.sep.join([MX_OUTPUT, "lists/val.lst"]) TEST_MX_LIST = path.sep.join([MX_OUTPUT, "lists/test.lst"]) TRAIN_MX_REC = path.sep.join([MX_OUTPUT, "rec/train.rec"]) VAL_MX_REC = path.sep.join([MX_OUTPUT, "rec/val.rec"]) TEST_MX_REC = path.sep.join([MX_OUTPUT, "rec/test.rec"]) # Label encoder used to convert species names to integer categories LABEL_ENCODER_PATH = path.sep.join([BASE_PATH, "output/le.cpickle"]) # define the RGB means from the ImageNet dataset R_MEAN = 123.68 G_MEAN = 116.779 B_MEAN = 103.939 # define the percentage of validation and testing images relative # to the number of training images NUM_CLASSES = 2 NUM_VAL_IMAGES = 0.15 NUM_TEST_IMAGES = 0.15 # define the batch size BATCH_SIZE = 32 NUM_DEVICES = 1
The RBG means are taken from the original Imagenet paper by Simonyan and Zisserman. That way we can fine tune an existing Imagenet trained model rather than training our model entirely from scratch.
This first model will only attempt to classify 2 classes since we don't have much training data yet and we only want to make sure our data processing pipeline is functioning properly. We're not expecting a high quality model just yet.
Building the Record File Dataset
While our image dataset is already created, our model actually needs to consume rec files rather than raw image files so creating those will be our next step. The rec files are essentially just images compressed into the record file format. Their creation will be handled by the im2rec.py file included with the MxNet framework, but we'll use our own script to create the lst files that serve to pair each image filepath with it's encoded bird species class.
from config import bird_config as config from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split import progressbar import pickle import os # read the contents of the labels file, then initialize the list of # image paths and labels print("[INFO] loading image paths and labels...") rows = open(config.LABELS_PATH).read() rows = rows.strip().split("\n")[1:] trainPaths = [] trainLabels = [] # loop over the rows for row in rows: # unpack the row, then update the image paths and labels list filename, species = row.split(",") filename = filename[filename.rfind("/") + 1:] trainPaths.append(os.sep.join([config.IMAGES_PATH, filename])) trainLabels.append(species) # now that we have the total number of images in the dataset that # can be used for training, compute the number of images that # should be used for validation and testing numVal = int(len(trainPaths) * config.NUM_VAL_IMAGES) numTest = int(len(trainPaths) * config.NUM_TEST_IMAGES) # our class labels are represented as strings so we need to encode # them print("[INFO] encoding labels...") le = LabelEncoder().fit(trainLabels) trainLabels = le.transform(trainLabels) # perform sampling from the training set to construct a a validation # set print("[INFO] constructing validation data...") split = train_test_split(trainPaths, trainLabels, test_size=numVal, stratify=trainLabels) (trainPaths, valPaths, trainLabels, valLabels) = split # perform stratified sampling from the training set to construct a # a testing set print("[INFO] constructing testing data...") split = train_test_split(trainPaths, trainLabels, test_size=numTest, stratify=trainLabels) (trainPaths, testPaths, trainLabels, testLabels) = split # construct a list pairing the training, validation, and testing # image paths along with their corresponding labels and output list # files datasets = [ ("train", trainPaths, trainLabels, config.TRAIN_MX_LIST), ("val", valPaths, valLabels, config.VAL_MX_LIST), ("test", testPaths, testLabels, config.TEST_MX_LIST)] # loop over the dataset tuples for (dType, paths, labels, outputPath) in datasets: # open the output file for writing print("[INFO] building {}...".format(outputPath)) f = open(outputPath, "w") # initialize the progress bar widgets = ["Building List: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA()] pbar = progressbar.ProgressBar(maxval=len(paths), widgets=widgets).start() # loop over each of the individual images + labels for (i, (path, label)) in enumerate(zip(paths, labels)): # write the image index, label, and output path to file row = "\t".join([str(i), str(label), path]) f.write("{}\n".format(row)) pbar.update(i) # close the output file pbar.finish() f.close() # write the label encoder to file print("[INFO] serializing label encoder...") f = open(config.LABEL_ENCODER_PATH, "wb") f.write(pickle.dumps(le)) f.close()
Running our build dataset script will create the lst files in the directory defined by the config file we created earlier. Now that we have those, we can run the im2rec script to generate the rec files.
To make things easy I grabbed the im2py script off of MxNet's github and put it in my project directory:
cd /bird_ml/ wget
To make generation of the rec files easier, I wrote a small script to create and organize them.
build_rec_files.py:
#!/bin/bash /bird_ml/venv/bin/python /bird_ml/im2rec.py \ --resize 256 --quality 100 --encoding '.jpg' /ML/Birds/lists "" mv /ML/Birds/lists/*.idx /ML/Birds/rec mv /ML/Birds/lists/*.rec /ML/Birds/rec
Now that we have our rec files, we're ready to start training! I'll handle that in the next post. | https://averyuslaner.com/automatic-bird-identification-part-ii/ | CC-MAIN-2022-21 | refinedweb | 837 | 50.84 |
Type: Posts; User: Chris ZANARDI
Yes, it's the problem.
What I do now is I keep my exe alive as long as my AUDROS application is alive. So the icons stay correct.
Thanks.
hi gurus
I try to make an exe to change the icon of a window of an other application.
here my code :
#include "stdafx.h"
#include <winbase.h>
#include <windows.h>
Hi Gurus
I'trying to make an exe to change the icon of the window of an other application.
Here my code :
#include "stdafx.h"
#include <winbase.h>
#include <windows.h>
Thank you, Craig
Your way was the good one. In fact, I reach my goal using :
Me.Context.Response.Buffer = False
Me.Context.Response.Cache.SetExpires(Now())
With these to line, I go...
Hello All,
I would like to trap the event that occurs when the user clicks on the REFRESH BUTTON in my webform1.aspx.vb
Any idea ?
Yeeeesssss !!! I display succesfully the form. But one problem back, ten problems front (don't know if it's really correct)
The new problem is that it's know impossible to interract with the form,...
Sorry but it is still not working
I join a screen copy to show u
Well, I don't understand what you mean with 'not using correct version of ocx ' coz if I see in the html page the pink rectangle with the button...
OK, can you try on your computer this example :...
Very interresting subject.
I tried your project and it works fine. But if :
- I build the project1.ocx
- Register the test1.ocx using regsvr32
- Edit an html page to loag the ocx
When load the...
Hello All,
I am actually doing a library of subs and functions that will be use by collegues in the office.
I would like to describe, when usefull, the list of possible values available for...
Hello all
It is possible so set the style of the html tag INPUT in a style sheet (.css) and my question is :
Is it possible to set the style of the html tag INPUT only when the type of the...
Thank you for your interset, Andy, but the code you send me is not exactly what I need : you just switch the key and text values, but the job is not done on the children of the node you move. Your...
This is at runtime. I want for example :
1 - user select a node
2 - hit a button UP or DOWN
==> The node goes up or down until it reach the first or the last position of its current level
Hello All,
Does anybody know how to move a node up or down in a treeview ctrl, in a same level.
Say in other words, moving a node before its upper brother or after its lower brother
changing... | http://forums.codeguru.com/search.php?s=30c088d9f4e788c144588528ae9c8ab2&searchid=7002865 | CC-MAIN-2015-22 | refinedweb | 472 | 83.46 |
The Viz3d class represents a 3D visualizer window. This class is implicitly shared. More...
#include <opencv2/viz/viz3d.hpp>
The constructors.
Add a light in the scene.
Transforms a point in window coordinate system to a 3D ray in world coordinate system.
Transforms a point in world coordinate system to window coordinate system.
Returns a camera object that contains intrinsic parameters of the current viewer.
Returns rendering property of a widget.
Rendering property can be one of the following:
REPRESENTATION: Expected values are
IMMEDIATE_RENDERING:
SHADING: Expected values are
Returns the current pose of the viewer.
Retrieves a widget from the window.
A widget is implicitly shared; that is, if the returned widget is modified, the changes will be immediately visible in the window.
Returns the current pose of a widget in the window.
Returns the name of the window which has been set in the constructor.
Viz - is prepended to the name if necessary.
Returns the current size of the window.
Sets keyboard handler.
Sets mouse handler.
Remove all lights from the current scene.
Removes all widgets from the window.
Removes a widget from the window.
Resets camera.
Resets camera viewpoint to a 3D widget in the scene.
Saves screenshot of the current scene.
Sets background color.
Sets or unsets full-screen rendering mode.
Create a window in memory instead of on the screen.
Sets rendering property of a widget.
Rendering property can be one of the following:
REPRESENTATION: Expected values are
IMMEDIATE_RENDERING:
SHADING: Expected values are
Sets geometry representation of the widgets to surface, wireframe or points.
Sets pose of the viewer.
Sets pose of a widget in the window.
Sets the position of the window in the screen.
Sets the size of the window.
Removed all widgets and displays image scaled to whole window area.
Shows a widget in the window.
The window renders and starts the event loop.
Starts the event loop for a given time.
Updates pose of a widget in the window by pre-multiplying its current pose.
Returns whether the event loop has been stopped. | https://docs.opencv.org/3.4/d6/d32/classcv_1_1viz_1_1Viz3d.html | CC-MAIN-2022-33 | refinedweb | 341 | 62.24 |
Core (3) - Linux Man Pages
Core: The Core widget class
NAMECore --- The Core widget class
SYNOPSIS
#include <Xm/Xm.h>
DESCRIPTION
Core is the Xt Intrinsic base class for windowed widgets. The Object and RectObj classes provide support for windowless widgets.
Classes
All widgets are built from Core.
The class pointer is widgetClass.accelerators
- Specifies a translation table that is bound with its actions in the context of a particular widget. The accelerator table can then be installed on some destination widget. Note that the default accelerators for any widget will always be installed, no matter whether this resource is specified or not.
- XmNancestorSensitive
- Specifies whether the immediate parent of the widget receives input events. Use the function XtSetSensitive to change the argument to preserve data integrity (see XmNsensitive). For shells, the default is copied from the parent's XmNancestorSensitive resource if there is a parent; otherwise, it is True. For other widgets, the default is the bitwise AND of the parent's XmNsensitive and XmNancestorSensitive resources.
- XmNbackground
- Specifies the background color for the widget.
- XmNbackgroundPixmap
- Specifies a pixmap for tiling the background. The first tile is placed at the upper left corner of the widget's window.
- XmNborderColor
- Specifies the color of the border in a pixel value.
- XmNborderPixmap
- Specifies a pixmap to be used for tiling the border. The first tile is placed at the upper left corner of the border.
- XmNborderWidth
- Specifies the width of the border that surrounds the widget's window on all four sides. The width is specified in pixels. A width of 0 (zero) means that no border shows. Note that you should use resources like XmNshadowThickness and XmNhighlightThickness instead of XmNborderWidth to specify border widths.
- XmNcolormap
- Specifies the colormap that is used for conversions to the type Pixel for this widget instance. When this resource is changed, previously generated pixel values are not affected, but newly generated values are in the new colormap. For shells without parents, the default is the default colormap of the widget's screen. Otherwise, the default is copied from the parent.
- XmNdepth
- Specifies the number of bits that can be used for each pixel in the widget's window. Applications should not change or set the value of this resource as it is set by the Xt Intrinsics when the widget is created. For shells without parents, the default is the default depth of the widget's screen. Otherwise, the default is copied from the parent.
- XmNdestroyCallback
- Specifies a list of callbacks that is called when the widget is destroyed.
- XmNheight
- Specifies the inside height (excluding the border) of the widget's window.
- XmNinitialResourcesPersistent
- Specifies whether or not resources are reference counted. If the value is True when the widget is created, the resources referenced by the widget are not reference counted, regardless of how the resource type converter is registered. An application that expects to destroy the widget and wants to have resources deallocated should specify a value of False. The default is True, implying an assumption that the widget will not be destroyed during the life of the application.
- XmNmappedWhenManaged
- If this resource is set to True, it maps the widget (makes it visible) as soon as it is both realized and managed. If this resource is set to False, the client is responsible for mapping and unmapping the widget. If the value is changed from True to False after the widget has been realized and managed, the widget is unmapped.
- XmNscreen
- Specifies the screen on which a widget instance resides. It is read only. When the Toolkit is initialized, the top-level widget obtains its default value from the default screen of the display. Otherwise, the default is copied from the parent.
- XmNsensitive
- Determines whether a widget receives input events. If a widget is sensitive, the Xt Intrinsics' Event Manager dispatches to the widget all keyboard, mouse button, motion, window enter/leave, and focus events. Insensitive widgets do not receive these events. Use the function XtSetSensitive to change the sensitivity argument. Using XtSetSensitive ensures that if a parent widget has XmNsensitive set to False, the ancestor-sensitive flag of all its children is appropriately set.
- XmNtranslations
- Points to a translations list. A translations list is a list of events and actions that are to be performed when the events occur. Note that the default translations for any widget will always be installed, no matter whether this resource is specified or not.
- XmNwidth
- Specifies the inside width (excluding the border) of the widget's window.
- XmNx
- Specifies the x-coordinate of the upper left outside corner of the widget's window. The value is relative to the upper left inside corner of the parent window.
- XmNy
- Specifies the y-coordinate of the upper left outside corner of the widget's window. The value is relative to the upper left inside corner of the parent window.
Translations
There are no translations for Core.
RELATED
Object(3) and RectObj(3). | https://www.systutorials.com/docs/linux/man/3-Core/ | CC-MAIN-2021-31 | refinedweb | 823 | 57.47 |
>>.
citibank.co (Score:5, Funny)
now with moar than $100 billion in frictionless laundered money. That's what we call
.colocation!
GoDaddy stories on Slashdot ."
What registrar would you recommend? (Score:4, Interesting)
Re: (Score:3, Interesting)
Re: (Score:3, Informative)
gandi.net
Re: (Score:3, Informative)
Re: (Score:2)
I've been registering with 1&1 for years now. I have a free hosting account (developer preview) from 5 years ago. In any case, they charge $10 a year for
.com - used to be $6 a year.
NearlyFreeSpeech (Score:2) is the best registrar and webhost anywhere. Rock bottom prices, clean website, and absolutely no bullshit. Just sayin' as a satisfied customer for three years.
Re: (Score:2)
Re: (Score:2)
I had about 30 domains with GoDaddy, and was very unhappy with their user interface and customer service. I wanted to be able to make mass changes to the domains, such as name servers. I tried a few different ones and settled on gkg.net [gkg.net]. It's not the prettiest, but it's inexpensive and reliable, and the website UI is simple (no crazy Ajax, Flash interface, browser requirements, etc). For my highly important business domains, I went with DynDNS [dyndns.com], which is slightly more expensive, but has a clean and beautiful
Re: (Score:2)
I've been very happy with gandi.net. [gandi.net]
Namecheap (Score:5, Informative)
I've been using Namecheap for years, and they've been pretty awesome. They have a nice set of DNS management tools, they notify me of all important things, and as their name implies, they're inexpensive.
Another thing I like about Namecheap is that you can delegate control over your names to other people. I run a suite of hobby gaming web sites, and I've made contingency plans in case I get hit by a proverbial bus. (Or a real one.) I've given one of the other site admins permissions over the names so that if need be, he can manage them or even move them to another registrar. Obviously, I trust him implicitly, but the point is that if something happens to me, the names aren't just up for grabs once the registration expires. They may exist, but I don't know of another registrar that allows you to delegate permissions like this.
I can't speak about their technical support; I've never had to use it.
Just to prove I'm not a shill for the company (I'm only affiliated with them as being a customer), if there's one thing that's stupid about them, it's their name. I mean, "Namecheap"? Makes them sound so, I dunno, Wal-Martish, especially given what has been a good record so far with me.
Re: (Score:2)
I agree - I host over 100 domains through Namecheap, and have never had any problem with them. I left GoDaddy because of their PlaySkool, Javascript intense interface, long before I had enough domains to be worried about the privacy and security implications.
I also like money. A lot. In that line, here's an affiliate link to Namecheap [namecheap.com] that might make me some
:)
Re: (Score:2, Informative)
That's what I did, and now my company provides and sells domains to all of our website design customers as a part of our packages.
Why go to a secondary reseller, when you can become one yourself and take out a middle man.
Re: (Score:2)
I'll look into this - thanks
:)
I don't do much web development these days, but this is still worth checking into.
Re: (Score:2)
I can speak for NameCheap's technical support. They are quick and helpful. I only have certificates with them, but it's an ever-growing number
:)
I have a reseller account with some other company for domains, which is tens of cents cheaper per domain (special offers not included). The only difference between going through NameCheap and reseller accounts is that the latter normally requires a little deposit. If they need no deposit, they're usually slightly more expensive. For just a few domains I'd go with N
Re: (Score:2)
I can second the Namecheap recommendation. I moved my registration and hosting/email of my dozen domains from Godaddy to Namecheap last year and have been very satisfied.
Re: (Score:2)
Re: (Score:3, Funny)
What do you mean by "weird domains"? Are you referring to something like "ifuckfishinmydreams.com" where the name itself is weird or "nationalreview.com" where all the writers are weird, or "lookbook.nu" where the idea is weird or...?
(Note: "ifuckfishinmydreams.com" is not a real website. But it you're interested in owning that domain, drop me an email. We can talk.)
It's not mined out. (Score:5, Informative)
It's squatted, sniped, tasted, and front-run out.
When a speculator can register thousands of names and move them around for free by playing the system, is there any wonder that
.com is "mined out"? When a registrar front-runs domain names (Network Solutions) and fills the space with reserved names for itself, is there any wonder that .com is "mined out"?
Get rid of domain tasting and other shenanigans and the problem will go away.
--
BMO
Re: (Score:3, Informative)
This.
Also 'investors'. A little while back I read an online article by someone congratulating themselves on investing in
.com names. He was going through a dictionary, finding obscure words and testing to see if they were available, then buying them up. He had about 30 dictionary words and he was going to make money on the idea, also encouraging others to do the same.
It's one of those times when you wish you could reach through the screen and strangle the person on the other side. Squatters, 'investors' and: (Score:2)
I know that WWW ist just one of many services. And a definition of "use" (or better of what kind of behaviour leads to losing the domain) that eliminates most of the speculants and cybersquatters but doesn't hurt other people shouldn't be too difficult to find.
And if it's only done on request by someone with serious interest in using the domain, there would be no need to "visit millions of websites".
Re: (Score:2)
I doubt it. Accepting email (and then ignoring it) costs the "speculants and cybersquatters" nothing - they just point them all at the same mail server just as they do with the web servers.
Plus, why is putting up a page of advertisements not "using"?
Re: (Score:2)
I doubt it. Accepting email (and then ignoring it) costs the "speculants and cybersquatters" nothing - they just point them all at the same mail server just as they do with the web servers.
Oh my. Just imagine this: guy wants to register $HISNAME-software.com that is taken by a domain grabber. Guy goes to some kind of ombudsman who gives the thing a closer look and easily sees that the running mailserver is just an alibi. Domain will be transferred, grabber maybe fined.
Sure, you could never really get all of them, if we make sure not to have "false positives", but why shouldn't we at least get rid of the big ones, where it is easy to proove?
Plus, why is putting up a page of advertisements not "using"?
Because of the missing content?!
Re: (Score:2)
Flamebait? Seriously? What a stupid mod.
Re: (Score:2)
The easy solution would be a "use it or lose it" rule where the ownership of a domain that is just parked will be revoked when someone else would like to register it.
It is non-trivial to define "parked" in regards to a domain name in a way that is fair. I have 2
.com domains registered. One I've used since the price of a .com name was writing a justification memo to the InterNIC. I registered the other one in the late 90's when I thought I might want to migrate off the old one (complicated story) but I've never done so. My old registrar consideredd both of those domains "parked" simply because I didn't use their DNS servers for either of them, but in fact the old domai
Re: (Score:2)
Oh, "registering a domain in order to treat it as a good to be sold", maybe with an added "especially when not making any real use in terms of running stuff like websites, mail, ssh, VPN,
..." seems like a good starter to me.
And in your case, I would suspect that - assuming your business is not selling domains - your (businesses') name or what you do and the domain name give clear evidence that you had no malicious intent.
Re: (Score:2)
So what? That scheme would be obvious enough. They would have to come up with more complexity in the generated pages, register the domains to many different real people and so on. Maybe we'll have to add fines for "professional" parkers in the recipe.
OK, I admit that it's no sooo easy. But it would be a huge advancement to the situation now without being technically unrealistic.
And there is one thing I forgot: any abuse of domain tasting must be severely punished.
Re: (Score:2)
I wouldn't be against the prices being raised back to former levels across all top level names. For those who have a legitimate use for the name, the cost is still not that high, but high enough to force squatters to rethink their approach. registe.
People may not be paying (Score:5, Interesting)
The squatters may just think people will pay. Remember that for something like this to happen there doesn't have to be an actual worthwhile market, just the perception of one. You get all kinds of dumb, greedy, people who get in to shit.
A great example is back in the day when eBay was young and some domain squatters decided to buy up domains they thought might be worthwhile and try to sell them. So the funniest one I came across was a guy who had registered generalmills.cc and wanted to sell it for $10,000,000. That's right, ten million dollars. His sales pitch was you could buy it and then "Make them pay whatever you liked for the rights." Of course General Mills happily owned generalmills.com at the time and didn't seem to have an interest in others. What's more, a company can nab a domain name that is their trademark if they wish (these days through ICANN, back then through the courts). I e-mailed him calling him an idiot more or less and got one of the most caustic, hate filled responses defending his business claiming he made millions "regularly" on sales. I pointed out to him that he had no sales on eBay thus far, and got more hate in response.
It was quite clear that he though he'd got a brilliant scam, which was successful only in his own mind. He was just waiting for his big payday... Which of course never came..
Re: (Score:2)
Wow, lol. This wasn't a month ago, and it was squatted. Purchased, and thanks!
Re: (Score:2)
Yes, but most often that's in use, which is a different thing.
Re: (Score:2)
Re: (Score:2)
By burned down buildings..
Re: (Score:2)
Re: (Score:2)
Sheep? I take it you don't utilize any thermostats in the heating of your house? Shun automatic transmission?
For that matter, why not remember and write in IP in the browser bar?
Re: (Score:2)
Re: (Score:2)
For that matter, why not remember and write in IP in the browser bar?
Flashbacks to SUN terminal rooms in college; having a notebook half-filled with IP addresses, passed from person to person, because only the CS grad students got printer time...good times.
Re: (Score:2)
To get to slashdot.org (I don't use facebook), I hit Ctrl+T, then the letter s, then the right arrow key, then enter. Once you've been to a site once, you barely need to think at all these days.
Re: (Score:2)
Re: (Score:2)
1) Send neural impulses to direct your right arm such that said arm is above the keyboard. You may, if you wish, separate your eyelids so that you might see when you are successful in this.
2) Send more neural impulses to move your thumb right over the key the light reflecting off of which forms the letters Ctrl upside down on your retina. Similarly move your pinky finger right over the key that looks like a T. Note that although pressing the key normally places a lowercase t on the screen, the key is still
Re: (Score:2)
> browser does a swift “I'm feeling lucky” search
Umm... Maybe this changed, but the last time I checked, Firefox tries
.com and a few other toplevels until one resolves.
Re: (Score:3, Informative)
Actually, the reason Google knows that bit more about sites people visit, is that Firefox, Chrome and Safari all send each and every domain you visit to Google's Safebrowsing servers before they connect to it.
That is not how SafeBrowsing works. Firefox downloads a large database of hash prefixes. If the hashes of the domain and url are not in the list you go to the site and nothing is sent to Google. If the first bit of the hash matches an entry in the list Firefox asks Google for the list of complete hashes that start with that prefix. If the site's hash matches then you're blocked, if it doesn't you're not, but nothing more is sent.
To further obfuscate things, when Firefox finds a prefix match it doesn't just
Re: (Score:2, Redundant)
So the only reason that you are against it is so you do not need to pay more for another domain name. And yet by registering three daomain names (com, net, org) you and almost everybody else are using up those names.
I always thought these com, net, org and all others are not a good idea. The best would have been to just use the ones for each country. That would have made this site slashdot.us. "But what about international organizations like debian?" I hear you ask. Well, either take the one where the organ
Re: (Score:2)
Here is proof, in the form of a registry desperatly trying and failing to get people to buy
Re: (Score:2)
Re: (Score:3, Interesting)
It's the manner in which the girls are selling domains.
I don't mind girls in commercials. Even sexy girls in commercials, if it's appropriate for the product. For example, beer, which is traditionally a "macho" drink, or Axe bodywash, or Victoria's Secret (who, contrary to common sense, are targeting their ads mainly at men that buy those sexy clothes for their girlfriends/wives).
GoDaddy's commercials pretty much tell me that they're positioning their services as a "macho" service, and it simply doesn't m
Re:It's not mined out. (Score:5, Informative)
Get rid of domain tasting
It's pretty much gone: [wikipedia.org]
"ICANN reported in August 2009, that prior to implementing excess domain deletion charges, the peak month for domain tastings was over 15 million domain names. After the $0.20 fee was implemented, this dropped to around 2 million domain names per month. As a result of the further increase in charges for excess domain deletions, implemented starting April 2009, the number of domain tastings dropped to below 60 thousand per month."
I know from personal experience that a domain I had let lapse and was sat on for years became available again after the ICANN policy was put in place.
Re: (Score:2)
Yes, its frustrating. I am trying to come with the a
.com name and most of the a names are squatted (Registered but no website or godaddy.com website.)
Re: (Score:3, Informative)
Yes, its frustrating. I am trying to come with the a
.com name and most of the a names are squatted (Registered but no website or godaddy.com website.)
The web is not the internet. There are many more things to use a domain for than just a website.
Re: (Score:2)
You're a good couple years behind. "Tasting" is long-dead. [icann.org]
So now would you like to try again to regail us with your extensive insight into the domain name system, and the answers to all our problems?
.co for company ? (Score:4, Insightful)
are already in use as a company designator so why not ? but what about the collision with the Colombia state domain ?
Re:.co for company ? (Score:5, Funny)
...and
.co.ck
(Cook Islands, really, look it up!)
Re: (Score:2)
.co.uk
.co.jp .co.nz
are already in use as a company designator so why not ? but what about the collision with the Colombia state domain ?
You don't like
.co.co?
.co for phishing (Score:2)
It's pretty easy to pick out the "yourbank.leethaxors.com" and "batt13.net.com" spam. But with an appropriately formatted email, a link to "slashdot.co" might actually get some folks to click the link and log in to the phishing site.
-Rick
Re: (Score:3, Funny)
In return, let Canadians use the ccTLD for Western Sahara [wikipedia.org]..
Re:The right question (Score:4, Interesting)
The question we should ask ourselves is whether or not we should accept domain name registration as a commercial practice.
How about a resounding yes? The vast majority of sites on the internet are used for businesses. ".com" is short for "commercial," you know. If you want to talk about taking ".org" domains out of the commercial registration pool, there are practices that might be put in place to restrict their use in a way that ".edu" and ".gov" are used. I think you would be a little late to the party, though.
Re: (Score:2)
Just so we are clear on that, I'm not suggesting anything. I honestly do not know the right answer to this complex question myself.
But I want to put emphasis on the point that I'm talking about the registration process of a domain name, not the actual websites behind theses names. I'm referring to the fact that registrars are commercial websites themselves, employing commercial tactics I would expect from every other commercial websites or store.
Re: (Score:2)
Re: (Score:3, Interesting)
Real eastate is an extremely good model for how the DNS system should be run.
In places with significant unused land (for our purposes preserves and protected wilderness would be considered used) it is often possible to obtain ownership of such land by simply claiming it, and using it. (Law varies by nation, but this still occurs, and was far more common in the past).
In all other cases you buy land from an existing holder.
Regardless of one one obtains the land though, one must still pay any property tax, or
Godaddy mistake? (Score:2, Interesting)
Re: (Score:3, Interesting)
I use Godaddy almost exclusively for my many (too many) domains... that said, let's be honest.
It's not a mistake. Their checkout process is designed to wave as many unnecessary - yet seemingly useful - options as possible in front of novice domain customers, in hopes that one or two will fall into their basket by mistake. No doubt their logs are full of new customers landing and searching for an unavailable
.com domain, repeat, repeat, repeat, give up.
Now by defaulting to
.co and hiding .com they can sell
Re:Godaddy mistake? (Score:5, Interesting)
Yes, no mistake. They were pushing this even before it became available for sale: [godaddy.com]
'Pre-registration is now open for the newest truly global and recognizable domain name extension to come along in years:
.co -- It's used everywhere as an abbreviation for Company, Corporation, and Commerce. Let it vault your company into the global Internet marketplace!
Here's your chance to grab domain names that have been taken for years with the
.com extension. Pre-registration includes application periods for trademark holders and others.'
garbage domains (Score:2, Insightful)
Re: (Score:2)
.co is a country TLD. It's just misused, in largely the same was as
.me, .nu, and many others.
Re: (Score:2)
So is
.tv, Tuvalu.?
Of course the entire top level domain thing is largely broken from today's point of view, because it's so US-centric. Non-country domains should be global. Country domains should be somehow related to that country.
What I mean is, if you go to porn.<country tld>, you should get porn site from that country, or at least content with "performers" who are mostly from that country, and advertising meant for that country, even for foreign web clients, because presumably they're planning a vacation or somethi?
Since I live in the US, not only am I OK with it, I see it as a significant benefit!
Re: (Score:2)
Because many people who grab these domains don't understand what "their rules" are, or even that they are dealing with the rules of another country. They just think the TLD sounds cool. And the registrar (who doesn't want to lose a sale) doesn't do anything to explain it to them. Which leads to situations like this [arstechnica.com].
Re: (Score:2)
Which leads to situations like this [arstechnica.com].
Or this [theregister.co.uk]
Re: (Score:2)
country code tld's are supposed to represent sites in or at least related to that country. Misuse would be using them for sites that have nothing to do with that country.
Misusing cctlds particularly of unstable countries or ones ruled by a very different idiology to your own is a dangerous game. If the country decides they don't like your type or site or they don't like misuse in general there is little you can do about it. As someone has already pointed out registrars do nothing to explain this to their c
Let's call it scam when it is a scam (Score:3, Insightful)
Re: (Score:3, Interesting)
agreed. just another way for godaddy to profit from the clueless or too-lazy-to-read-what-they're-doing... which is a pretty large percentage of their customer base.
Regular business = scam (Score:2)
Re:Let's call it scam when it is a scam (Score:4, Interesting)
It's a scam to sell off
.co domains as .com domains, and it should be outed as such by slashdot.
I smell lawsuit. Unwary and dumb users expect to have their hands held in this day and age.
.COM domain - .CO domains are from COlumbia!" you are automatically setting yourself up for a class-action suit which you will assuredly lose or settle.
.com price. In which case, we are the sheeple and will be eaten soon by the GoDragon.
This is a really uninformed error by the world's largest registrar. If you don't have a big blue banner that says "This is NOT a
But maybe the GoDaddy lawyers already figured out the cost of the suit, the settlement and the legal fees, and the 90% markup still leaves more on the table than an ultra-competitive
Fuck the ccTLDs anyway... (Score:2)
I saw the stupid Twitter-140-character-limit-moronity-mandated URL-shortened [flic.kr] the other day, and I thought, the concept of ccTLDs are dead! Why not just use [flickr] if you're going to do that.
Yeah, the Internet is getting stupider and stupider every second...
Re: (Score:2)
Damn ACs, making all Americans look stupid and unworldly
;(
Vote with yr wallet. (Score:3, Insightful)
Re: (Score:2)
When a monopoly provides a service you desperately need, it's hard to stop them from milking you for all you're worth.
You have to maintain an internet presence these days, and failure to "keep with the times" may well jeopardize your ability to do business, hold down a job, and so on.
So you pay the piper.
Re: (Score:2, Insightful)
Re: (Score:2)
Considering how they and their competitors pull the same crap, I'd call it a de-facto cartel.
Public needs to learn not everyting is dot com (Score:2)
Re: (Score:2, Informative)
"Domaining" may be on the way out. (Score:3, Interesting)
With the October 27th change to Google web search, "domaining" may be on the way out.
Google made huge changes when they merged "Google Places" (which is really Google business search") results into their main web search results. Search for DVD player [google.com]. There are almost no "organic search results" shown. At the top, there's "Related searches for dvd player - Brands, Stores, Types". There are two "organic" results from Amazon and Best Buy, both Google advertisers. Then a big block of "shopping results" A right side column of ads.
And that's a non-local search. On searches which imply some location ("london hotels" is a good test case), Google displays a map. For a few days, they displayed a big map in the main search area; today it's on the right, above the ads. Between the big ad block at the top, the map at the right, the ads below the the map, and the links in the main search area to the map, only a few organic results are squeezed in.
Google's organic search isn't any better than it used to be at filtering out the bottom-feeders. Down below the fold on "dvd player" search, there's still a result from "bestsoftware4download" (which tries a drive-by install of some
.exe). In the "london hotels" search, there are a few junk entries. Most of the stuff visible on the first screen isn't organic search results, though. This makes "domaining" futile.
Google is still fooling around with their layout after their big change, and it hasn't settled yet. (Also, Google's layout changes if you're logged into Google and allow "personalization". The results mentioned above are not "personalized".) The trend, though, is clear. The primary results for a search with commercial intent now come from Google advertisers. Google is pushing advertisers to buy ads directly from Google, not from the "bottom feeders".
So buying up large numbers of ".co" domains may be futile. I expect we'll see many junk domains in ".com" expiring, with nobody picking them up.
Not dissimilar to CentralNic's "country" .com/.co (Score:2)
15 years ago, CentralNic pulled a similar stunt with the
.com domains - they went around and registered domains like uk.com, us.com, cn.com and ru.com and then brazenly sold subdomains off of those as if they were "top-level domains", completely with hefty charges (32.50 GBP per year for something.uk.com for example).
It ties in with this story too, because CentralNic have indeed registered uk.co and us.co as well, so I wonder when they'll try to "persuade" the publc that something.uk.co is a legit top-leve
Re: (Score:2)
Go to flat namespace (Score:2)
Why do we even have root domains? Why not simply partition load by say the last few letters of the domain name. Reserve trademarks, proper names, and other forms of identity to their rightful owners - this way say a city can register a "root" domain and sell subdomains. Or a country. Or a DNS hotel like GoDaddy. Small organizations can register with whoever they wish as a subdomain, or run their own top level if they wish. Charge a flat fee per domain to recover load costs.
And get rid of the annoying
Re: (Score:2)
Um, you don't know much about Colombia then. They have made significant advances in fighting the drug cartels. Maybe you are thinking about Mexico?
Re: (Score:2)
Why yes, yes I am. | http://tech.slashdot.org/story/10/11/13/2324256/The-Ascendancy-of-co | CC-MAIN-2016-07 | refinedweb | 4,721 | 73.88 |
cc [ flag ... ] file ... -lm [ library ... ]
#include <math.h>
The j0(), j1() and jn() functions compute Bessel functions of x of the first kind of orders 0, 1 and n respectively..
For exceptional cases, matherr(3M) tabulates the values to be returned as dictated
by Standards other than XPG4.
The j0(), j1() and jn() functions may fail if:
An application wishing to check for error situations should set errno to 0 before calling j0(), j1() or jn(). If errno is non-zero on return, or the return value is NaN, an error has occurred.
See attributes(5) for descriptions of the following
attributes:
isnan(3M), matherr(3M), y0(3M), attributes(5), standards(5) | http://www.shrubbery.net/solaris9ab/SUNWaman/hman3m/j0.3m.html | CC-MAIN-2017-30 | refinedweb | 112 | 59.03 |
Topic: Looping in Programming
Not finding your answer? Try searching the web for Looping in Programming
Answers to Common Questions
How to Make an Infinite Loop Program in Basic
The Basic programming language is just that--basic. It uses commands and terms that make basic sense to just about anyone that would read them. It stands to reason, then, that even though it is considered by some an outdated language, it is... Read More »
Source:....
What is the use of loop in a program?
In computing, a loop is a programming statement or set of instructions, that allows the code to run repeatedly until some specific condition is met. For e.g. in C language the following looping statements are available. for loop, while loop... Read More »
Source:
What is looping in programming?
When you repeat an action in programming you use a loop. For example, one way to calculate 5 factorial would be: i=5 answer=1 repeat until i = 1: ____answer= answer*i ____i= i-1 return answer The two rows "answer= answer*i" and "i= i-1" are... Read More »
Source:
More Common Questions
Answers to Other Common Questions
loops execute a set of insructions repeatedly for a certain numbers of times.. Read More »
Source:...
A nested loop is when you have a loop in a loop. So this code: for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { cout << "i: " << i << "j: " << j << endl; } } will output 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 Read More »
Source:...
The "while" loop is a function built-in C language which allows you to loop certain piece of code until the criteria is met instead of retyping the code all over again. For example, this is C# thought (similar concept, different syntax): st... Read More »
Source:
Answer you use loops to draw out information from an array or a vector. Also they can be used to count up or down from any giving number. #include <iostream> using namespace std; int main() { short a = 1; short b = 1; short c = 2; //do while (a && b Read More »
Source:...
n A programming technique whereby a group of instructions is repeated with modification of some of the instructions in the group and/or with modification of the data being operated on. Read More »
Source:
Note: This article assumes you have installed Microsoft Visual C# 2008 Express Edition. You may download it for free from here: Open Microsoft Visual C#. Click on "Project..." to the right of Creat... Read More »
Source:.... | http://www.ask.com/questions-about/Looping-in-Programming | crawl-003 | refinedweb | 433 | 72.87 |
Here is my code :
- (NSData *)dataOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError { NSLog(@"Document dataOfType"); return ([NSKeyedArchiver archivedDataWithRootObject:ovalArray]); } - (BOOL) readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError { NSLog(@"Document readFromData"); ovalArray = [NSKeyedUnarchiver unarchiveObjectWithData:data] ; [ovalView setNeedsDisplay:YES] ; return YES ; } + (BOOL)autosavesInPlace { return YES; }
The file’s owner has a correspondance outlet with the ovalView.
When I try to save and restore, I have no print of NSLog and obviously, no oval in the window …
The size of the created file is always of 1062 bytes.
I definitely prefer an IDE like netbean for java !
Why ? becasue I can see the generated code and understand what is wrong in my code.
With xcode, I can’t compare with the solution, if I miss a binding or something else. It’s necessary to spend hour to find, if we can, the error.
Grrrr !
But I will appreciate any idea, for my problem. I’m sure, it’s something stupid, but I already spent 2 hours on it and I’m tired.
As my code seems very similar to the one of the proposed solution, I suppose that my problem reside in the “magic” part of xcode, the part I can’t visit.
Maybe, you can give me the mice or keyboard manipulation related to the save/restore functionnality.
Maybe, there is something todo that the file’s owner correspondance outlet with the ovalView ?
Thank you for your help.
[EDIT] one day later, i’m always stuck on this problem. | https://forums.bignerdranch.com/t/challenge-cant-load-and-save/4934 | CC-MAIN-2018-43 | refinedweb | 250 | 53.61 |
Understanding Isolated Storage - Day 3 - Part 6
- Posted: Nov 11, 2010 at 6:07 PM
- 26,459 Views
- 10 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Each Windows Phone 7 application is allocated space on the phone's flash drive where it can store information in a solitary area that cannot be accessed by other applications. The application can save any type of file or data here. In this video, Bob demonstrates how to utilize this feature to create new files or open existing files (like text files), read them, and display their information on the Phone's
Where abouts is isolated storage found on the computer during wp7 emulation? This would be convenient to know for debugging.
Thanks,
Brendan
I am getting errors on the "IsolatedStorageFile" and "StreamWriter" items in the code. I have both verified the code is the same as the video and copied the Code from the MainPage.Xaml.cs source code and it still flags it as an error.
I'm also getting the same issues with IsolateStorageFile and StreamWriter :/
If you pause the video at 3:14, you can see that new code appears in lines 13 and 14. Adding the following code to lines 13 and 14 appears to solve the issue.
using System.IO.IsolatedStorage;
using System.IO;
this also brings up the (small) issue, that if someone were to get this exact example from the marketplace and click the "open" button before anything was saved, you would have the same issue as when restarting your phone emulator, i.e. the unhandled exception. make sure to use some kind of error-catching, or at least a simple if statement to check whether the file exists.
The thing is the data stored are not overwritten when a new data is stored. hence when the new data (e.g. 12345) has less characters than the previous data (e.g. 987654321), and when we recall the data, the part of the prvious data after the new data is recalled as well (e.g. 123454321).
So how do we completely clear out the previous data when the new data is stored?
Very cool indeed.
Great video series!!
My question relates to the saved file (simple.txt) and the open/recall function. When the user enters new information and saves it to the flash memory of the device, the old entry is not completely overwritten. The user has to termintate the program to completely clear the initial message from the flash memory. Is there a fix to this? If so, what is it? That would have been a great ending to this video...and helped me tremendously!
@Shawn: You need to delete the file before writing with something like
using
(IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
storage.Remove();
}
Hi, i have a question:
if I switch off my phone after saved my file, when i restart the phone the file is deleted, clear, or is the same that i have svaed before?
Thanks
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Series/Windows-Phone-7-Development-for-Absolute-Beginners/Understanding-Isolated-Storage?format=html5 | CC-MAIN-2014-35 | refinedweb | 523 | 71.95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.