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 |
|---|---|---|---|---|---|
Read and write from EventHubs using a hybrid .NET/Java Storm topology
An example of using a hybrid dotnet/Java-based Apache Storm topology to work with Azure Event Hubs.
NOTE: This example requires a Storm on HDInsight cluster version 3.5 or 3.6.
Prerequisites
Visual Studio 2015 or 2017
Azure SDK for Visual Studio - at least version 2.5. This gives you the Azure entries in Server Explorer and the ability to view things like table storage
Java. Java is used to package the topology when it is submitted to the HDInsight cluster.
- The JAVA_HOME environment variable must point to the directory that contains Java.
- The %JAVA_HOME%/bin directory must be in the path
HDInsight Tools for Visual Studio - has the steps to install and configure.
eventhubs-storm-spout jar file - this contains the Event Hub Spout and Bolt. Download the version at for use with this example.
Azure Event Hub - you need to create an Event Hub, with two policies defined - one that can send, and one that can listen. You will need the following information from the Event Hub configuration.
- Event Hub Name - the name of the Event Hub you created
- Event Hub Namespace - the namespace of the Azure ServiceBus that contains the Event Hub
- Listen policy - the name and key of the policy that can listen to events for the Event Hub
- Send policy - the name and key of the policy that can send events to the Event Hub
For information on creating an Event Hub and policies, see Get Started with Event Hubs.
Storm on HDInsight cluster - the Azure HDInsight cluster that you will submit the topologies to. This example requires Storm on HDInsight 3.5 or 3.6.
SCP.NET package version
The SCP.NET package version that you use for this project depends on the version of Storm installed on your HDInsight cluster. Use SCP 1.0.#.# with this example.
Build and deploy
The two topologies in this project work together - EventHubWriter writes events, while EventHubReader reads them. You can deploy them in any order, but when both are deployed, events should flow from the Writer, to the Reader, then to Table Storage.
The configuration for Event Hub and Table Storage is stored in the App.config for each project. Fill in the values needed to connect to Azure Event Hub and (for the reader,) Azure Table Storage. For the TableName entry, enter the name of the table you want events to be stored in.
In Server Explorer, right-click the solution (EventHubExample,) and select Build. This will restore any missing packages and build the project.
In Server Explorer, right-click the Azure entry and select Connect to Microsoft Azure Subscription to make sure you are connected.
In Server Explorer, right-click the project name (EventHubWriter or EventHubReader,) and select Submit to Storm on HDInsight.
- Use the drop-down to select the Storm on HDInsight server
- Expand Additional Configurations, select Java File Paths, and browse or enter the path to the directory that contains the storm-eventhubs-1.0.2-jar-with-dependencies.jar file.
- Select Submit to submit the topology to the server
Once the topology has been submitted, the Storm Topologies Viewer should appear, with a list of running topologies. If not, you can open it from Server Explorer by expanding Azure, HDInsight, right-click the cluster name and select View Storm Topologies.
View output
In Storm Topologies Viewer, select the EventHubWriter topology.
In the graph view, double-click the LogBolt component. This will open the Component Summary page for the bolt.
In the Executors section, select one of the links in the Port column. This will display information logged by the component. The logged information is similar to the following:
2016-10-20 13:26:44.186 m.s.s.b.ScpNetBolt [INFO] Processing tuple: source: com.microsoft.eventhubs.spout.EventHubSpout:7, stream: default, id: {5769732396213255808=520853934697489134}, [{"deviceId":3,"deviceValue":1379915540}] 2016-10-20 13:26:44.234 m.s.s.b.ScpNetBolt [INFO] Processing tuple: source: com.microsoft.eventhubs.spout.EventHubSpout:7, stream: default, id: {7154038361491319965=4543766486572976404}, [{"deviceId":3,"deviceValue":459399321}] 2016-10-20 13:26:44.335 m.s.s.b.ScpNetBolt [INFO] Processing tuple: source: com.microsoft.eventhubs.spout.EventHubSpout:6, stream: default, id: {513308780877039680=-7571211415704099042}, [{"deviceId":5,"deviceValue":845561159}] 2016-10-20 13:26:44.445 m.s.s.b.ScpNetBolt [INFO] Processing tuple: source: com.microsoft.eventhubs.spout.EventHubSpout:7, stream: default, id: {-2409895457033895206=5479027861202203517}, [{"deviceId":8,"deviceValue":2105860655}]
Kill the topologies
In the Storm Topologies Viewer, select each topology and then select the Kill button at the top of the Topology Viewer.
Project code of conduct
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. | https://azure.microsoft.com/nb-no/resources/samples/hdinsight-dotnet-java-storm-eventhub/ | CC-MAIN-2018-05 | refinedweb | 804 | 57.57 |
Last year I upgraded my Personal Organiser to a Psion Series 5 and was contemplating spending the money (175UKP) to get the EPOC C++ SDK - EPOC is the operating system that runs the Series 5. To a professional C++ (and hobbyist Java) developer this looked more enticing than learning the alternative OPL "user friendly" programming language.
I'm not really interested in writing applications for the Psion, but there are occasions when I write utilities that it would be nice to have available both on my desktop system and on the Psion. Obviously some EPOC specific code would be required, but since I keep platform specific code (such as user interfaces and input/output) in separate modules from the core application I expected this to be feasible.
The Psion is a small system so it would be unreasonable to expect all the facilities of a desktop system. But since I had already established that the C standard library was available I had hopes of "porting" some of my less demanding programs.
Around the time I was considering buying the SDK Psion had separated their software development under the name of Symbian. On visiting the Symbian website [symbian] I found they advertised an evaluation version of their C++ SDK. I requested a copy but in August 1998 a dispute with STNC led to the SDK becoming unavailable.
Time passed, the dispute with STNC continued and I found other interests. So it was a surprise when sometime around the end of January or early February I finally received this SDK. It then had to sit on a shelf until I had time to look at it.
The evaluation SDK requires Windows95 or NT and Visual C++ 4 or 5 (the learning edition will do) which may be a disappointment to those developers that resist all things Microsoft. There is a patch on the Symbian web site that "cures some of the problems experienced using Visual C++ 6".
The full SDK is built around two tool chains. One of these is based on Visual C++ and targets a version of EPOC implemented on top of Windows and allows debugging using Visual Studio. The second tool chain is based on Cygnus's build tools distribution (gcc etc.) and targets EPOC systems. Key elements of the latter are omitted from the evaluation SDK.
In addition there are instructions for building a range of example programs, coding guidelines, and an API reference. The API covers all the EPOC operating system facilities - such as accessing files, communications ports, and the GUI library.
The SDK installed easily - although it annoyed me by creating a number of top level directories on the partition of my choice rather than letting me specify a base directory under which to install everything.
After installation I followed the instructions for building some of the example programs to run using the "Emulator". This is a library that implements the EPOC APIs under Windows and provides a user interface via a window that looks like the Psion. The example programs built and ran happily and I could debug into them using Developer Studio. Looking at the code my first impression was confusion - class instances were initialised using two phase construction, many of the member functions had weird looking names ending in a capital "L" and class names began either with "T" or "C" prefix with no apparent pattern.
This led to a nagging suspicion that all was not as I had hoped - two phase construction is a technique developed in the early days of C++ to deal with the inability of the language to deal with error conditions occurring in constructors. When exception handling was adopted in the early '90s it fell into disuse.
I dived into the documentation seeking an explanation. Here I discovered that the "coding guidelines" require two phase construction, that "L" identifies a function that could "leave" and that "T" and "C" are used to distinguish classes that have no destructor from those that need to free memory at the end of their lifetime. I also discovered "R" a prefix for classes that need to free other system resources.
I deduced that "leaving" isn't like throwing an exception since any function that calls an "L" function has to manually register instances of any "C" or "R" classes with a "cleanup stack". This delivers similar results to exception handling with the following differences: the programmer can get the registration logic wrong (the compiler shouldn't), and there is a runtime cost to all these extra function calls (this can be avoided with compiler support). There is definitely more code to maintain, but I don't have figures to support my suspicion that there is also a space cost.
Hopefully, no-one would introduce the unwieldy mechanisms I'd encountered in preference to using genuine exception handling! But at the time I could find no direct indication that the version of C++ was anything other than compatible with Visual C++ which does have exception handling support. (I later discovered documentation that states that exceptions - and other language features - are not supported, but it is hidden in various parts of the API function reference, not in the introductory material or white papers.)
Having decided that the supported language probably lacked exceptions I wondered what else was non-standard and decided to email Symbian in the hope of clarifying matters:
- Alan Griffiths:
-
Could you confirm a suspicion that has been growing as I read through the SDK documentation - that the language supported by the SDK is very different from that defined by the current ISO C++ Language Standard.
In particular I was puzzled by the lack of an explanation of when one would use the cleanup stack mechanism in preference to allowing exceptions to unwind the stack. Is this because the C++ exception handling mechanism is not supported? (On a related point the examples seem to suggest that the "new" operator returns 0 in place of throwing a std::bad_alloc exception.)
I appreciate that compiler support for a number of language features is distinctly patchy and that the development of EPOC32 spans a period of rapid evolution in C++. However, I am repeatedly puzzled by the approaches taken. While I can surmise that these are compromises enforced by the available compiler technology I can't be sure since these issues do not appear to be addressed anywhere.
- >Martin Tasker(Symbian):
-
There were essentially two reasons for not adopting the C++ standard library when we started developing EPOC:
-
at the time (mid 95) the standard had not been agreed - though the language standard was substantially in place - clearly that has changed since
-
the standard library, in particular its use of templates and its exception-handling culture, was considered too profligate in terms of space and time for adoption in a small system - that has not changed since Embedded C++ is evidence that we were not the only people that shared this feeling. They didn't even support templates at all! - we do, but we use them exclusively in "thin template" idioms.
- AG:
-
I can understand your reasons for not adopting the standard library, my main concern however is the _language_
I think your choice is wiser than that of the EC++ group [EC]. (Templates in themselves are not harmful and can greatly enhance the type safety and reliability of some code.)
- >MT:
-
By default, we will pick up and deliver some support for standard C++ as time goes by. Later this year, we will take newer drops of Cygnus' GCC toolchain which will include more standard C++ support (our current supported technology dates from 1996). It might then be possible to implement a C++ standard library on EPOC, but we have as yet no plans to do that ourselves.
The accessibility of this information could be improved, and our plans for technical papers in the first half of this year should help.
Incidentally in EPOC C++, operator new() returns 0 on failure, unless you use the override which appears as new(ELeave) - which "leaves" with KErrNoMemory on failure. There was a debate in mid-96 about whether to make ELeave the default behaviour. Largely on the grounds that this would confuse imported C++ programs too much, we decided against.
- AG:
-
Equally, having new return 0 causes portability problems - it would be best if it threw std::bad_alloc. However, there are still many platforms that implement the pre '95 semantics you describe.
I must confess to being disappointed that the supported language was closer to EC++ than C++ but my main difficulty throughout was the lack of documentation of what is and isn't supported.
I have to thank John Forrest <j.forrest@dial.pipex.com> for posting the following summary on usenet nntp://comp.sys.psion.programmer (I've corrected a few typos).
-
Don't use any file scope or local static variables.
-
Don't use any multiply derived types, apart from the limited M classes.
-
Can't use exceptions - use the EPOC Leave mechanism.
-
Don't use any C++ library stuff, just the EPOC stuff. (This is easier since you'd have to go out of your way to link them in).
-
Can't use dynamic casts (or other RTTI)
-
Beware that this version of gcc uses an older syntax for specific templates.
-
Be careful about the IMPORT_C and EXPORT_C usage for dll external declarations - you only get complaints when compiling for gcc.
-
Be careful about DLL UIDs - ditto.
-
Ensure all build information is given via the .mmp file - resist the temptation to add files directly into the VC++ Workspace/Project.
You can use <stdio.h>, but I'd advise against - that and other C library stuff are there for backward compatibility - unless you are trying to port a pure C program. If you mix and match then you have to close down the library in a special way.
Otherwise as a rule stick to the style used in the examples and the manual. This is pretty different from normal, and some people moan like hell, but since all the apps are written in this style you are much less likely to hit bugs. Try to avoid backsliding - some people in the past have hit problems because they (as far as I can make out) have tried to do C style string manipulation directly on the contents of descriptors (used for strings and other things).
I guess I'm one of those that "moan like hell" because I don't want to make a commitment to developing solely for EPOC. I'd rather my programs were available on whatever computer I have to hand (which is why Java interests me). If I were intent on developing applications specifically for EPOC platforms then the non-standard nature of the C++ used would be less important to me.
At the root of my concerns is a problem I first wrote [Griffiths] about in 1995 as a result of reading the first public draft of the ISO C++ standard. I complained about the many ways in which changes to the language invalidated the experience, skills and code base of those working with it. A particular issue is that the presence of exception handling necessitates a different style of coding. (Of course, the decision to include exceptions took place long before this - they are described in the 1990 ARM [Ellis] as "experimental" language features.)
Having spent the intervening four years becoming accustomed to these features I find that I am addicted. My current code base would not compile or work without exceptions, namespaces, or STL (I could live without RTTI). I also find that the resulting programs require less code and are more robust. (If they use <iostream> they take a substantial, but fixed, hit in executable size, but otherwise they tend to be smaller or have more functionality.)
Regarding the programs that it would be nice to have available on my Psion I'd be willing to do some rework to have them. However, as it stands I would also need to redevelop the core application in the supported dialect of C++ and for me this is not worthwhile.
I've had several discussions with Martin about the issues raised by the above (which he has read in draft form) you may be interested in the following response: - Alan
Your comments are understandable from your perspective but consider the following:
-
the C++ facilities weren't there in GCC when we designed our leave support
-
our system is entirely effective re its original design goals and - re those goals alone - is more economical than native C++ exception facilities
-
compared to other palmtop systems, we're better: Windows CE, for instance, kills apps and loses data in order to save memory: we never do that, precisely because our exception handling stuff is built in so deep
Compatibility with "standard" C++ (the quotes were justified in 1995) was not a design goal of the original system: we could see the design goals of the C++ library and exception handling mechanism diverging grossly from ours, and the GCC toolchain didn't support exceptions as late as 1996. Our version of the toolchain will add support for native exceptions - possibly before the year is out. That will enable others to port the standard library, and code using it, onto EPOC.
I actually look forward to more dyed-in-the-wool C++ programmers such as ACCU members using EPOC for both academic/research purposes and commercial development. Much of commercial work we've fostered or known about hitherto has been by people from a SIBO/C/UNIX/Java/Win32-type background - including our own in-house developers - for whom EPOC poses an entirely different set of learning and porting issues.
[symbian]
[EC] Embedded C++ is an ARM like dialect of C++ being promoted by a Japanese consortium - details may be found at | http://accu.org/index.php/journals/540 | CC-MAIN-2016-26 | refinedweb | 2,309 | 56.39 |
Created on 2019-10-19 18:40 by Ron Frederick, last changed 2019-12-07 11:40 by asvetlov. This issue is now closed.
In testing AsyncSSH against Python 3.8, I noticed a large number of the following errors, even though I was properly closing streams before the objects holding them were garbage-collected.
An open stream object is being garbage collected; call "stream.close()" explicitly.
After some investigation, the problem appears to be that closing a stream is not good enough to prevent the error. The check in asyncio doesn't properly handle the case where the stream is closing, but has not fully closed. Here's a simple test program that demonstrates this:
import asyncio
async def tcp_client():
reader, writer = await asyncio.open_connection('127.0.0.1', 22)
writer.close()
asyncio.run(tcp_client())
It's possible to avoid this message by awaiting on writer.wait_closed(), but wait_closed() doesn't exist until Python 3.7, making it very difficult to write portable code and still avoid this message.
I think the following change might address this problem:
***************
*** 233,239 ****
def _on_reader_gc(self, wr):
transport = self._transport
! if transport is not None:
# connection_made was called
context = {
'message': ('An open stream object is being garbage '
--- 233,239 ----
def _on_reader_gc(self, wr):
transport = self._transport
! if transport is not None and not transport.is_closing():
# connection_made was called
context = {
'message': ('An open stream object is being garbage '
Sorry, I should have said that the change below was in the file asyncio/streams.py.
Yes, I've experienced this bug. We need to fix this in 3.8.1.
New changeset 7ddcd0caa4c2e6b43265df144f59c5aa508a94f2 by Andrew Svetlov in branch 'master':
bpo-38529: Fix asyncio stream warning (GH-17474)
New changeset 7fde4f446a3dcfed780a38fbfcd7c0b4d9d73b93 by Miss Islington (bot) in branch '3.8':
bpo-38529: Fix asyncio stream warning (GH-17474) | https://bugs.python.org/issue38529 | CC-MAIN-2021-21 | refinedweb | 302 | 66.64 |
010010.binBAN USER
First, a small nitpick: it's Singleton, not Singelton, but this is probably not the sort of advice you're looking for.
There is nothing in your class that forces usage of the getInstance() method to get a MySingleton instance. Usually, it is considered good practice to make the constructor private, to prevent other code from inadvertently calling the constructor and obtain another instance. If this was part of an interview question, then I'd say this is what the interviewer was looking for - after all, if you really know what the Singleton pattern is all about, you should know that the code should *forbid* creation of other instances. You do it by making the constructor private.
Classic application of recursion + backtracking.
My solution assumes that you are given a starting position in the maze, and that getting out of the maze is equivalent to reach a free position in the borders. With that in mind, all you have to do is branch on every direction (left, right, up, down), recursively finding the path until a border position is reached, or until you have tried every possibility and none worked (meaning it is impossible to get out of the maze from that starting position).
Just be careful to keep track of visited positions in a given path search, so that you don't recurse infinitely. Also, as positions are added to the path, we can keep track of the current path in a vector (C++ jargon for growable array), so that we can print it when we reach one of the border positions.
C++ implementation, tested and (apparently) working:
#include <cassert>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
bool find_path_aux(const vector<vector<char> > &maze, vector<vector<bool> > &visited,
vector<string> &path, int curr_x, int curr_y) {
if (curr_x < 0 || curr_x >= (int) maze.size() || curr_y < 0 || curr_y >= (int) maze[0].size())
return true;
if (visited[curr_x][curr_y] || maze[curr_x][curr_y] == 'X')
return false;
assert(maze[curr_x][curr_y] == '_');
visited[curr_x][curr_y] = true;
ostringstream oss;
oss << "( " << curr_x << ", " << curr_y << " )";
path.push_back(oss.str());
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if ((i == 0) != (j == 0))
if (find_path_aux(maze, visited, path, curr_x+i, curr_y+j))
return true;
path.pop_back();
visited[curr_x][curr_y] = false;
return false;
}
bool find_path(const vector<vector<char> > &maze, vector<string> &path, int pos_x, int pos_y) {
path.clear();
vector<vector<bool> > visited(maze.size(), vector<bool>(maze[0].size(), false));
return find_path_aux(maze, visited, path, pos_x, pos_y);
}
int main(void) {
cout << "Enter maze dimensions N and M for an NxM maze, followed by each entry separated by a blank," << endl;
cout << "followed by the initial position" << endl;
cout << "> ";
unsigned rows, cols;
while (cin >> rows >> cols) {
vector<vector<char> > maze(rows, vector<char>(cols));
for (unsigned i = 0; i < rows; i++)
for (unsigned j = 0; j < cols; j++)
cin >> maze[i][j];
unsigned pos_x, pos_y;
cin >> pos_x >> pos_y;
vector<string> path;
if (find_path(maze, path, pos_x, pos_y)) {
if (path.size() > 0)
cout << path[0];
for (vector<string>::size_type i = 1; i < path.size(); i++)
cout << " -> " << path[i];
cout << endl;
} else {
cout << "Impossible" << endl;
}
cout << "> ";
}
return 0;
}
Typical topological sort application. Build a directed graph where a node stores the name of a package. There is an edge from node U to node V if package U depends on V. Run topological sort to find the order of packages installation that does not violate dependency constraints.
A small tweak is necessary to detect cyclic dependencies, but it's easy to do. A graph has a cycle if there are back-edges in the DFS tree; simply keep track of the nodes in the DFS stack and check each traversed edge to make sure that node is not in the current stack already (if it is, a loop was found and we can abort everything).
Full C++ working implementation. Note that it's a lot more code than expected in an interview, probably the scope of the interview was mostly about getting the core graph algorithm right (and not so much about reading and parsing input):
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <cassert>
#include <cctype>
using namespace std;
struct graph_node {
string package;
vector<graph_node*> neighbors;
bool visited;
bool in_stack;
graph_node(const string &pkg_name) : package(pkg_name) { }
};
static graph_node *get_graph_node(map<string, graph_node *> &graph, const string &str) {
if (graph.find(str) == graph.end())
graph[str] = new graph_node(str);
return graph[str];
}
static bool dfs_visit(graph_node *node, vector<graph_node *> &top_sort_out) {
if (node->in_stack)
return false;
if (node->visited)
return true;
node->visited = true;
node->in_stack = true;
for (vector<graph_node *>::iterator neighbor_it = node->neighbors.begin();
neighbor_it != node->neighbors.end();
neighbor_it++)
if (!dfs_visit(*neighbor_it, top_sort_out))
return false;
top_sort_out.push_back(node);
node->in_stack = false;
return true;
}
static string topological_sort(map<string, graph_node *> &graph) {
for (map<string, graph_node*>::iterator node_it = graph.begin();
node_it != graph.end();
node_it++) {
node_it->second->visited = false;
node_it->second->in_stack = false;
}
vector<graph_node *> deps_order;
for (map<string, graph_node*>::iterator node_it = graph.begin();
node_it != graph.end();
node_it++) {
if (!node_it->second->visited && !dfs_visit(node_it->second, deps_order))
return "Dependencies contain cycles";
}
ostringstream res;
if (deps_order.size() > 0)
res << deps_order[0]->package;
for (vector<graph_node *>::size_type i = 1; i < deps_order.size(); i++)
res << ", " << deps_order[i]->package;
return res.str();
}
void parse_dependency(const string &entry, string &pkg_name, vector<string> &deps) {
string::size_type pkg_name_end = entry.find(':');
assert(pkg_name_end < entry.size());
pkg_name = entry.substr(0, pkg_name_end);
string::size_type begin = pkg_name_end+1;
while (begin < entry.size()) {
while (begin < entry.size() && isspace(entry[begin]))
begin++;
string::size_type end = begin;
while (end < entry.size() && entry[end] != ',' && !isspace(entry[end]))
end++;
if (begin < entry.size())
deps.push_back(entry.substr(begin, end-begin));
begin = end+1;
}
}
void print_dependencies(const vector<string> &packages) {
map<string, graph_node *> graph;
/* Build the graph */
for (vector<string>::const_iterator pkg_it = packages.begin();
pkg_it != packages.end();
pkg_it++) {
string pkg_name;
vector<string> deps;
parse_dependency(*pkg_it, pkg_name, deps);
graph_node *node = get_graph_node(graph, pkg_name);
for (vector<string>::const_iterator dep_it = deps.begin();
dep_it != deps.end();
dep_it++)
node->neighbors.push_back(get_graph_node(graph, *dep_it));
}
/* Perform topological sort, or stop if there is a cycle */
string res = topological_sort(graph);
cout << res << endl;
}
int main(void) {
cout << "Enter the number of entries, followed by each entry." << endl;
cout << "An entry is of the form: package_name: dependency1, dependency2, ..." << endl;
cout << "Example: emacs: gcc, build-essential, g++" << endl;
cout << "> ";
unsigned entries_count;
while (cin >> entries_count) {
vector<string> entries(entries_count);
getline(cin, entries[0]); // Ignore last newline
for (unsigned i = 0; i < entries_count; i++)
getline(cin, entries[i]);
print_dependencies(entries);
cout << "> ";
}
return 0;
}
Iterate through both lists and insert each node of each list in a hash table or a balanced binary search tree indexed by (name, phone) key-value pairs (in C++ you can use a set<pair<string, string>>, assuming name and phone are strings). When inserting, if an element is already there, then just ignore the current node and do not insert it.
Then iterate through the set / hash table, building a new list along the way. Each node retrieved from the set is a new node in the linked list.
Time complexity: linear in the size of the lists
Space complexity: linear in the size of the lists
Other possible approaches include sorting both lists to avoid using additional space, but it comes at the cost of raising running time to O(n log(n)); OR you can use nested loops to check if each node exists in the other list or on the rest of the current list, but that would be n^2.
Interesting question. It can be solved in linear time, or, to be more precise, O(N+M) where N and M is the length of each string.
Assume the larger string has size N, and the shorted has size M. A naive approach is to iterate through each index i in the large string, compute the character frequency table of large_str[i..i+M-1], and compare it to the short string's character frequency table - if they are the same, then we report i as an index.
However, computing the character frequency table of each substring from scratch and comparing it against the short string's table is O(M), so this would be O(NM).
We can improve on this and make it O(N+M). First, compute the character frequency table for the short string. Then, compute the character frequency table for large_str[0..M-1]. As you build it for the larger string, keep track of how many unique positions were filled, and how many of those matched with positions in the short string frequency table.
Then it works as if you had a sliding window on the larger string. When you move it right one place, remove the character on the left, and add the new character on the right, updating the number of matched positions so far, along with the number of total positions.
If you implement it correctly, then at any given time you know how many positions you have matched so far and how many unique positions are set in the character frequency table. So you can test if both tables match in O(1) - they are the same it the number of matched positions on the large table is equal to the number of positions filled in the small table, and if the number of total filled positions in the large stable is equal to the number of positions filled in the small table.
Implementation in C below; ran a few test cases and seems to be good. One interesting testcase is "mississippi" with "sis". It correctly finds all overlapping matches.
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
void match_permutations_aux(const char *big_str, const char *short_str, size_t short_len,
const size_t short_freq[UCHAR_MAX+1], size_t nfreq) {
static size_t big_freq[UCHAR_MAX+1];
memset(big_freq, 0, sizeof(big_freq));
size_t total_big = 0;
size_t matched = 0;
size_t i;
for (i = 0; i < short_len; i++) {
unsigned char idx = big_str[i];
if (big_freq[idx] == short_freq[idx] && big_freq[idx] != 0)
matched--;
if (big_freq[idx] == 0)
total_big++;
big_freq[idx]++;
if (big_freq[idx] == short_freq[idx])
matched++;
}
if (matched == nfreq && total_big == nfreq)
printf("0 ");
for (i = short_len; big_str[i] != '\0'; i++) {
unsigned char idx_remove = big_str[i-short_len];
unsigned char idx_add = big_str[i];
assert(big_freq[idx_remove] > 0);
/* Remove leftmost character */
if (big_freq[idx_remove] == short_freq[idx_remove])
matched--;
big_freq[idx_remove]--;
if (big_freq[idx_remove] == short_freq[idx_remove] && big_freq[idx_remove] != 0)
matched++;
if (big_freq[idx_remove] == 0)
total_big--;
/* Add rightmost character */
if (big_freq[idx_add] == 0)
total_big++;
if (big_freq[idx_add] == short_freq[idx_add] && big_freq[idx_add] != 0)
matched--;
big_freq[idx_add]++;
if (big_freq[idx_add] == short_freq[idx_add])
matched++;
if (matched == nfreq && total_big == nfreq)
printf("%zu ", i-short_len+1);
}
}
void match_permutations(const char *str_a, const char *str_b) {
if (str_a == NULL || str_b == NULL)
return;
const char *big_str = str_a;
const char *short_str = str_b;
size_t short_len;
if (strlen(str_b) > strlen(str_a)) {
big_str = str_b;
short_str = str_a;
}
short_len = strlen(short_str);
static size_t short_freq[UCHAR_MAX+1];
memset(short_freq, 0, sizeof(short_freq));
size_t total_short = 0;
size_t i;
for (i = 0; i < short_len; i++) {
if (short_freq[(unsigned char) short_str[i]] == 0)
total_short++;
short_freq[(unsigned char) short_str[i]]++;
}
match_permutations_aux(big_str, short_str, short_len, short_freq, total_short);
putchar('\n');
}
static char str_a_buff[1024];
static char str_b_buff[1024];
int main(void) {
printf("Enter string A and B.\n");
printf("> ");
while (scanf("%s%s", str_a_buff, str_b_buff) == 2) {
match_permutations(str_a_buff, str_b_buff);
printf("> ");
}
return 0;
}
This problem may seem intimidating at first, but if you look at the tree as a special case of a graph, it's not that hard.
Perform a BFS traversal of the tree, but print the children count of a node before printing the children themselves. So, serializing is just doing a BFS, attaching the number of children before actually printing the children.
Example for a tree of integers (applies similarly to a tree of strings). If you have this tree:
1 5 2 3 4 5 6 3 7 8 9 1 10 2 11 12 0 3 13 14 15 0 0 0 0 0 0 0 0 0
This is the serialized version of a tree with the following properties:
The root is 1. 1 has 5 children; they are 2, 3, 4, 5 and 6.
2 has 3 children; they are 7, 8, 9
3 has 1 child; it is 10
4 has 2 children: 11 and 12
5 has no children
6 has 3 children: 13, 14, 15
7 has no children
8 has no children
9 has no children
10 has no children
11 has no children
12 has no children
13 has no children
14 has no children
15 has no children
Deserializing is easy. You use another queue. Initialize the queue with the first node read. Then until the queue becomes empty, dequeue a node, read the children count from input, and then read that same amount of nodes and enqueue them as you read them.
Working C++ implementation:
#include <iostream>
#include <vector>
#include <queue>
#include <sstream>
using namespace std;
struct tree_node {
int val;
vector<tree_node *> children;
tree_node(int v) : val(v) { }
};
string serialize(tree_node *root) {
if (root == NULL)
return "";
queue<tree_node*> queue;
ostringstream oss;
queue.push(root);
oss << root->val;
while (!queue.empty()) {
tree_node *curr = queue.front();
queue.pop();
oss << " " << curr->children.size();
for (vector<tree_node*>::const_iterator it = curr->children.begin();
it != curr->children.end();
it++) {
oss << " " << (*it)->val;
queue.push(*it);
}
}
return oss.str();
}
tree_node *deserialize(const string &tree_str) {
if (tree_str == "")
return NULL;
queue<tree_node*> queue;
istringstream iss(tree_str);
int value;
iss >> value;
tree_node *root = new tree_node(value);
queue.push(root);
while (!queue.empty()) {
tree_node *curr = queue.front();
queue.pop();
int count;
iss >> count;
for (int i = 0; i < count; i++) {
iss >> value;
tree_node *new_node = new tree_node(value);
curr->children.push_back(new_node);
queue.push(new_node);
}
}
return root;
}
static void destroy_tree(tree_node *root) {
if (root == NULL)
return;
for (vector<tree_node*>::iterator it = root->children.begin();
it != root->children.end();
it++)
destroy_tree(*it);
delete root;
}
int main(void) {
cout << "Enter an N-ary tree as described in the comments to deserialize and serialize it again" << endl;
cout << "> ";
string input;
while (getline(cin, input)) {
cout << serialize(deserialize(input)) << endl;
cout << "> ";
}
return 0;
}
Bubble sort? Seriously?
You are right: merge sort is usually a good way to sort a linked list. I wouldn't work for this company.
If they explicitly say it's a large file, then you probably can't keep all the data in in-memory data structures like hash tables or binary search trees.
In any case, grouping together all the anagrams can be achieved by sorting each string while keeping a copy of the original, and then sort all the words based on their sorted version.
So, start by making a first pass over the file. The result of this step is to create a second file of key value pairs, where each pair K, V consists of a sorted word followed by the original word.
For example, if the file had the words "My dog is god", the first pass would create a file with these contents:
My My
dgo dog
is
dgo god
Then, sort the auxiliary file that was just created. Since we're dealing with very large datasets, you might have to use an external sort algorithm. Merge sort is a good candidate here -- probably the interviewer would test your knowledge of how merge sort works externally to sort a big amount of data.
After sorting the file, you have all anagrams close to each other:
dgo dog
dgo god
is is
My My
Or it might just be the opposite. He may be interested in testing if you know syscalls and how find works under the hood.
What exactly do you mean by "identify"? The rank of the bit? There's no general solution for an N-bit integer, but for reasonably small values you can make a lookup table to get O(1).
Naive recursion will be O(2^(max(N, M)). With dynamic programming you can make it O(N*M) which is a *HUGE* improvement.
Going from recursive approach to DP is not very hard if you think about the recursion tree.
C++ implementation with naive recursion and DP approach:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
unsigned scheduler_possibilities(unsigned m, unsigned n) {
if (m == 0 || n == 0) {
return 1;
}
return scheduler_possibilities(m-1, n)+scheduler_possibilities(m, n-1);
}
unsigned scheduler_possibilities_dp(unsigned m, unsigned n) {
unsigned dim = max(m+1, n+1);
vector<vector<unsigned> > dp(dim, vector<unsigned>(dim));
for (size_t i = 0; i < dim; i++) {
dp[i][0] = 1;
dp[0][i] = 1;
}
for (size_t i = 1; i < dim; i++) {
for (size_t j = 1; j < dim; j++) {
dp[i][j] = dp[i-1][j]+dp[i][j-1];
}
}
return dp[m][n];
}
int main(void) {
cout << "Enter M and N" << endl;
cout << "> ";
unsigned m, n;
while (cin >> m >> n) {
//cout << scheduler_possibilities(m, n) << endl;
cout << scheduler_possibilities_dp(m, n) << endl << "> ";
}
return 0;
}
Generating the powerset of a set of N elements cannot be any better than O(2^N), so there's not much you can do. Any algorithm will stop working with relatively small values for N.
It depends on the implementation. There are some guarantees, but the implementation is not forced to use a mutex.
The C standard I/O library (stdio) documentation states that each call to printf(), scanf(), getchar(), putchar(), and any other stdio functions behave as if a call to flockfile(3) was made before invoking the specified function and a call to funlockfile(3) was made after invocation.
So, stdio is thread safe, as long as the threads are well behaved and use the accepted, known interface to deal with file streams - the stdio library.
The same guarantees apply to C++, but note that things like
cout << "Hello" << " World";
is actually 2 calls, so this is not atomic.
Note, however, that stdio and any I/O library uses the read(2) and write(2) syscalls under the hood, which are not atomic. If a misbehaving process neglects to use stdio and starts reading and writing with read(2) and write(2), then things can start to break even if everyone else uses stdio to manipulate the file.
So, in short, as long as you use the library, you are mostly safe, but an important point to mention to the interviewer is that the exact implementation details of how stdio manages locking are very platform specific and don't necessarily rely on a mutex.
I believe the idea is to do it in the same matrix. Also this won't scale, the running time is too bad.
Sort the matrix first as if it were a regular array. That is, for an MxN matrix treat it as a sequential, linear array of M*N elements and sort it using a known sorting algorithm.
Then, swap the first row with the last, the second row with the second to last, the third row with the third to last, etc.
This is O(MN log(MN)) as it is bounded by the initial sorting. No additional memory is used so space complexity is O(1). I believe you can't achieve better than these bounds.
#include <stdio.h>
static void swap(int arr[], size_t i, size_t j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
static void swap_arrays(int arr1[], int arr2[], size_t sz) {
size_t i;
for (i = 0; i < sz; i++) {
int tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}
static void quicksort(int arr[], size_t sz) {
if (sz <= 1) {
return;
}
swap(arr, 0, sz/2);
size_t i, j;
i = 0;
for (j = i+1; j < sz; j++) {
if (arr[j] <= arr[0]) {
i++;
swap(arr, i, j);
}
}
swap(arr, 0, i);
quicksort(arr, i);
quicksort(arr+i+1, sz-(i+1));
}
void matrix_mostly_sorted(size_t rows, size_t cols, int matrix[rows][cols]) {
quicksort(&matrix[0][0], rows*cols);
size_t i;
for (i = 0; i < rows/2; i++) {
swap_arrays(&matrix[i][0], &matrix[rows-(i+1)][0], cols);
}
}
static void print_matrix(size_t rows, size_t cols, int matrix[rows][cols]) {
size_t i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
putchar('\n');
}
}
int main(void) {
printf("Enter matrix dimensions followed by the elements\n");
printf("> ");
size_t rows, cols;
while (scanf("%zu%zu", &rows, &cols) == 2) {
int matrix[rows][cols];
size_t i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
matrix_mostly_sorted(rows, cols, matrix);
print_matrix(rows, cols, matrix);
printf("> ");
}
return 0;
}
deb and beed are not anagrams, so they belong to separate sets. Two strings are an anagram if they have the same count of each character. beed has one more 'e' than deb so they are not anagrams.
Also you forgot few. So there you go - 5 sets of anagrams.
A naive approach to this problem would be to have an array of stacks and update the necessary
stacks on each folding operation. The problem is that each fold requires us to reverse half of
the stacks at each step, or, to put it another way, pop everything from half of the stacks
and push it again on the other half.
When processing the i-th fold, each stack has 2^i elements, and we would have to pop
2^i elements out of 2^N/2^(i+1) stacks and push them back into the other 2^N/2^(i+1) stacks.
So for each step we pop half of the total elements and push them again.
For an array of size M, this amounts to O(M log(M)), since there are log(M) steps, and each step
does O(M/2 + M/2) work (pop + push).
This code goes a little further and optimizes the stack merging step by doing it in O(1). To do
so, it has each stack element point to two elements - the node below and the node underneath.
These pointers are not always accurante: because we don't actually reverse the stacks when
merging, traversing a stack from top to bottom is not as easy as following pointers to the
element that comes next, since a merge operation effectively turns a stack upside down
(so the element below is now the element above, and vice versa). We just have to be careful
with this when traversing the stack by following the link that does NOT takes us to the previous
node we just came from.
Also, each stack base (the bottommost node, that never changes) in the array keeps a pointer to
the current top of the stack whose bottom is that node. This ensures that we can find the top
of a stack in O(1) given any node in the array, and merge them in O(1).
This optimization reduces the runtime down to O(M) at the cost of a little memory overhead to
store the pointers.
Note that a naive complexity analysis would argue that the runtime is still O(M log(M)), because
at each step we do at most M/2 merges and there are log(M) steps. This is wrong though: O(1)
merges amortize the total runtime to O(M/2) because the stack sizes double on each step.
So, step 1 does M/2 merges, step 2 does M/4, step 3 does M/8:
M/2 + M/4 + M/8 + M/16 + ...
Which is bounded by 2M and thus the algorithm is O(M).
Note, however, that M = 2^N, but we need to at least represent the paper elements to move them
around, so this is probably the best asymptotic complexity we can get.
struct array_node {
int value;
struct array_node *up;
struct array_node *down;
struct array_node *top;
};
static void merge_stacks(struct array_node *below, struct array_node *above) {
if (below->up == NULL) {
below->up = above;
} else {
assert(below->down == NULL);
below->down = above;
}
if (above->up == NULL) {
above->up = below;
} else {
assert(above->down == NULL);
above->down = below;
}
}
void fold(struct array_node arr[], const char cmds[], size_t cmds_sz) {
size_t beg = 0;
size_t arr_sz = 1 << cmds_sz;
size_t len = arr_sz;
size_t i;
for (i = 0; i < cmds_sz; i++) {
size_t j, k;
for (j = beg, k = beg+arr_sz-1; j < beg+arr_sz/2; j++, k--) {
if (cmds[i] == 'L') {
merge_stacks(arr[k].top, arr[j].top);
arr[k].top = &arr[j];
} else if (cmds[i] == 'R') {
merge_stacks(arr[j].top, arr[k].top);
arr[j].top = &arr[k];
} else {
assert(0);
}
}
arr_sz /= 2;
if (cmds[i] == 'L') {
beg += arr_sz;
}
}
assert(arr_sz == 1);
struct array_node *curr = arr[beg].top;
struct array_node *prev = NULL;
struct array_node *next;
for (i = 0; i < len; i++) {
printf("%d ", curr->value);
if (curr->up == NULL || curr->up == prev) {
next = curr->down;
} else {
next = curr->up;
}
prev = curr;
curr = next;
}
printf("\n");
}
int main(void) {
printf("Enter N followed by the sequence of commands.\n");
printf("> ");
size_t n;
while (scanf("%zu", &n) == 1) {
struct array_node values[1 << n];
size_t i;
for (i = 0; i < (1 << n); i++) {
values[i].value = i+1;
values[i].top = &values[i];
values[i].up = values[i].down = NULL;
}
char cmds[n];
for (i = 0; i < n; i++) {
scanf(" %c", &cmds[i]);
}
fold(values, cmds, n);
printf("> ");
}
return 0;
}
Some tests:
Enter N followed by the sequence of commands.
> 3
L R L
5 4 1 8 7 2 3 6
> 3
L L L
7 2 3 6 5 4 1 8
> 3
R R R
2 7 6 3 4 5 8 1
> 3
R L R
4 5 8 1 2 7 6 3
>
Seems to be good.
This is easier said than done. How do you get an index to the other array out of the hash code? This requires a very specific and contextualized hash function. How do you choose the hash function? How do you even find it efficiently?
Compilation warnings aside, your getPoint() function is wrong, and consequently the whole algorithm doesn't work.
Counter-example:
Find 6 in [ 6, 20, 15, 12, 11, 10, 9 ].
Hint: getPoint() will mistakenly recurse on array[4..6] looking for the maximum.
Can be solved in linear time.
Partition the array into a negative side and a positive side. The switch point can be found in O(n) by iterating from right to left until a negative value is found (or until we fall off the left end). It could even be found in O(log(n)) with a modified binary search, but it's not worth the hassle, since the rest of the algorithm is O(n). Let idx_negative be the index of the rightmost negative integer, or -1 if there are no negatives.
Now, perform a conceptual merge sort where one array is the subarray A[idx_negative+1..n-1] and the other array is the array that you'd get if you travel right to left on the negative side, taking the absolute value of each element along the way.
In other words, the problem reduces to a merge step of mergesort if you look at your array as 2 independent sorted arrays (where the negative array is traversed right to left after getting the absolute value of each element). To avoid counting the same number twice, keep track of the previous number that would have been inserted in the output array of mergesort - if the current number is equal, don't count it, otherwise, count it.
Implementation in C:
#include <stdio.h>
#include <assert.h>
unsigned abs_distinct_merge(int arr[], size_t arr_sz, int idx_positive, int idx_negative, int last) {
unsigned res = 0;
while (idx_negative >= 0 && idx_positive < arr_sz) {
int next;
if (-arr[idx_negative] < arr[idx_positive]) {
next = -arr[idx_negative];
idx_negative--;
} else {
next = arr[idx_positive];
idx_positive++;
}
if (next != last) {
res++;
}
last = next;
}
while (idx_negative >= 0) {
if (last != -arr[idx_negative]) {
res++;
}
last = -arr[idx_negative];
idx_negative--;
}
while (idx_positive < arr_sz) {
if (last != arr[idx_positive]) {
res++;
}
last = arr[idx_positive];
idx_positive++;
}
return res;
}
unsigned abs_distinct(int arr[], int arr_sz) {
int right_neg;
for (right_neg = arr_sz-1; right_neg >= 0 && arr[right_neg] > 0; right_neg--)
; /* Intentionally left blank */
int idx_positive = right_neg+1;
int idx_negative = right_neg;
int last;
if (idx_negative >= 0 && idx_positive < arr_sz) {
if (-arr[idx_negative] < arr[idx_positive]) {
last = -arr[idx_negative];
idx_negative--;
} else {
last = arr[idx_positive];
idx_positive++;
}
} else if (idx_negative >= 0) {
last = -arr[idx_negative];
idx_negative--;
} else if (idx_positive < arr_sz) {
last = arr[idx_positive];
idx_positive++;
} else {
assert(0);
}
return abs_distinct_merge(arr, arr_sz, idx_positive, idx_negative, last)+1;
}
static int array_buf[1024];
int main(void) {
printf("Enter array size, followed by the elements. Array must be sorted.\n");
printf("> ");
size_t array_sz;
while (scanf("%zu", &array_sz) == 1) {
assert(array_sz <= sizeof(array_buf)/sizeof(array_buf[0]));
size_t i;
for (i = 0; i < array_sz; i++) {
scanf("%d", &array_buf[i]);
}
unsigned distcount = abs_distinct(array_buf, array_sz);
printf("Absolute distinct count = %u\n", distcount);
printf("> ");
}
return 0;
}
The problem can be solved in O(n).
Basically, at each index K you need to know if the largest element in A[0..K-1] is less than or equal to A[K], and if the smallest element in A[K+1..N-1] is greater than or equal to A[K].
Build two auxiliary arrays, mins and maxs, such that mins[i] stores the smallest element in array[i+1..N-1], and maxs[i] stores the largest element in array[0..i-1]. The auxiliary arrays can be built in O(N).
After building the auxiliary arrays, iterate through the array once more, looking for a position where maxs[K] <= array[K] and mins[K] >= array[K]. If found, return it; otherwise, if the loop ends, no such K exists.
Working implementation:
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
vector<int>::const_iterator magnitude_pole(const vector<int> &arr) {
if (arr.size() == 0) {
return arr.end();
}
vector<int> mins(arr.size());
vector<int> maxs(arr.size());
mins[arr.size()-1] = numeric_limits<int>::max();
maxs[0] = numeric_limits<int>::min();
for (vector<int>::size_type i = 1; i < arr.size(); i++) {
mins[arr.size()-1-i] = min(mins[arr.size()-i], arr[arr.size()-i]);
maxs[i] = max(maxs[i-1], arr[i-1]);
}
for (vector<int>::size_type i = 0; i < arr.size(); i++) {
if (maxs[i] <= arr[i] && mins[i] >= arr[i]) {
return arr.begin()+i;
}
}
return arr.end();
}
int main(void) {
cout << "Enter number of elements in array followed by each element" << endl;
cout << "> ";
vector<int>::size_type elems;
while (cin >> elems) {
vector<int> array(elems);
for (vector<int>::size_type i = 0; i < elems; i++) {
cin >> array[i];
}
vector<int>::const_iterator mag_pole = magnitude_pole(array);
if (mag_pole == array.end()) {
cout << "No magnitude pole found." << endl;
} else {
cout << "Magnitude pole found at index " << mag_pole-array.begin() << endl;
}
cout << "> ";
}
return 0;
}
Won't work. Counter-example: 1, 2, 9, 9, 2. Can be sorted by swapping the first 9 with the second 2; the code throws an exception.
Doesn't work. This code is checking whether the array has at most one element out of place.
Consider this array:
1, 2, 3, 9, 6, 7, 4, 12, 13
The code will return false, but the array can be made sorted by swapping 9 with 4, so it should return true.
Won't work.
Take this heap as an example:
15, 12, 10, 8, 9, 5, 6, 6, 7, 8, 5
For k = 7 (counting from 1), the k-th max is in level 3 (counting from 0), and your algorithm would assume it's in level 2 because levels 0-2 contain 7 elements.
It can be found in linear time using a suffix tree. The algorithm is described in Algorithms on Strings, Trees and Sequences, section 7.4.
Suppose the strings to match are str1 and str2. The algorithm works as follows: first, build the generalized suffix tree for both strings. If you're not familiar with the concept, it's basically a suffix tree for both str1 and str2, that is, the same tree stores both the suffixes of str1 and str2. The only difference when compared with a traditional suffix tree is that the leafs in a generalized suffix tree can have different terminators (there is one terminator for each input string). So, for example, if str1 has size M and str2 has size N, we will have M+1 leafs with the terminator for str1 - let it be $1 - and N+1 leafs with the terminator for str2 - let it be $2.
For this problem, the generalized suffix tree traditional algorithm is modified so as to keep track of which terminators are in a given subtree. An internal node is marked with a 1 if there is at least a leaf below that contains the terminator $1; we do the same thing for str2 and $2.
The generalized suffix tree can be built in linear time using Ukkonen's algorithm.
Now, with the generalized suffix tree, the problem is reduced to finding the internal node with the largest string-depth that was marked with both a 1 and a 2, since internal nodes marked twice represent common substrings. So, just traverse the tree and visit every node to find the deepest one that meets such criteria. Once found, the longest common substring corresponds to the string path of that node.
It is considerably easier to understand and explain when in a whiteboard -- this is very well suited for an in-person interview.
I do believe that the point of the question is to have you explain the algorithm and show that you understand suffix trees and their construction, but I think that implementing it in the timespan of an interview is extremely hard, if not impossible. Suffix tree construction is a hard topic and coming up with bug-free code is not trivial.
Is the question about printing an unsorted list in sorted order (ascending and descending), or is it about printing a list left-to-right and right-to-left?
If it's the former, it's pretty much impossible unless you are given some specific information about the data that the list holds, since sorting in general is not achievable in O(n).
The solution to this problem is outlined by Jon Bentley in Programming Pearls, Column 2. The idea is that the amount of characters to rotate acts as if your string was divided into two blocks, A and B, such that the original string is AB and you wish to turn it into BA.
The elegant way to do it is with reverse(reverse(A) + reverse(B)). This is time- and space-efficient.
Out of curiosity, here's a small interesting excerpt of that Column: Brian Kernighan and P. J. Plauger used precisely this code in their 1981:
#include <stdio.h>
#include <string.h>
void reverse(char *str, size_t begin, size_t end) {
while (begin < end) {
end--;
char tmp = str[begin];
str[begin] = str[end];
str[end] = tmp;
begin++;
}
}
void left_rotate(char *str, size_t amt) {
size_t str_sz = strlen(str);
amt %= str_sz;
reverse(str, 0, amt);
reverse(str, amt, str_sz);
reverse(str, 0, str_sz);
}
static char input_buf[512];
int main(void) {
printf("Enter a string and a value to rotate it left.\n");
printf("> ");
while (scanf("%s", input_buf) == 1) {
size_t amt;
scanf("%zu", &amt);
left_rotate(input_buf, amt);
printf("%s\n", input_buf);
printf("> ");
}
return 0;
}
Hi, glad you found the code useful. I haven't touched Java for a while, so I'm afraid I can't help you much on that. I'm not comfortable with it and it would take me a while, I guess. But if you understand the algorithm, and if you know Java, it should be easy for you to convert it. Just make sure to understand how powerset_aux() works and you're good. About the memory error: well, the algorithm is O(2^N), and it can't possibly get any better than that, so you will always be out of memory pretty soon. An iterative approach may trade memory usage by runtime, but then your program just won't terminate anytime soon. There's nothing you can do about that.
Sort the array. Then, code the usual recursive powerset implementation, but with some changes: each call will first recursively compute the powerset without the current element. Then, iterate from the current index and keep incrementing until a different element is found. Now, recurse with 1 element, 2 equal elements, 3 equal elements, etc., but passing the index of the first different element to the next call.
Here's a working implementation in C++:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
static void powerset_aux(const vector<int> &elems, vector<int>::size_type elems_i, vector<int> &out_buff) {
if (elems_i >= elems.size()) {
cout << "{ ";
if (out_buff.size() > 0) {
cout << out_buff[0];
}
for (vector<int>::size_type i = 1; i < out_buff.size(); i++) {
cout << ", " << out_buff[i];
}
cout << " }" << endl;
return;
}
vector<int>::size_type next_different;
for (next_different = elems_i+1;
next_different < elems.size() && elems[next_different] == elems[elems_i];
next_different++)
; /* Intentionally left blank */
powerset_aux(elems, next_different, out_buff);
for (vector<int>::size_type next_eq = elems_i; next_eq != next_different; next_eq++) {
out_buff.push_back(elems[next_eq]);
powerset_aux(elems, next_different, out_buff);
}
for (vector<int>::size_type i = elems_i; i != next_different; i++) {
out_buff.pop_back();
}
}
void powerset(vector<int> &elems) {
sort(elems.begin(), elems.end());
vector<int> buff;
powerset_aux(elems, 0, buff);
}
int main(void) {
cout << "Enter the number of elements, followed by each element, to generate the power set." << endl;
cout << "> ";
vector<int>::size_type elems_no;
while (cin >> elems_no) {
vector<int> elems;
for (vector<int>::size_type i = 0; i < elems_no; i++) {
int element;
cin >> element;
elems.push_back(element);
}
powerset(elems);
cout << "> ";
}
return 0;
}
Space complexity is not O(1)- 010010.bin September 23, 2015 | https://careercup.com/user?id=5760419939483648 | CC-MAIN-2020-24 | refinedweb | 6,219 | 59.43 |
Added CMFD Functionality - Tally windows, statepoint write/restart, in-memory functions
Created by: shikhar413
This PR adds more functionality to the current CMFD implementation to make it easier to run CMFD functions in memory and on larger benchmark problems with better accuracy. The following features are included as part of the PR:
- Numpy 32-bit precision: The
weightfactorsnumpy array passed to OpenMC through the CAPI is now explicitly defined as a 32-bit array. This is because I was finding that originally passing a default 64-bit array led to k-effective values passed back from OpenMC that had slight discrepancies for large test cases that became larger as the cycles progressed. A 32-bit numpy array ensures consistent results for the same test case. This is also the main cause of values changing in the CMFD test suite.
- Restart capabilities from statepoint file: All relevant data needed to restart a CMFD run is now outputtted to statepoint file, and this statepoint file can also be used to restart a CMFD run. More details below.
- Separating
tally_beginand
feedback_begin: Originally, if CMFD is run with feedback, the batch at which CMFD tallies begin and the batch when feedback is turned on had to be the same. However, a lot of times it is beneficial to aggregate CMFD tallies over a few batches before turning CMFD feedback on to ensure that a large enough tally window has been accumulated. This is now implemented by defining
tally_beginand
feedback_beginvariables
- Add functions to allow CMFD to be run in-memory batch-by-batch: Similar to the C API functions, the
CMFDRunclass now has functions
run_in_memory,
iter_batches,
init,
next_batch,
finalizeso that users can run CMFD in-memory batch-by-batch as follows:
from openmc import cmfd cmfd_run = cmfd.CMFDRun() with cmfd_run.run_in_memory(): do_stuff_before_simulation_start() # e.g. define new tallies, set certain tallies to active for _ in cmfd_run.iter_batches(): do_stuff_between_batches() # e.g. observe behavior of tallies, source distribution
- Tally window options: Currently, the CMFD matrix system that is solved from batch
tally_beginonwards is based on tallies aggregated from the very first batch. However, tallies from initial batches are usually biased and should not be used to update the source many batches later. While CMFD tallies can be reset at specific batches, this usually causes the CMFD k-effective value to spike suddenly, since the previous CMFD update uses tallies aggregated over a large number of batches, while the following update is based on tallies from only one batch. To smoothen out this behavior, users have the option to choose between a "rolling window" and "expanding window" type for tally aggregation, based on work by @bhermanmit and @lilulu. More details below:
- Reference diffusion parameters: Another way to smoothen out CMFD behavior and allow for feedback to start at an earlier batch is to be able to specify reference diffusion coefficients that will be used to set
dhatand
dtildeat each batch. Normally, the diffusion coefficient is calculated at each batch using the P1 scattering approximation, but the
CMFDRun.ref_dvariable can be used to define reference diffusion coefficients for each group (e.g. from CMM).
CMFD Restart FunctionalityCMFD Restart Functionality
The variables outputted to statepoint file can be found in
CMFDRun._write_cmfd_statepoint. While some of these variables are not essential to restart the simulation (such as
window_type,
albedo,
coremap,
indices etc.), many are outputted to overwrite parameters set during a restart run to ensure that users do not change these parameters mid-simulation and lead to unexpected behavior. In terms of how
statepoint_write works, I make sure that statepoint files are written only if this function is called. Typically, a statepoint file is written right after
openmc.capi.next_batch() is called (but before CMFD is run for that batch), but this outputs an incorrect source to the statepoint file that does not have source weights updated through CMFD. Thus, a statepoint is written only after CMFD is run for that batch, using either the function
CMFDRun.statepoint_write() in-memory or by specifying statepoint batches in the settings.xml file. In order to make this work, I create the variable
cmfd_run and function
openmc_is_statepoint_batch() in OpenMC.
Restarting a CMFD simulation from a restart file is also slightly roundabout. CMFD tallies are outputted to statepoint file, but the way OpenMC is currently implemented, tally data is only populated for tallies that have been defined in the tallies.xml file during openmc_simulation_init(). However, since CMFD tallies are defined in-memory, CMFD tally data is never populated since these tallies have not been initialized yet by the time
load_state_point is called in OpenMC. Thus the following workaround is proposed to reset CMFD data and tallies:
openmc.capi.init(args=['-r','res_file.h5']) # Specify restart_run and restart_file openmc.capi.simulation_init() # calls load_state_point CMFDRun._create_cmfd_tally() # allocate CMFD tallies in memory openmc.capi._dll.openmc_load_cmfd_tallies() # populate CMFD tally data from statepoint file
The last two function calls occur in CMFDRun._reset_cmfd which is called by CMFDRun._configure_cmfd in CMFDRun.init()
Description of tally window typesDescription of tally window types
This PR introduces two new types of window types, a rolling window and an expanding window. A rolling window is a fixed window width that moves over by one batch once the window size has been met. On the other hand, an expanding window doubles in size once tallies from previous batches have filled up the entire window. This is based on making sure that more batches are used to compute CMFD parameters at later batches, since there should now be less chance of biased tallies affecting results. The illustration of these two window schemes are given below, taken from @lilulu's Ph.D. thesis (tallies from batch 1 are typically discarded for large problems like 2D BEAVRS). Rolling window: Expanding window (Window at batch 2 is not shown since it is not used for feedback but is of size 1):
To implement these types of windowing schemes, I introduce cross section rate variables like
total_rate,
p1scatt_rate etc that save tally data at each batch in
CMFDRun._compute_xs(), where tallies are reset every batch. The actual cross sections are now defined as the sum of these rate variables over the defined window size. Note that the cross section rate variables grow at the size of the window. By default,
window_type is set to
'none' and this implementation is incorporated within the framework of using cross section rate variables so that
CMFDRun._compute_xs() can be kept as general as possible. | https://xgitlab.cels.anl.gov/shikhark/openmc/-/merge_requests/1222 | CC-MAIN-2020-40 | refinedweb | 1,071 | 51.89 |
Build a Spring Boot App with User Authentication
JavaScript is the language on fire. Build an app for any platform you want including website, server, mobile, and desktop.
Spring Boot makes it fun and easy to build rich Java webapps. It allows you to rapidly develop, test, run and deploy Spring applications. Plus with over 100 starters, Spring Boot provides a huge amount of out-of-the-box functionality that traditionally you had to build yourself.
While Spring Boot makes it easier to build Java applications, authentication and authorization protocols can still be one of the biggest pain points for any application developer. Good news though! This 15-minute tutorial shows you how to build a fully-operational Spring Boot webapp that protects user access to restricted paths with Spring Security and Stormpath.
You never have to build auth again with Stormpath's Spring Boot integration, which offers out-of-the-box identity management that you can implement in minutes. You'll see how easy it is to roll out a simple Spring Boot web application, with a complete user registration and login system, with these features:
- Login and registration pages
- Password reset workflows
- Access control based on Group membership
- Additional configurable features from the Stormpath Java library, including API authentication, SSO, social login, and more
This demo uses the
stormpath-default-spring-boot-starter. The modular design of this starter encompasses Spring Boot 1.3.6 and Spring Security 4.1.1 as well as Spring Boot WebMVC, and the Thymeleaf templating engine. I will be using my Mac, the Terminal app, and the IntelliJ IDE.
Grab the code for this tutorial here, and follow along!
Also, throughout this post you can see the example code in action by clicking on the Deploy to Heroku button. All you need to do is register for a free Heroku account.
Get Stormpath
Stormpath is an Identity Management API that enables you to:
- Authenticate and authorize your users
- Store data about your users
- Perform password and social based login
- Send password reset messages
- Issue API keys for API-based web apps
- And much more! Check out detailed Product Documentation
In short, Stormpath makes user account management a lot easier, more secure, and more scalable.
The first step in this tutorial is to register for a free developer account here, if you don't already have one!
Set up Your Spring Boot Project
Whether you are a Maven maven or Gradle great, getting your project setup is a snap.
For Maven, start with this
pom.xml file:
<project xmlns="" xmlns: <modelVersion>4.0.0</modelVersion> <groupId>com.stormpath.sample</groupId> <artifactId>stormpath-spring-boot-spring-security-tutorial</artifactId> <version>0.1.0</version> <name>Spring Boot Spring Security Stormpath Tutorial</name> <description>A simple Spring Boot Web MVC application with Spring Security and out-of-the-box login and self-service screens!</description> <dependencies> <dependency> <groupId>com.stormpath.spring</groupId> <artifactId>stormpath-default-spring-boot-starter</artifactId> <version>1.0.RC9.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.3.6.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
Or, here's a
build.gradle file, if you prefer:
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE") } } apply plugin: 'java' apply plugin: 'maven' apply plugin: 'spring-boot' group = 'com.stormpath' version = '0.1.0' repositories { mavenCentral() } dependencies { compile group: 'com.stormpath.spring', name: 'stormpath-default-spring-boot-starter', version:'1.0.RC9.2' }
You may notice that we're working with a single dependency, regardless of whether you're using Maven or Gradle:
stormpath-default-spring-boot-starter.
That one dependency gives you all of the Spring Boot, Spring Security and Stormpath magic at once, which we'll demonstrate as we progress through the tutorial.
Gather Your API Credentials and Application href
The connection between your webapp and Stormpath is secured with an API key pair which your webapp will use when it communicates with Stormpath. Download your API key pair (it'll be the
apiKey.properties file) from the Admin Console.
Also in the Admin Console, you'll want to get the href for your default Stormpath Application. In Stormpath, an Application object is used to link your web app to your user stores inside Stormpath. All new developer accounts have an app called "My Application." Click on "Applications" in the Admin Console, then click on "My Application." On that page you will see the href for the Application. Copy this -- we will need it later.
Write the Spring Boot Application
The code for this section can be found in the LockedDown tag of the code repo.
We need three small Java classes and an html template to fire up the first version of our webapp. Let's get to it!
Spring Boot Application Entry Point
All Spring Boot applications have an entry point that works just like an ordinary Java program,
main method and everything.
Here's
Application.java:
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
It's just six little lines of code, including the
@SpringBootApplication annotation that kicks off the party.
Spring Security Configuration
Spring Security's default is to lock down your entire application. While this conforms to industry-standard best security practices, it's not terribly useful by itself. Additionally, we need to hook Spring Security and Stormpath together. That brings us to our
SpringSecurityWebAppConfig.java:
@Configuration public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.apply(stormpath()); } }
The
@Configuration annotation causes Spring Boot to instantiate this class as a configuration and
.apply(stormpath()) hooks all of the Stormpath authentication and authorization workflows into Spring Security.
Because there is no further configuration in the
configure method, we maintain the best practice behavior of having everything locked down. However, instead of the default Spring Security authentication flows, we will see the default Stormpath flows. Attempting to browse to any path in the application will result in a redirect to the Stormpath
login page.
Yep, you saw it happen. A one-line method call and we've got security!
Tie It All Together With Spring WebMVC
Our security configuration above ensures that all paths in the application will be secured.
A Controller determines how requested paths get directed to display which templates.
Here's our
HelloController.java:
@Controller public class HelloController { @RequestMapping("/") String home() { return "home"; } }
The
@Controller annotation signals Spring Boot that this is a controller. We have one path defined on line 3,
/. Line 5 returns the Thymeleaf template named
home. Welcome to MVC routing!
Bring Us
home.html
By default, the Thymeleaf templating engine will look for templates returned from controllers in a folder called
templates in your classpath. It will also look for the default extension of
.html.
When when the controller we just built returns
"home", Thymeleaf will find the template in
resources/templates/home.html.
Let's take a look at the
home.html file:
<html xmlns: <head> <!--/*/ <th:block th: /*/--> </head> <body> <div class="container-fluid"> <div class="row"> <div class="box col-md-6 col-md-offset-3"> <div class="stormpath-header"> <img src=""/> </div> <h1 th:Hello, [[${account.fullName}]]!</h1> <a th:Logout</a> </div> </div> </div> </body> </html>
Line 1 sets up the
th namespace for Thymeleaf.
Line 3 looks like an html/xml comment. However, this is a directive that Thymeleaf picks up on to include a fragment in this template. The fragment is found at:
resources/templates/fragments/head.html and contains all the setup needed to hook in Bootstrap styling for our views.
Lines 13 and 14 are where the action happens. Since every pathway in our application is locked down, we know that we can only access this page post-login. Part of the Stormpath magic is that once logged in, an
account object is always in scope to your views. Line 13 shows the logged in user's full name. Line 14 provides a link to log out when clicked.
Fire up Your Spring Boot Application
So that's 1 Stormpath account, 15 lines of Java code, and 19 lines of html template code (3 of which are significant) to bring us to the point of a fully functional Spring Boot WebMVC app protected by Spring Security and backed by Stormpath.
Wow.
If you stored your
apiKey.properties file from before in the standard location:
~/.stormpath/apiKey.properties and if you have only the default Stormpath Application that was created for you, no other configuration is necessary to start up the application.
Here's the Maven way:
mvn clean package mvn spring-boot:run
Note: The
spring-boot-maven-plugin also creates an uber-jar due to the presence of the
repackage execution. You can exercise the same code by just running Java:
mvn clean package java -jar target/*.jar
And, here's the Gradle way:
gradle clean build java -jar build/libs/*.jar
You can browse to and see it in action:
But wait! What if you stored your
apiKey.properties file somewhere else or you have other Stormpath Applications defined? Totally not a problem!
Remember that Application href you saved earlier? Go grab it.
Maven:
mvn clean package STORMPATH_API_KEY_FILE=~/.stormpath/apiKey.properties \ STORMPATH_APPLICATION_HREF= \ mvn spring-boot:run
Gradle:
gradle clean build STORMPATH_API_KEY_FILE=~/.stormpath/apiKey.properties \ STORMPATH_APPLICATION_HREF= \ java -jar build/libs/*.jar
By adding
STORMPATH_API_KEY_FILE and
STORMPATH_APPLICATION_HREF environment variables to the command line, we can easily tell our app where to find the API key pairs and which Stormpath Application to use.
The Stormpath Java SDK has an extremely flexible configuration mechanism. We will see more of that below when we get to restricting access to your application by Group membership.
Refined Access Control With Spring Security
The code for this section can be found under the
BasicAccessControl tag of the code repo.
So, in the last section we created a webapp that was locked up tight. Every path, including
/, required login.
But, maybe you need a publicly accessible home page. Or some areas of the site that any authenticated user can access and other areas restricted to members based on their Group.
Stormpath makes those kinds of fine-grained controls possible, and simple.
Spring Security: Your Bouncer at the Door
We'll start by allowing public access to the home page. Users will still have to authenticate to access any another page. Remember our empty
SpringSecurityWebAppConfig.java from before? We are going to add a little something to it now:
@Configuration public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .apply(stormpath()).and() .authorizeRequests() .antMatchers("/").permitAll(); } }
Spring Security provides a fluent interface for providing access rules.
On Lines 5 - 8 above, we are building a rule set for how Spring Security will allow access to our application.
You might state it like this in plain English:
Permit anyone to go to the front door Ensure that they've authenticated for anything else
The rules we are specifying take precedence before the default behavior of locking everything down.
Let's update our
home.html template as well:
<html xmlns: <head> <!--/*/ <th:block th: /*/--> </head> <body> <div class="container-fluid"> <div class="row"> <div class="box col-md-6 col-md-offset-3"> <div class="stormpath-header"> <img src=""/> </div> <!--/* displayed if account IS NOT null, indicating that the user IS logged in */--> <div th: <h1 th:Hello, [[${account.fullName}]]!</h1> <a href="/restricted" class="btn btn-primary">Restricted</a> <a th:Logout</a> </div> <!--/* displayed if account IS null, indicating that the user IS NOT logged in */--> <div th: <h1>Who are you?</h1> <a href="/restricted" class="btn btn-primary">Restricted</a> </div> </div> </div> </div> </body> </html>
Notice how we now have two distinct sections. The first starts on line 13 and is displayed if the user is logged in. The second section starting on line 20 is displayed if the user is not logged in.
Here you're seeing Thymeleaf templates in action! Thymeleaf provides very powerful controls for conditionally showing parts of a template.
Before we make any additional changes, let's pause and start up the app.
When you browse to, you should see the unauthenticated version of the
home template.
Click the
Restricted button, and you'll be redirected to the
login form, as expected. After you authenticate, you'll end up at a
404 page, because we haven't defined the restricted page yet.
Defining the restricted page is as easy as adding a route in our controller and creating a template to show. Here's the updated
HelloController.java:
@Controller public class HelloController { @RequestMapping("/") String home() { return "home"; } @RequestMapping("/restricted") String restricted() { return "restricted"; } }
And, here's a new
restricted.html template:
<html xmlns: <head> <!--/*/ <th:block th: /*/--> </head> <body> <div class="container-fluid"> <div class="row"> <div class="box col-md-6 col-md-offset-3"> <div class="stormpath-header"> <img src=""/> </div> <h1 th:[[${account.fullName}]], You are allowed here.</h1> <a href="/" class="btn btn-primary">Go Home</a> </div> </div> </div> </body> </html>
Notice how we re-use the
head fragment to provide Bootstrap styling for this template.
Re-start the app again, and you will get the full experience of the home page changing depending on whether or not you are logged in.
Spring Security Access Control By Group Membership
The code for this section can be found in the GroupAccessControl tag of the code repo.
Spring Security provides a set of annotations and a rich expression language for controlling access to methods in your application. Among the most commonly used Spring Security annotations is
@PreAuthorize. And, among the most commonly used SpringEL expressions is
hasRole.
We integrate with this mechanism, connecting Stormpath Groups to Spring Security roles.
Let's break down this code by adding a new service that restricts access by Group membership. Here's
AdminService:
@Service public class AdminService { @PreAuthorize("hasRole(@roles.ADMIN)") public boolean ensureAdmin() { return true; } }
Line 3 above is the key. The annotation along with the SpringEL expression could be stated in plain English as:
Before this method is even entered, check to see that user is authenticated and is a member of the ADMIN group
The
check to see that user is authenticated part of this may not be obvious. What's going on is that a
@PreAuthorize check can only be done on an authenticated user. Spring Security is smart enough to check that the user is logged in before checking to see if they are a member of the specified group.
Let's dig in to the Spring Expression Language above. Where is Spring Security looking for
@roles.ADMIN? The
@ symbol is special - it identifies a Java bean, in this case named
roles. Defined inside that bean we expect to find a constant named
ADMIN.
Ultimately,
hasRole needs to be checking against a unique href representing a Stormpath Group. So, our
ADMIN constant needs to be a Java
string that holds the href to our Stormpath Group used for admin.
To complete this configuration and to make it awesomely dynamic, we need a new class called
Roles.java:
@Component public class Roles { public final String ADMIN; @Autowired public Roles(Environment env) { ADMIN = env.getProperty("stormpath.authorized.group.admin"); } }
These 9 lines are so amazingly powerful, I'm geeking out over here! Are you seeing it yet?
By annotating this class with
@Component on line 1, Spring will instantiate it and expose it as a bean. Guess what the name of the bean is? Spring will take the name of the class and camel-case it to derive the bean name by default. So, the bean name is
roles. Sweet!
The
@Autowired annotation on line 5 causes the Spring
Environment object to be passed into the constructor. Inside the constructor, we have our only opportunity to set
ADMIN since it's declared
final - a requirement to be able to use it inside the
hasRoles clause.
The last piece of the puzzle utilizes some Spring configuration magic. Notice that we are setting the value of
ADMIN to whatever the environment property named
stormpath.authorized.group.admin is set to. This is standard Spring. If you have a property in your
application.properties file with this name, it will be available in the Spring Environment.
Spring also supports the ability to set this as a system environment variable, alleviating the need to have the value - a Stormpath Group href in this case - hardcoded anywhere in your application.
Typically, system environment variables are
ALL_CAPS_WITH_WORDS_SEPARATED_BY_UNDERSCORES. Spring automatically converts these system variables into the
lowercase.dotted.notation.
Dig this:
STORMPATH_AUTHORIZED_GROUP_ADMIN= \ java -jar build/libs/spring-boot-spring-security-tutorial-0.1.0.jar
Behind the scenes, Spring will convert the
STORMPATH_AUTHORIZED_GROUP_ADMIN system environment variable to a Spring env variable named
stormpath.authorized.group.admin. That will get picked up by our code above.
Now, we need to wire the
AdminService to our Controller. Here are the relevant parts of our updated
HelloController.java:
@Controller public class HelloController { @Autowired AdminService adminService; ... @RequestMapping("/admin") String admin() { adminService.ensureAdmin(); return "admin"; } }
AdminService is Autowired in on lines 4 & 5. Notice on line 11, we are calling the
adminService.ensureAdmin method. If the logged in user is NOT in the
ADMIN group, a
403 (forbidden) response will be generated.
The last bit of code housekeeping to do here is to create an
admin.html template. In the code that is associated with this post, there's a simple
admin.html template that shows a nicely formatted message confirming that you are, indeed, an admin.
Now, to see this in action, you'll need to do a little bit of Stormpath housekeeping in the admin console.
Here are the steps:
Create a new Application
Create a new Group called "admin" for the Application
Create a new Account in the admin Group
Create another new Account, but NOT in the admin Group
In the code for this post, I've also included a handy error page so that if you are not in the admin Group you get a nicely formatted page rather than the default
403 page.
Now we're going to start up the application again, only this time we'll use the hrefs found in the Admin Console for the new Application and Group you just created.
With Maven:
mvn clean package STORMPATH_API_KEY_FILE=~/.stormpath/apiKey.properties \ STORMPATH_APPLICATION_HREF= \ STORMPATH_AUTHORIZED_GROUP_ADMIN= \ mvn spring-boot:run
With Gradle:
gradle clean build STORMPATH_API_KEY_FILE=~/.stormpath/apiKey.properties \ STORMPATH_APPLICATION_HREF= \ STORMPATH_AUTHORIZED_GROUP_ADMIN= \ java -jar build/libs/spring-boot-spring-security-tutorial-0.1.0.jar
Browse to the
/admin page.
If you log in as the user you created in the Stormpath
admin Group (micah+admin@stormpath.com in my case), you will have access to the admin page. If you log in as the user you created that's NOT in the Stormpath
admin Group (micah+user@stormpath.com in my case), you will get the forbidden page.
No matter who you log in as, you will have access to the
/restricted page.
Wrapping Up
We've covered a lot of ground here, haven't we? Let's review:
- We saw how you can protect individual pages as well as protect methods based on membership in a Group.
- We saw how you can apply Stormpath in your class that extends
WebSecurityConfigurerAdapterto define access controls for different paths as well as make use of the Spring Security
@PreAuthorizeannotation for a finer grain of control.
- We saw how the Stormpath Java SDK manages environment configuration properties to provide a high degree of flexibility for your application without having to hardcode anything.
There are a ton of additional features in the Java SDK and the Spring Boot integration that I didn't demonstrate in this tutorial. You can walk through a more in-depth Stormpath tutorial here.
If you have questions or want to learn more catch me on Twitter @afitnerd ot drop a line over to support anytime.
This content is sponsored via Syndicate Ads | https://scotch.io/tutorials/build-a-spring-boot-app-with-user-authentication | CC-MAIN-2017-13 | refinedweb | 3,350 | 57.16 |
Introduction
In the GraphQL specification, we have different built-in scalar types. We have described them in the dedicated article. But what can we do if we need to use scalars which are not defined in the GraphQL specification? The answer is to use the so-called custom scalar. The implementation of the GraphQL custom scalar can vary based on the language you use for building GraphQL server. In some of these implementations, it may not be even possible to use custom scalars. In our case, we will on building custom scalar with our official graphql-js library.
We will continue with the same repository as with the enums and built-in scalars. You can clone the GitHub repository using this command
You can quickly start with:
git clone git@github.com:atherosai/graphql-gateway-apollo-express.git
install dependencies with
npm i
and start the server in development with
npm run dev
Custom scalar definition
As mentioned the built-in scalars might not be able to fulfil all the required parsing and validating of the input or output. That is the reason why we need to sometimes implement our own scalar. In this quick tutorial, we will implement DateTime custom scalar, which can be used for all date fields in your project. You can replicate all the steps also to build your scalars based on your needs. Now let’s go right into the designing of the DateTime scalar. We will use validator-js library to test if the value is in ISO8601 date-time string format. The simplified definition of the DateTime scalar can be as follows:
import { GraphQLScalarType } from 'graphql';import { isISO8601 } from 'validator';// This is only very simple DateTime scalar to show how to create your custom scalars. You can use some of the libraries for production use cases.const parseISO8601 = (value: any) => {if (isISO8601(value)) {return value;}throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');};const serializeISO8601 = (value: any) => {if (isISO8601(value)) {return value;}throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');};const parseLiteralISO8601 = (ast: any) => {if (isISO8601(ast.value)) {return ast.value;}throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');};const DateTime = new GraphQLScalarType({name: 'DateTime',description: 'An ISO-8601 encoded UTC date string.',serialize: serializeISO8601,parseValue: parseISO8601,parseLiteral: parseLiteralISO8601,});export default DateTime;
In graphql-js, each custom scalar type definition has different fields and methods that should be defined. Just as with input/output object types, we have to define the required field name of the scalar. The description field is once again mandatory. If you read the article on built-in scalars we went through input and result coercion for each type. This is already predefined in graphql-js library for built-in scalars. However, when we define our own custom scalar, we have to specify these rules. That is why we have to define a couple of methods for each custom scalar. These are:
- serialize: result coercion
- parseValue: input coercion for variables
- parseLiteral: input coercion for inline arguments
Serialize
The serialize function refers to the result coercion. The first argument for this function is the received value itself. In our case, we would like to check if the value is in ISO8601 date format. If the received value passes the validation, we want to return this value; otherwise, we would raise the GraphQL error.
ParseValue and parseLiteral
The parseValue and parseLiteral function refer to the input coercion. The difference is that in parseValue, we refer to the input passed using the variables. When we use parseValue, the first argument of this function is the value itself. On the other hand, the parseLiteral function has its first argument the ast value in the following format
{ "kind": "StringValue","value": "2017-10-06T14:54:54+00:00","loc": { "start": 51, "end": 78 } }
That is why we have to extract the value from the ast variable and again validate it by our rules.
Implementation
We have completed the definition of our custom scalar, and therefore it is possible to implement it in the schema. We will apply it on the timestamp fields createdAt and updatedAt for our Task type. We can simply import our Date Time scalar and use it as a type for these fields. check out if our rules, which we defined works as expected. Just go to GraphQL Playground and try to call the basic getTasks query:
query getTasks {tasks {idnametaskPriorityprogresscreatedAtupdatedAt}}
If our custom Date Time scalar is implemented correctly, you should get something like this:
{"data": {"tasks": [{"id": "7e68efd1","name": "Test task","taskPriority": 1,"progress": 55.5,"createdAt": "2017-10-06T14:54:54+00:00","updatedAt": "2017-10-06T14:54:54+00:00"}]}}
Now let’s test out our serialize function. Just go to the task-db.ts file and reassign createdAt or updatedAt to a string which is not in ISO8601 date format. We will change the createdAt field to 2017–10–06T14:54:54+0. Now if we try to call the getTasks Query, the GraphQL server will raise the following error:
{"data": {"tasks": [null]},"errors": [{"message": "DateTime cannot represent an invalid ISO-8601 Date instance","locations": [{"line": 7,"column": 5}],"path": ["tasks",0,"createdAt"]}]}
Summary
Custom scalars provide an even greater benefit when we have a collection of our predefined custom scalars. Then we can centralize most of our custom validations and move them from our resolver functions to our custom scalar types. Our simple Date Time scalar was a great model example. However, if you want to use more complex scalars like JSON or more precisely defined Date Time scalars, etc., it is possible to use some of the open-sourced npm packages. These include:
- JSON: Using JSON as a scalar.
- Date Time: It is a library you can use for more precisely defined Date Time scalar. In this library, Time and Date scalars are also available.
- Custom scalar collection: This package is a collection of custom scalars .
Did you like this post? The repository with the examples and project set-up can be cloned here. Feel free to send any questions about the topic to david@atheros.ai. | https://atheros.ai/blog/how-to-design-graphql-custom-scalars | CC-MAIN-2022-40 | refinedweb | 1,024 | 63.09 |
I am starting to learn Scala and got into this simple problem. I am used to doing this using Unix command line with Bash and Awk but I decided to use Scala for learning.
I want to parse multiple text file which are tab separated and want to extract 1 or any arbitrary column.
I also want to remove lines that start with "#" which I was able to do.
The code below will print first row from a specific column from each file.
How do I get it to print all the rows?
import scala.io.Source
if (args.length > 0){
for (arg<-args){
val file= Source.fromFile(arg).getLines.filter(s => !(s contains "#")).mkString("\n").split("\t")
println(file(2))
}
}
else
Console.err.println("Please enter filename")
Calling mkString("\n") on getLines will result in a single string of the entire file and that is the reason you are seeing output for first row alone.
The following code snippet should be working:
if (args.length > 0) { for (arg <- args) { println(Source.fromFile(arg).getLines().filterNot(_.trim.startsWith("#")).map(_.split("\t")(2)).mkString("\n")) } } | https://codedump.io/share/qOwNAHNNA9ME/1/reading-multiple-files-and-extracting-1st-column-using-scala | CC-MAIN-2018-09 | refinedweb | 186 | 67.04 |
virtualbox: Error opening file for reading
Bug Description
I have just upgraded my Kubuntu system from 11.10 to 12.04, and then installed virtualbox. I have gotten far enough to install Oracle_
I am seeing the following error on both version 4.1.12 (in the 12.04 release) and in the latest downloadable version from Oracle 4.1.16.
Everytime I start up virtualbox, I get the error:
[CODE]Error opening file for reading: Permission denied[/CODE]
Running strace on this process (well, seems I have to run it on the shell within which I start virtualbox) I can see the following:
[CODE]
15128 open("/
15128 dup(2) = 19
15128 fcntl(19, F_GETFL) = 0x8002 (flags O_RDWR|O_LARGEFILE)
15128 fstat(19, {st_mode=
15128 mmap(NULL, 4096, PROT_READ|
15128 lseek(19, 0, SEEK_CUR) = -1 ESPIPE (Illegal seek)
15128 write(19, "Error opening file for reading: "..., 50) = 50
15128 close(19) = 0
[/CODE]
This error does not seem to cause a problem, and the virtualbox session proceeds without further problems.
Looking about the web, I see that virtualbox is apparently trying to open /proc/self/auxv in order to determine some system capabilities, and that it is realized that this is not a reliable method -- auxv may or may not be readable.
In my situation, auxv is reliably NOT readable .
The following shell command reliably shows the contents of what is, I suspect, the desired auxv information:
[CODE]LD_
For example on my Kubuntu 12.04 amd64 system, it shows:
[CODE]
AT_SYSINFO_EHDR: 0x7fffcd7c4000
AT_HWCAP: bfebfbff
AT_PAGESZ: 4096
AT_CLKTCK: 100
AT_PHDR: 0x400040
AT_PHENT: 56
AT_PHNUM: 9
AT_BASE: 0x7ffc2640c000
AT_FLAGS: 0x0
AT_ENTRY: 0x401134
AT_UID: 1000
AT_EUID: 1000
AT_GID: 1000
AT_EGID: 1000
AT_SECURE: 0
AT_RANDOM: 0x7fffcd772489
AT_EXECFN: /bin/true
AT_PLATFORM: x86_64
[/CODE]
The following code might provide a useful and reliable means of parsing this auxv information:
[CODE]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* The following flgets() and examine_auxv() routines are Copyright
* 2006 and 2012 respectively by Paul Jackson <email address hidden>.
*
* These routines are free software; you can redistribute them and/or
* modify them may obtain a copy of this license from: <http://
*/
/*
* char *flgets(char *buf, int buflen, FILE *fp)
*
* Obtain one line from input file fp. Copy up to first
* buflen-1 chars of line into buffer buf, discarding rest
* of line. Stop reading at newline, discarding newline.
* Nul terminate result and return pointer to buffer buf
* on success, or NULL if nothing more to read or failure.
*
* Paul Jackson
* 20 Feb 2006
*/
static char *flgets(char *buf, int buflen, FILE * fp)
{
int c = -1;
char *bp;
bp = buf;
while ((--buflen > 0) && ((c = getc(fp)) >= 0)) {
if (c == '\n')
goto newline;
*bp++ = c;
}
if ((c < 0) && (bp == buf))
return NULL;
if (c > 0) {
while ((c = getc(fp)) >= 0) {
if (c == '\n')
}
}
newline:
*bp++ = '\0';
return buf;
}
/*
* int examine_auxv(const char *pattern, char *buf, int buflen)
*
* Examine /proc/self/auxv, as formatted in the manner
* seen by running the command:
* LD_SHOW_AUXV=1 /bin/true
* Return the first line that has some substring matching
* the input "pattern". Return up to the first (buflen-1)
* characters of that line, nul-terminated, in the provided
* buffer "buf".
*
* Only the first buflen-1 characters of each line are examined
* for the input pattern. If that pattern is not entirely
* contained within those buflen-1 characters, it will not
* found on that line.
*
* Return zero if a match is found and placed in buf, else
* return -1 and (in most cases - see popen(3) man page)
* set errno appropriately. If no match is found, the
* buffer buf is overwritten with the last line of input
* from the above command.
*
* Paul Jackson
* 17 June 2012
*/
int examine_auxv(const char *pattern, char *buf, int buflen)
{
char *bp;
FILE *fp;
fp = popen("
while ((bp = flgets(buf, buflen, fp)) != NULL) {
if (strstr(bp, pattern) != NULL) {
return 0;
}
}
pclose(fp);
return -1;
}
/*
* Test case for above:
*/
#define BUFLEN 256
char buf[BUFLEN];
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++) {
if (examine_
printf ("%s ==> %s\n", argv[i], buf);
}
exit(0);
}
[/CODE]
Also affects virtualbox 4.1.18, on my ubuntu 12.04 64bit
I tried an strace , but could not see any "denied" error.
To anyone who is trying to replicate and capture this error with strace. I had to:
[CLI]
sudo chmod u+s /usr/bin/strace
sudo -u <username> strace -f -o vbox.out VirtualBox
[/CLI]
The way I got the strace output, without having to make the strace binary setuid root, was to note the pid of my shell (echo $$), then in another terminal window, invoke strace as root on that shell. Then within the now strace'd shell, run virtualbox under my normal user id.
Does VirtualBox actually launch? I'm getting the same "Error opening file for reading: Permission denied" when launched VBox 4.1.18 (from the virtualbox repos) but VirtualBox loads up fine.
I'm running vbox as a non sudo user on 12.04 x64 server.
Have you made a thread over on the virtualbox forums/submitted a bug report?
Yes, virtualbox starts and works fine. I've just spent several hours in it, doing various Windows XP installs and configurations ... virtualbox worked flawlessly.
I am also running virtualbox on a 12.04 x64 system, non-super user.
I have not submitted any bug report to Oracle/virtualbox -- just this bug report to ubuntu.
Thanks.
I just tested it on Ubuntu 12.04 as an admin user and still got the same error, but VBox started just fine.
I have posted a question over on the virtualbox forums: https:/
I make a aptitude purge virtualbox-4.1 and a fresh package install from virtualbox.org.
worked fine for me.
wasare wrote:
>> I make a aptitude purge virtualbox-4.1 and a fresh package install from virtualbox.org.
>>
>> worked fine for me.
I only see the failure when running virtualbox as non-root.
===
One more important detail: the failing open of /proc/self/auxv apparently comes from the following file:
lrwxrwxrwx 1 root root 16 Jan 13 06:54 /usr/lib/
I say this for two reasons:
1) Just a few lines before the failing open in my strace, the most recent open is of this libjpeg.so library.
2) Scanning -all- the files opened in that strace, the -only- one of them that held the string "auxv" was this libjpeg.so library.
Apparently libjpeg-turbo8 (the package that owns this libjpeg.so library on my Kubuntu 12.04 system) is opening auxv in order to determine if some advanced SIMD instructions (MMX, SSE2, NEON) are available, to accelerate baseline JPEG compression.
Downloading libjpeg-turbo with this command:
bzr branch lp:ubuntu/precise/libjpeg-turbo
and searching the source code for "auxv", it seems that on my system (x86_64, but not APPLE) that the code tries to open /proc/self/auxv, and complains perror("Error opening file for reading") if the open fails, in the file: libjpeg-
"aptitude purge virtualbox-4.1 and a fresh package install from virtualbox.org"
Fixed the trouble running virtualbox as non-root and root user.
After i received the message: "Failed to load VMMR0.r0 (VERR_SUPLIB_
Fixed with:
chmod 0755 /usr
Now, when running from a terminal I get these message:
"
Error opening file for reading: Permission denied
Qt WARNING: QSpiAccessible:
"
But virtual box is working.
Wanderson Santiago dos Reis (wasare) :
The problem you are concerned with is NOT the problem this bug is concerned with.
Virtualbox has been working all along for me, all the time.
The only problem I am reporting in this bug report is the message "Error opening file for reading: Permission denied"
I have not seen, and this bug report is not reporting, a virtualbox failure with message "Failed to load VMMR0.r0 (VERR_SUPLIB_
Looking through the libjpeg code, it says in a README to send bug reports to <email address hidden>.
So I have just sent the following message there:
=======
As reported at https:/
Error opening file for reading: Permission denied
I have tracked this down to the perror() on line 49 of libjpeg-
I am seeing the error when I start up virtualbox as a non-root user, though just why /proc/self/auxv would not be readable by the current non-root user at that point in its startup is not clear to me.
I posted code in the first post of the first link above (see the routines flgets() and examine_auxv()) which -might- be more reliable. But it's using a sledge hammer to swat flies, calling popen("
=======
Thanks Paul. I'm not quite sure if this adds anything, but when I tested it on my 12.04 desktop box, /proc/self/auxv had permissions set to -r-------- (400) with the user and group set t whoever is logged in at the time.
In the case of my desktop - that is whoever is logged in either via ssh or desktop login:
vbox@Thor:~$ ls -ld /proc/self/auxv
-r-------- 1 vbox vbox 0 Jun 29 07:53 /proc/self/auxv
charles@Thor:~$ ls -l /proc/self/auxv
-r-------- 1 charles charles 0 Jun 29 07:53 /proc/self/auxv
Same on the server.
>> ... when I tested it on my 12.04 desktop box, /proc/self/auxv had permissions
>> set to -r-------- (400) with the user and group set t whoever is logged in at the time.
Well, /proc/self always links to the current process's /proc entry. It is just a short hand
for /proc/PID, where PID is the return from getpid(), or in most shells, the value of $$.
So I would have expected any virtualbox process to be able to read its own /proc/self/auxv,
as that special file would be owned by itself (and as you noticed, has permissions set to
allow the file owner to read it.)
It remains a mystery to me that a virtualbox process often can't read this auxv file.
Aha - /usr/lib/
pair of setresgid and setresuid calls, prior to the failure to open /proc/self/auxv. Perhaps the auxv file
retains its root ownership across these events, which would make it unable to be opened (EPERM) by
the non-root invoker.
The "Error opening file for reading" is caused by Ubuntu's patch to libjpeg-turbo library. I opened a separate bug report for it to libjpeg-turbo package here: https:/
The error message should be nonfatal, just obscure when it appears in application logs.
Status changed to 'Confirmed' because the bug affects multiple users. | https://bugs.launchpad.net/ubuntu/+source/virtualbox/+bug/1014487 | CC-MAIN-2018-13 | refinedweb | 1,757 | 60.85 |
On Sun, 19 Jan 2003 08:15:45 -0800, Dylan Reinhardt <python at dylanreinhardt.com> wrote: >At 03:41 AM 1/19/2003, Bengt Richter wrote: >>Why not write minimal code to illustrate? > > >My first post had this minimal code example: > Ok, sorry for my comment. > >------------------------- > > >------------------------- > > >>several_instances_of_spam[an_index_less_than_several].get_contained_egg( >> index_less_than_thousands).changed_attr = some_change > > >The whole point of doing it the way I'm doing it is to provide a clean, >Pythonic interface, thus: > >spam_instance.egg_instance.egg_method() > >should have a side effect on the spam instance. > I presume you mean "should" as a requirement of your problem, not "should because a spam has a reference in it to an egg (BTW, uppercasing the class name's first letter makes it so we can write Spam and spam for short instead of spam and spam_instance ;-) If you made Egg inherit from Spam, there would be a natural "should" implemented in the attribute access machinery's search sequence. E.g., since stuff is an attribute of Spam, you could monitor its use and though it's not going to be near as fast as direct references, it might be interesting to file for alternative ideas ... well, easier to show than talk about ;-) ====< spameggs.py >======================================== class Spam(object): stuff_monitoring_list = [] def _set_changed(self, v): self._changed = v def _get_changed(self): if self.__class__ is Spam: for egg in self.stuff_monitoring_list: self._changed = self._changed or egg.changed self.stuff_monitoring_list = [] return self._changed changed = property(_get_changed, _set_changed) def _set_stuff(self, v): self._stuff = v def _get_stuff(self): self.stuff_monitoring_list.append(self._stuff) return self._stuff stuff = property(_get_stuff, _set_stuff) def __init__(self): self.stuff = Eggs() self.changed = 0 class Eggs(Spam): def __init__(self): pass # must define or we get recursion via self.stuff above def do_stuff(self): # after we've done the main part of our work, # signal parent object that information has changed ## self.__some_namespace_voodoo__.changed = 1 self.changed = 1 # should find property in parent class return 'something_unrelated' ## string, to avoid name error here if __name__ == '__main__': a = Spam() b = Spam() print 'a=%s a.changed=%s' % (a, a.changed) print 'b=%s b.changed=%s' % (b, b.changed) print 'a.stuff_monitoring_list = %s' % a.stuff_monitoring_list x = a.stuff.do_stuff() # <--- should set value of a.changed to 1 print 'a.stuff_monitoring_list = %s' % a.stuff_monitoring_list print 'a._changed = %s, a._stuff._changed = %s' % (a._changed, a._stuff._changed) print 'a.changed = %s' % a.changed print 'a.stuff_monitoring_list = %s' % a.stuff_monitoring_list print 'a._changed = %s, a._stuff._changed = %s' % (a._changed, a._stuff._changed) print 'b.stuff_monitoring_list = %s' % b.stuff_monitoring_list x = b.stuff.do_stuff() # <--- should set value of b.changed to 1 print 'b.stuff_monitoring_list = %s' % b.stuff_monitoring_list print 'b.changed = %s' % b.changed print 'b.stuff_monitoring_list = %s' % b.stuff_monitoring_list =========================================================== If you run it, you get: [19:14] C:\pywk\clp>spameggs.py a=<__main__.Spam object at 0x007E0F70> a.changed=0 b=<__main__.Spam object at 0x007E0570> b.changed=0 a.stuff_monitoring_list = [] a.stuff_monitoring_list = [<__main__.Eggs object at 0x007E0F40>] a._changed = 0, a._stuff._changed = 1 a.changed = 1 a.stuff_monitoring_list = [] a._changed = 1, a._stuff._changed = 1 b.stuff_monitoring_list = [] b.stuff_monitoring_list = [<__main__.Eggs object at 0x007E0540>] b.changed = 1 b.stuff_monitoring_list = [] >>What is your concept of "subobject"? > >Hopefully this should be clear from the code example. > >>Sure, there's any number of ways to do it. But to choose one, we need to know >>how well/badly the above code reflects your problem world. > >Does the provided code do it? > >> class Egg: >> def __init__(self, my_container): >> self.my_container = my_container > > >This is actually what I'm doing now. If this is the best available answer, >I can certainly live with that, but it been surprised at what some of the >namespace wizards here have come up with in the past, so I thought I'd see >if there is a more elegant/efficient answer. > I doubt if you could get more efficient than a direct reference, but the property stuff might be interesting. Note that the Spam and Egg ._changed attributes attach to Spam and Egg instances respectively, but .changed goes through the property whether inherited or not -- but the accessor methods see different self instances. An egg instance still doesn't know about its "parent" container instance, but the Egg class does Know about the base Spam class, and an instance of either can find a Spam class variable like the stuff_monitoring_list. Of course, a reference in that list keeps an egg instance alive, so if that is a consideration, you might want to look into weak references, which would allow eggs to be deleted and their deletion later noticed via the weak references. > >>If you are in control over everything, there are going to be better ways, >>but it's >>not clear whether you are trying to tweak some big stuff you don't want to >>bother fully >>understanding, or whether you have creative control. > >The latter. I'm an experienced developer working on code I have total >control over. > >Thanks in advance, > Always fun to explore ;-) Regards, Bengt Richter | https://mail.python.org/pipermail/python-list/2003-January/184948.html | CC-MAIN-2014-15 | refinedweb | 835 | 70.9 |
As we've seen in the previous essay, Scala makes good use of immutability in its collections library, removing the need to be constantly making defensive copies of our data. In pure functional programming, all data is immutable. But Scala is not a pure functional language. It is functional, object-oriented hybrid (F/OO). Scala tries to bring in the best of both styles of programming. And while mutable data is fully supported, in general, we prefer not to use it. Code that uses immutable data is easier to reason about, and less prone to errors.
Scala's preference for mutable data can be seen in the alternative to the POJO - the case class. Both serve the same purpose: to provide a simple and easy way to describe types and objects with properties. For instance, in The POJO Myth, we saw this POJO that represents a Customer entity in the very early stages of development:
public class Customer {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
The Customer has a single property, firstName. This is not exactly the same as the private field firstName in the above code, since a property must be exposed by at least a getter method. The field itself is private, so it follows the OO principle that an object's data should never be directly exposed. But in a in a sense, it may as well be public, as the getter and setter more or less directly expose it.
The Scala equivalent to the POJO above is this:
case class Customer(firstName: String)
Case classes provide a lot of great functionality that goes well beyond what Java provides with POJOs. Take one example, they come with hashCode and equals methods based on the values of the properties. Writing correct hashCode and equals methods in Java is notoriously difficult, and the subject has an extensive writeup in Joshua Bloch's book Effective Java. Typically, we rely on our IDEs to generate a nasty glob of code for us and leave it at that.
Of course, in sharp contrast to the POJO, the case class is also immutable. If we want to change the Customer's firstName, first we change the way we are thinking, and say we want a copy of the Customer with a modified firstName. And we do it like this:
val customer2 = customer1.copy(firstName = "John")
If we were to build our domain model out of case classes and immutable collections, all our problems with maintaining our intra-aggregate constraints go away. To see that, let's recall our example from the last essay: An Order has multiple Order Items, each with their own quantity and price. The Order entity itself keeps track of the total price. We end up having to recompute our total price any time an Order Item changes, as well as any time the list of Order Items changes. When everything is immutable, we only have to compute the total price once, and we can do that in our constructor. The Scala code would look something like this:
case class OrderItem(quantity: Integer, price: Amount) {
val totalPrice = price * quantity
}
case class Order(orderItems: Seq[OrderItem]) {
val totalPrice = orderItems.map(_.totalPrice).sum
}
So what happens when somebody tries to change one of the Order Items? The answer is they can't, it's immutable. Instead, they can make a copy of the Order Item, with one or more of its properties modified. For example, let's "change" both the quantity and price for an Order Item. First, we create an Order with two Order Items:
val order = Order(Seq(OrderItem(2, "$9.99"),
OrderItem(3, "$19.95")))
Now, let's grab the first Order Item:
val firstItem = order.orderItems(0)
Now, let's change it:
val modifiedItem = firstItem.copy(quantity = 4, price = "$39.95")
firstItem remains entirely unchanged, and so does the Order. If we wanted to get a new Order that was the same as the original, but with the modified Order Item, we first need to create a modified list of Order Items:
val modifiedItems = order.orderItems.updated(0, modifiedItem)
Now we can create the new Order:
val modifiedOrder = order.copy(orderItems = modifiedItems)
Migrating from mutability to immutability does take a little shift in perspective when thinking about data. But it certainly isn't any harder to understand once you make that shift. The POJO equivalent to the above modification example might take one less line of code, but in exchange, the need for defensive copies and the complexities of recomputing the total price have gone away.
Let's take a step back in this essay, and revisit the PersistentState example we developed in Rethinking the POJO - the third essay in this series. At the time, we were trying to make our POJOs look and feel more like our actual domain entities - that is, closer to what appears in our UML diagrams. As we saw in The POJO Myth, our JPA POJOs end up containing a lot of clutter that is not representative of anything in our domain model, but instead manages persistence concerns, such as database identity, optimistic locking, and diagnostic fields such as createdBy and createdDate. Here's what an equivalent case class for the JPA POJO we saw there:
case class Customer(
customerId: Long,
firstName: String,
createdBy: User,
createdDate: Date,
lastModifiedBy: User,
lastModifiedDate: Date,
version: Long)
We were looking at redesigning that into something like this:
case class Customer(firstName: String)
case class PersistentState[E](
entity: E,
id: Long,
firstName: String,
createdBy: User,
createdDate: Date,
lastModifiedBy: User,
lastModifiedDate: Date,
version: Long)
entity: E,
id: Long,
firstName: String,
createdBy: User,
createdDate: Date,
lastModifiedBy: User,
lastModifiedDate: Date,
version: Long)
So we've begun to separate concerns, as we've untangled our persistent information from our domain. But we haven't hidden any of the implementation details of the PersistentState to the user. A model like the above might be fine for working within the persistence layer, but what would we want to present to the user outside of the persistence layer? A minimalist answer would be to say that they need to be able to get and set the entity. We certainly can get and set the entity with the above code. Notice that, in the fashion of immutability, setting the entity creates a new PersistentState. Here it is, spelled out step by step:
val retrievedState: PersistentState[Customer] =
customerRepo.retrieve(customerKey)
val retrieved: Customer =
retrievedState.entity
val modified: Customer =
retrieved.copy(firstName = "John")
val modifiedState: PersistentState[Customer] =
retrievedState.copy(entity = modified)
val updatedState: PersistentState[Customer] =
customerRepo.update(modifiedState)
There is a potential problem in the line where we create modifiedState: We've only updated the entity. Perhaps some of the persistent state information should be updated in a case like this, such as lastModifiedBy? So we really want an API that presents a getter and a setter, and hides the rest. We've already seen two similar examples that we can draw from. We saw how to create a new version of a list with the first element updated:
val modifiedItems = order.orderItems.updated(0, modifiedItem)
And we used method List.map to convert a list of Order Items to a list of total prices:
val totalPrice = orderItems.map(_.totalPrice).sum
The first example takes a modified item, and the second example takes a function that converts from Order Item to Amount. Let's try the second approach. Here is a version of PersistentState that hides all of the persistence details from the user:
trait PersistentState[E] {.
To see how manipulating PersistentStates might work in practice, let's add a couple of business methods to the Customer. The first one updates some Customer preferences, and the second validates:
case class Customer(firstName: String) {
def updatePrefs(changes: CustomerPrefsChanges): Customer = {
// returns a new customer with updated prefs
}
def validate: Customer = {
// returns this if this is a valid customer. otherwise,
// throws a validation exception
}
}
Now we can update the preferences of a persistent Customer like so:
val customerState2 = customerState1.map(_.updatePrefs(changes))
And we can validate like so:
val customerState3 = customerState2.map(_.validate)
The following service method looks up a Customer by natural key, updates the preferences, validates, and persists the results:
def updateCustomerPrefs(
key: NaturalKey[Customer],
changes: CustomerPrefsChanges): Unit = {
val retrieved = customerRepo.retrieve(key)
val updated = retrieved.map(_.updatePrefs(changes))
val validated = updated.map(_.validate)
customerRepo.update(validated)
}
You could fit the body of that method on a single line by inlining the local variables.
It may seem strange to consider your entities as immutable. After all, an entity is something that has a fixed identity and changes over time. But with a subtle change of mindset, we can think of the entity object as the current state of the entity, whereas state transitions are extracted from the object API, and placed into functions and service methods.
The most important thing to take forward from all this is that we should encapsulate the persistent state within the repository layer whenever possible. Making these fields private in the domain classes, with no getters and setters, is a good first step. But it is still less than ideal. Encapsulating things further provides for a workable but clunky interface in Java that feels much more natural in an F/OO language like Scala.
In the next essay, we will continue to look at immutability in our domain objects by considering the differences between entities and value objects in Domain Driven Design. | http://scabl.blogspot.com/2015/05/aeddd-12.html | CC-MAIN-2018-39 | refinedweb | 1,583 | 53.1 |
Since my project has been reliant of multiple networked nodes from day one, I've already been making use of I2c for almost every electronics project this semester. This week was intended to be a time to tie the entire project together.
The major remaining board I had to make was the Radar monitoring board. I finally got around to routing it this week and it was my plan to stuff it and get the entire system commmunicating over the I2c interface I've been building all semester.
I used the special circuit milling machine at work to make a double sided board and simplify making such a large board. I also played around with electroless through-hole plating for making vias. This process is quite useful for plating lots of small vias simultaneously and is a alternative to rivets. However, this process is not as simple as using the rivets and requires special safety precautions; it requires a chemical fume hood, corrosion resistant equipment, and experience handling chemicals properly. In the future, I'll probably only use through-hole plating in very specific instances and use rivets for most simple boards.
Meanwhile, the Op-amps I was waiting on from DigiKey which were required to complete the board decided they didn't want to cooperate with my schedule.
Instead I decided to put off finishing the main board until later this week and get some of the other networking related functionality working. One of these tasks was getting the cabling harness which will connect all the boards together made.
For cabling, I decided to use CAT-5e (commonly used for Ethernet) UTP (Unshield Twisted Pair) cable. It's 24 AWG so it can carry more current than the inexpensive ribbon cable. Additionally, The cable is quite cheap and abundant and has 8 conductors which means that there are enough strands to carry the I2c signal lines, VCC, and independent ground connections to avoid ground loops.
I'm interested in trying the vinyl cutter method to make my final harness but I suspect this may be a more weather resistant and durable solution.
After making the harness, I connected the two boards I had from previous weeks. Then I wrote a quick Arduino program (Adapted from an Arduino example) and used an Arduino Uno R3 in lieu of my final board. Although not ideal, this setup allowed me to test the functionality of the harness and ensure that both devices worked on the I2c network simultaneously.
#include <Wire.h> void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output } void loop() { Wire.requestFrom(16, 1); // request byte from slave device #16 Serial.println("Speed is:") while (Wire.available()) { // slave may send less than requested char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character } delay(300); Wire.requestFrom(40, 1); // request byte from speaker (this actually plays the tone) Serial.println("Playing speaker") delay(300); }
I initally started this semester not knowing about the multiple drop serial implementation. I still opted to use I2c for the project as the semester went on due to its provision for collision detection allowing multiple masters. I've yet to use this functionality yet on this project so I may think about simplifying my interface. | http://fab.cba.mit.edu/classes/863.16/section.Harvard/people/Garbarini/week12.html | CC-MAIN-2019-13 | refinedweb | 554 | 54.32 |
I some integrations up there.
But it is annoying for those of us who want something simple - like debug logs or notifications when scripts fail. Or something complex like conditional processing. Or even just a human to talk to when things break.
So, sod the lot of them. I'm slowing replacing my IFTTT "applets" with my own home-brew. Starting with...
RSS & Tumblr
I have a IFTTT recipe which
- Reads an RSS feed
- If there is a new item, queue it to Tumblr
Simple! And yet IFTTT randomly fails. It either can't read the RSS, or it doesn't spot new items, or it duplicates all my posts. Oh, and there's no way to set queued posts to automatically Tweet. It basically seems that IFTTT's MVP is certainly minimal, but sadly unviable.
This is a Python script which can be run as often as you like. It reads RSS, checks for new items, queues them, and sets Tweet text. NB - no Python 3 support yet because Tumblr can't be bothered to update their libraries.
Prerequisites
- Install pytumblr
- Install feedparser
- Create an app on Tumblr.
- Generate your Tumblr API tokens
The code
import pytumblr import feedparser import sys id_file = "id_file" # Authenticate via OAuth tumblr = pytumblr.TumblrRestClient( 'AAAAA', 'BBBBB', 'CCCCC', 'DDDDD' ) feed = feedparser.parse('') # Read the last id with open(id_file,'r') as file_: last_id = file_.read().strip() most_recent_id = feed['entries'][0]['id'] if (last_id == most_recent_id): # Do nothing sys.exit() else: # Save the new ID for later with open(id_file, 'w') as file_: file_.write(most_recent_id) # Loop through the posts for post in feed['entries']: # If the post has been encountered before, time to end things. if (last_id == post["id"]): sys.exit() else: # Queue it on Tumblr tumblr.create_text( "YOUR-TUMBLR-NAME", state="queue", title=post["title"].encode("utf-8"), format="html", body=post["summary"].encode("utf-8") )
Running
I have a crontab set up to run this a few times per day. By default, IFTTT seems to check every hour.
Caveats
- You will need a file called
id_fileto store the latest ID of the RSS feed.
- If your RSS feed doesn't have unique IDs, this may not work.
- This isn't exactly a robust, error-proof solution - but then, neither is IFTTT.
5 thoughts on “Replacing IFTTT - Part 1: RSS & Tumblr”
Hey Terence, I recommend trying out AWS Lambda to drive these little integrations.
AWS Lambda is interesting - but I'm tired of third party services. If I can't run it on my own machines, I'm at the mercy of Amazon shutting down the service, jacking the price up, or generally being idiots.
z.
You would probably enjoy tinkering with Node-RED I've replaced lots of the things I used to do with IFTTT to it.
Not to mention that IFTTT's ingredients stopped working ages ago. The text "Via RSS Feed" and the "EntryPublished" ingredient seem to be hard-coded, since the frontend received a major overhaul. | https://shkspr.mobi/blog/2016/12/replacing-ifttt-part-1-rss-tumblr/ | CC-MAIN-2018-34 | refinedweb | 496 | 67.35 |
---- I am doing some experiments about regression problem using pytorch. (e.g., input a noised image and output a denoised image). 1. In the training epoch, I first execute model.train(). 2. after each epoch, I do validation, and execute model.eval().I found the validation loss is normal (consistent with training loss) without calling model.eval(). However, the validation loss becomes much higher when executing model.eval(). So I guessed that this phenomenon may disappear in the test phase. Unfortunately, in the test phase, the performance is still bad when calling model.eval(), while is normal without doing it.
I also tried some other CNN tools, such as matconvnet and tensorflow, they both work fine, and the performance is better when calling ´model.eval()´ in the test phase. (I think it is related to the batchnorm module in my network, I hope for a higher performance when using running average and variance, but the results are opposite)
So anyone can help me on this? Thanks in advance.
Here is my network.
class Net(nn.Module):
def __init__(self):
self.layers = 17
super(Net, self).__init__()
self.layer_m = self.make_h_layers()
self.layer_f = nn.Conv2d(64, 1, 3, padding=1)
def make_h_layers(self):
layer_1 = nn.Sequential(nn.Conv2d(1, 64, 3, padding=1), nn.ReLU(inplace=True))
layer_m = nn.Sequential(nn.Conv2d(64, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True))
layers = []
layers.append(layer_1)
for i in range(self.layers-2):
layers.append(layer_m)
return nn.Sequential(*layers)
def forward(self, x):
x = self.layer_m(x)
x = self.layer_f(x)
return x
This is very likely to be caused by the BatchNorm layer. BatchNorm computes a running mean and variance that is used during prediction.
For some reason, the running mean/variance are not a good approximation of the true distribution of the activations during prediction. Maybe the batch size you used was to small, maybe the default momentum parameter for the running mean/variance (0.1 IIRC) for BatchNorm is too large in your case.
@smb thanks. But it seems the problems is not caused by the issues you mentioned. 1. currently the batch size is 128, i have also tried 256, the result is similar. 2. I set the momentum 0.01, but does not help.
I also believed this is caused by BatchNorm layer, when i drop out the model.eval() in the validation phase, the validation loss is very similar to training loss (i used the MSE loss). However, when model.eval() is activated, the performance becomes very bad, i found sometimes the performance becomes even worse and worse as the epoch increases (quite interesting).
So could list some more potential reasons?
Did you solve this problem? I run into the same problem these days...Use model.train() got very high performance even in the first iteration during the test time, but significance drop when use model.eval()....
If you are performing a train step followed by an ‘if step % ___ == 0’ condition to evaluate a test batch in that same step, YOU MUST CALL model.train() in the next step BEFORE any model param/gradient is updated, this must include optimizer.zero_grad( ).
This answer helps me a lot! I use the optimizer.zero_grad() before mode.train() by mistake. Now the problem is solved. Thanks!
@xiaoxiaolishan Hi, I encountered the same problem. Have you found the solution to this problem? Thanks!
Have you solved the problem? I run into the same problem here | https://discuss.pytorch.org/t/performance-highly-degraded-when-eval-is-activated-in-the-test-phase/3323 | CC-MAIN-2017-47 | refinedweb | 580 | 61.63 |
Java Types and Type Conversion (Casting)
In Java, there are primitive types: {short, int, double}. But there are also corresponding number classes, that wraps a class structure around these.
Technically, every variable and expression in Java is of some type.
Java data types are of two kinds: primitive and reference.
- Primitive types: byte, short, int, long, char, float, double.
- Reference types: class, interface, array.
You can convert one data type to another, by a operation
called “casting”. Converting from one type to another is necessary, because sometimes a function f accept type A, and your expression e has type B and you want to do
f(e). So, you need to convert your e to type A.
The general syntax to do casting is this:
(type) myExpression. For example, if “n” is a “int” and you want to cast it to “double”, do
(double) n.
In the following example,
java.lang.Math.pow() returns a “double”. It can be casted to “int” by including
(int) in front. (if this is removed, the code won't compile.)
import java.lang.Math; class T2 { public int square (int n) { return (int) java.lang.Math.pow(n,2); } } class T1 { public static void main(String[] arg) { T2 x1 = new T2(); double m =x1.square(3); System.out.println(m); } } | http://xahlee.info/java-a-day/casting.html | CC-MAIN-2016-22 | refinedweb | 216 | 68.16 |
XmInstallImage (3) - Linux Man Pages
XmInstallImage: A pixmap caching function that adds an image to the image cache
NAMEXmInstallImage --- A pixmap caching function that adds an image to the image cache
SYNOPSIS
#include <Xm/Xm.h> Boolean XmInstallImage( XImage * image, char * image_name);
DESCRIPTION.
- image
- Points to the image structure to be installed. The installation process does not make a local copy of the image. Therefore, the application should not destroy the image until it is uninstalled from the caching functions.
- image_name
- Specifies a string that the application uses to name the image. After installation, this name can be used in .Xdefaults for referencing the image. A local copy of the name is created by the image caching functions.
The image caching functions provide a set of eight preinstalled images. These names can be used within a .Xdefaults file for generating pixmaps for the resource for which they are provided.
RETURN
Returns True when successful; returns False if NULL image, NULL image_name, or duplicate image_name is used as a parameter value.
RELATED
XmUninstallImage(3), XmGetPixmap(3), and XmDestroyPixmap(3). | https://www.systutorials.com/docs/linux/man/3-XmInstallImage/ | CC-MAIN-2021-25 | refinedweb | 178 | 58.89 |
#include <archiver.h>
#include <archiver.h>
List of all members.
Definition at line 17 of file archiver.h.
C'tor.
Definition at line 26 of file archiver.cc.
References m_exit_str, m_signal_str, m_unknown_exit, m_unknown_signal, and TRY_nomem.
Get a verbose string for an exit code.
Definition at line 94 of file archiver.cc.
References m_exit_str, and m_unknown_exit.
Referenced by job_archiver::mf_do_chores(), and jobs_report::write_report().
Get a verbose string for a signal number.
Definition at line 103 of file archiver.cc.
References m_signal_str, and m_unknown_signal.
[private]
Definition at line 25 of file archiver.h.
Referenced by exit(), and rstat().
Definition at line 26 of file archiver.h.
Referenced by rstat(), and signal().
Definition at line 27 of file archiver.h.
Definition at line 28 of file archiver.h. | http://rvm.sourceforge.net/doxygen/0.90.3-beta/html/classrstat.html | CC-MAIN-2017-39 | refinedweb | 125 | 65.18 |
>>> dir(exec_code)
['__init__', '__str__', 'append_stmt', 'compile', 'dedent', 'execute', 'indent', 'p']
>>> eco = exec_code()
>>> eco.indent_increment = 4
>>> eco.append_stmt("for i in range(0,4):")
>>> eco.indent()
>>> eco.append_stmt("print 'Hi!!!! This is count: ', i")
>>> eco.p()
<exec_code instance> with indent-level 4 and code:
--------------------------------------------------------------
for i in range(0,4):
print 'Hi!!!! This is count: ', i
>>> eco.execute()
Hi!!!! This is count: 0
Hi!!!! This is count: 1
Hi!!!! This is count: 2
Hi!!!! This is count: 3
>>> eco.dedent()
>>> eco.append_stmt("print '---------- ALL DONE!!! ----------'")
>>> eco.exec_code_valid
0
>>> eco.compile()
>>> eco.exec_code_valid
1
>>> eco.p()
<exec_code instance> with indent-level 0 and code:
--------------------------------------------------------------
for i in range(0,4):
print 'Hi!!!! This is count: ', i
print '---------- ALL DONE!!! ----------'
>>> eco.execute()
Hi!!!! This is count: 0
Hi!!!! This is count: 1
Hi!!!! This is count: 2
Hi!!!! This is count: 3
---------- ALL DONE!!! ----------
In reality, my class doesn't do very much, but it may make automatic
code generation appear cleaner, if not done in many fewer statements.
The main reason I've posted the class is to generate discussion on the
topic, and get as much feedback as I can so I can improve my python
programming skills. I'm curious now about what code people are
generating on the fly this way, and how my class could be improved to
make the generation even easier. I didn't do this to fit any
particular need that I have, so I don't really know what would be
useful. Things I have been thinking about adding include:
- The ability to append one exec_code instance to another
using the syntax exec_code_instance1 + exec_code_instance2.
Basically this would just take exec_code_instance2, indent
the entire thing to the current indentation level of
exec_code_instance1, and append it, returning the result.
- The ability to optionally specify the namespace dictionaries
to use in the execute() command. Maybe even the ability to
bind these when a class instance is created using exec_code().
- Add some sequence-type functionality, such that the lines of
code in exec_string can be treated as a sequence of strings,
one line per "sequence item." This would allow modifying
inserted code, using slice operations, and change the
semantics of append_stmt, etc.
- The ability to save a code object to disk as a simple text
module. I could envision some sort of simple, *slow*
line-editor being implemented for the python command line
using a facility like this. It might improve on the current
situation for those without emacs or the readline package,
but I have trouble seriously contemplating extended use of
a line editor. Still, a possibility? Anyone interested?
- ???? Any other reasonable suggestions.
I would appreciate *any* comments on the code at all, especially with
regard to the namespace issues I discussed in the comments for the
execute() method. I'm still trying to figure python out, and I'm not
sure those are correct.
Thanks, Keith Amidon
-----------<snip>------------ exec_code.py ------------<snip>------------
# This class module is a first cut at creating a class to simplify the
# creation of code strings for execution by exec().
#
# by: Keith Amidon -- 2/27/94 -- Use this for whatever you want! :^)
# Usage: read the comments in the code below. I believe it is adequately
# commented.
class exec_code:
###### Data Members ######
#
# exec_string = the string of code that is to be executed.
# exec_code = compiled code from exec_string, to eliminate
# compile time if the exec-code object is to be
# frequently used.
# exec_code_valid = boolean that indicates if exec_code is in sync
# with exec_string.
# indent_level = current amount of indentation. Starts at zero,
# increase/decreases by indent_increment.
# indent_increment = amount to increase/decrease indent_level by.
# Defaults to 1 to make code string as short as
# possible. If you will be doing a lot of
# examination of exec_code objects using str(),
# you may want to set this to your favorite
# indentation level. Don't change this in the
# middle of adding code, as there is currently
# no way to expand/contract the indentation of
# previous lines.
###### Methods ######
# __init__ : Initializes the values of the data members when the
# class is first created
def __init__(self) :
self.exec_string = ""
self.exec_code = compile(self.exec_string,'<string>','exec')
self.exec_code_valid = 1
self.indent_level = 0
self.indent_increment = 1
# __str__ : Return a string representation of the object, for
# nice printing.
def __str__(self) :
return "<exec_code instance> with indent-level " \
+ `self.indent_level` + " and code:\n" \
+ "--------------------------------" \
+ "------------------------------\n" \
+ self.exec_string
# p : Since it is often useful to be able to look at the code
# that is generated interactively, this function provides
# a shorthand for "print str(some_exec_code_instance)", which
# gives a reasonable nice look at the contents of the
# exec_code object.
def p(self) :
print str(self)
# append_stmt : Add a statement at the end of exec_string, with
# the correct indentation. We don't recompile
# exec_string to exec_code after each append_stmt,
# because we want to keep statement insertion as
# inexpensive as possible. However, this makes it
# neccessary to compile the object before executing
# exec_code.
def append_stmt(self, stmt) :
self.exec_code_valid = 0
# I don't know how neccessary the following is, I used for to
# prevent the class from having to import any of the string
# routines. Probably this isn't a problem and performance code
# be improved by using the string functions.
for x in range(0,self.indent_level):
self.exec_string = self.exec_string + ' '
self.exec_string = self.exec_string + stmt + '\n'
# indent : Increase the level of indentation by one.
def indent(self) :
self.indent_level = self.indent_level + self.indent_increment
# dedent : Decrease the level of indentation by one.
def dedent(self) :
self.indent_level = self.indent_level - self.indent_increment
# compile : Compile exec_string into exec_code using the builtin
# compile function. Skip if already in sync.
def compile(self) :
if not self.exec_code_valid :
self.exec_code = compile(self.exec_string,'<string>','exec')
self.exec_code_valid = 1
# execute : Execute exec_code, compiling exec_string to exec_code if
# neccessary. Really, we could just exec exec_string becuase
# exec will do the compile, but this is a good way to keep
# exec_code and exec_string in sync, and reduces overhead if
# the object is executed repeatidly.
#
# NOTE: the symbol name spaces (n.s.) in use will be:
# local = n.s. of the execute() function
# global = global n.s. of the caller
# If it is neccessary to access the local n.s. of the
# caller, or to specify the name spaces within which the
# code segment will execute, simply exec the exec_code
# from within the caller with something like:
#
# some_exec_code_instance.compile()
# exec some_exec_code_instance.exec_code in global,local
#
# Alternatively, use exec_string instead, as exec will
# automatically compile the string. However, if you use
# exec_code, be sure to compile it first, otherwise you
# won't know if it is up to date.
def execute(self) :
if not self.exec_code_valid :
self.exec_code = compile(self.exec_string, '<string>','exec')
exec self.exec_code | http://www.python.org/search/hypermail/python-1994q1/0257.html | CC-MAIN-2013-20 | refinedweb | 1,106 | 50.73 |
import java.util.Set; 33 34 /** 35 * ListeningIOReactor represents an I/O reactor capable of listening for 36 * incoming connections on one or several ports. 37 * 38 * @since 4.0 39 */ 40 public interface ListeningIOReactor extends IOReactor { 41 42 /** 43 * Opens a new listener endpoint with the given socket address. Once 44 * the endpoint is fully initialized it starts accepting incoming 45 * connections and propagates I/O activity notifications to the I/O event 46 * dispatcher. 47 * <p> 48 * {@link ListenerEndpoint#waitFor()} can be used to wait for the 49 * listener to be come ready to accept incoming connections. 50 * <p> 51 * {@link ListenerEndpoint#close()} can be used to shut down 52 * the listener even before it is fully initialized. 53 * 54 * @param address the socket address to listen on. 55 * @return listener endpoint. 56 */ 57 ListenerEndpoint listen(SocketAddress address); 58 59 /** 60 * Suspends the I/O reactor preventing it from accepting new connections on 61 * all active endpoints. 62 * 63 * @throws IOException in case of an I/O error. 64 */ 65 void pause() 66 throws IOException; 67 68 /** 69 * Resumes the I/O reactor restoring its ability to accept incoming 70 * connections on all active endpoints. 71 * 72 * @throws IOException in case of an I/O error. 73 */ 74 void resume() 75 throws IOException; 76 77 /** 78 * Returns a set of endpoints for this I/O reactor. 79 * 80 * @return set of endpoints. 81 */ 82 Set<ListenerEndpoint> getEndpoints(); 83 84 } | http://hc.apache.org/httpcomponents-core-dev/httpcore-nio/xref/org/apache/http/nio/reactor/ListeningIOReactor.html | CC-MAIN-2016-44 | refinedweb | 241 | 56.15 |
Presence
Requirement: This guide expects that you have gone through the introductory guides and got a Phoenix application up and running.
Requirement: This guide expects that you have gone through the Channels guide.
Phoenix Presence is a feature which allows you to register process information on a topic and replicate it transparently across a cluster. It's a combination of both a server-side and client-side library which makes it simple to implement. A simple use-case would be showing which users are currently online in an application.
Phoenix Presence is special for a number of reasons. It has no single point of failure, no single source of truth, relies entirely on the standard library with no operational dependencies and self heals. This is all handled with a conflict-free replicated data type (CRDT) protocol.
To get started with Presence we'll first need to generate a presence module. We can do this with the
mix phx.gen.presence task:
$ mix phx.gen.presence * creating lib/hello_web/channels/presence.ex Add your new module to your supervision tree, in lib/hello/application.ex: children = [ ... HelloWeb.Presence, ] You're all set! See the Phoenix.Presence docs for more details:
If we open up the
lib/hello_web/channels/presence.ex file, we will see the following line:
use Phoenix.Presence, otp_app: :hello, pubsub_server: Hello.PubSub
This sets up the module for presence, defining the functions we require for tracking presences. As mentioned in the generator task, we should add this module to our supervision tree in
application.ex:
children = [ ... HelloWeb.Presence, ]
Next we will create a channel that Presence can communicate on. For this example we will create a
RoomChannel (see the channels guide for more details on this):
$ mix phx.gen.channel Room * creating lib/hello_web/channels/room_channel.ex * creating test/hello_web/channels/room_channel_test.exs Add the channel to your `lib/hello_web/channels/user_socket.ex` handler, for example: channel "room:lobby", HelloWeb.RoomChannel
and register it in
lib/hello_web/channels/user_socket.ex:
defmodule HelloWeb.UserSocket do use Phoenix.Socket channel "room:lobby", HelloWeb.RoomChannel end
We also need to change our connect function to take a
user_id from the params and assign it on the socket. In production you may want to use
Phoenix.Token if you have real users that are authenticated.
def connect(params, socket, _connect_info) do {:ok, assign(socket, :user_id, params["user_id"])} end
Next, we will create the channel that we'll communicate presence over. After a user joins we can push the list of presences down the channel and then track the connection. We can also provide a map of additional information to track.
Note that we provide the
user_id from the connection in order to uniquely identify the client. You can use whatever identifier you like, but you'll see how this is provided to the socket in the client-side example below.
To learn more about channels, read the channel documentation in the guide.
defmodule HelloWeb.RoomChannel do use Phoenix.Channel alias HelloWeb.Presence def join("room:lobby", _params, socket) do send(self(), :after_join) {:ok, socket} end def handle_info(:after_join, socket) do {:ok, _} = Presence.track(socket, socket.assigns.user_id, %{ online_at: inspect(System.system_time(:second)) }) push(socket, "presence_state", Presence.list(socket)) {:noreply, socket} end end
Finally we can use the client-side Presence library included in
phoenix.js to manage the state and presence diffs that come down the socket. It listens for the
"presence_state" and
"presence_diff" events and provides a simple callback for you to handle the events as they happen, with the
onSync callback.
The
onSync callback allows you to easily react to presence state changes, which most often results in re-rendering an updated list of active users. You can use the
list method to format and return each individual presence based on the needs of your application.
To iterate users, we use the
presences.list() function which accepts a callback. The callback will be called for each presence item with 2 arguments, the presence id and a list of metas (one for each presence for that presence id). We use this to display the users and the number of devices they are online with.
We can see presence working by adding the following to
assets/js/app.js:
import {Socket, Presence} from "phoenix" let socket = new Socket("/socket", { params: {user_id: window.location.search.split("=")[1]} }) let channel = socket.channel("room:lobby", {}) let presence = new Presence(channel) function renderOnlineUsers(presence) { let response = "" presence.list((id, {metas: [first, ...rest]}) => { let count = rest.length + 1 response += `<br>${id} (count: ${count})</br>` }) document.querySelector("main[role=main]").innerHTML = response } socket.connect() presence.onSync(() => renderOnlineUsers(presence)) channel.join()
We can ensure this is working by opening 3 browser tabs. If we navigate to on two browser tabs and then we should see:
Alice (count: 2) Bob (count: 1)
If we close one of the Alice tabs, then the count should decrease to 1. If we close another tab, the user should disappear from the list entirely. | https://hexdocs.pm/phoenix/presence.html | CC-MAIN-2021-04 | refinedweb | 831 | 51.75 |
Hi all, long time lurker and first time poster. I'm writing a Python program which does analysis on mp3 files, so I'd like to read in the mp3 data as a numpy array. I'm using pymad, which seems stable and works well. When you read in a frame of data from pymad, it gets returned as a buffer of unicode hex values and characters, eg,
'\x86\x01\x02\x01\xe4\x01@\x01\xb4\x00'
The format of these values is Left channel MSB, LSB, Right channel MSB, LSB, ... and so on. So, to convert this into a numpy array, here's my function:
def bufToNumpy( inBuf ): bufLength = len(inBuf) outBuf = np.zeros(bufLength/2) for i in range(bufLength/2): outBuf[i] = struct.unpack('h', inBuf[2*i] + inBuf[2*i+1])[0] return outBuf
As you can see, I am using struct's unpack function to grab each pair of MSB, LSB and converting it into a 16 bit int, which is stored in a numpy array. However, because I'm doing this per-number, it takes a LONG time (for a typical song I call unpack about 10 million times). Is there a way I can vectorize this? In other words, I'd like to just call struct.unpack once and get out an array (of some kind) of 16 bit integers. Thanks for any tips!
-Colin | https://www.daniweb.com/programming/software-development/threads/316107/fast-way-to-convert-a-buffer-of-unicode-values-to-a-numpy-array | CC-MAIN-2018-22 | refinedweb | 232 | 72.76 |
VIPS from C++
Using VIPS — How to use the VIPS library from C++
Introduction
VIPS comes with a convenient C++ API. It is a very thin wrapper over the C API and adds automatic reference counting, exceptions, operator overloads, and automatic constant expansion. You can drop down to the C API at any point, so all the C API docs also work for C++.
/* compile with: * g++ -g -Wall try.cc `pkg-config vips-cpp --cflags --libs` */ #include <vips/vips8> using namespace vips; int main( int argc, char **argv ) { GOptionContext *context; GOptionGroup *main_group; GError *error = NULL; if( VIPS_INIT( argv[0] ) ) vips_error_exit( NULL ); context = g_option_context_new( "" ); main_group = g_option_group_new( NULL, NULL, NULL, NULL, NULL ); g_option_context_set_main_group( context, main_group ); g_option_context_add_group( context, vips_get_option_group() ); if( !g_option_context_parse( context, &argc, &argv, &error ) ) { if( error ) { fprintf( stderr, "%s\n", error->message ); g_error_free( error ); } vips_error_exit( NULL ); } VImage in = VImage::new_from_file( argv[1], VImage::option()-> set( "access", VIPS_ACCESS_SEQUENTIAL_UNBUFFERED ) ); double avg = in.avg(); printf( "avg = %g\n", avg ); printf( "width = %d\n", in.width() ); VImage in = VImage::new_from_file( argv[1], VImage::option()-> set( "access", VIPS_ACCESS_SEQUENTIAL_UNBUFFERED ) ); VImage out = in.embed( 10, 10, 1000, 1000, VImage::option()-> set( "extend", "background" )-> set( "background", 128 ) ); out.write_to_file( argv[2] ); vips_shutdown(); return( 0 ); }
Everything before
VImage in = VImage::.. is exactly
as the C API. This boilerplate gives the example a set of standard
command-line flags.
This line is the C++ equivalent of
vips_image_new_from_file(). It works
in the same way, the differences being:
VImagelifetime is managed automatically, like a smart pointer. You don't need to call
g_object_unref().
Instead of using varargs and a
NULL-terminated option list, this function takes an optional
VOptionpointer. This gives a list of name / value pairs for optional arguments to the function.
In this case we request unbuffered IO for the image, meaning, we expect to do a single top-to-bottom scan of the image and do not need it to be decompressed entirely. You can use the C enum name, as is done in this case, or use a string and have the string looked up. See below.
The function will delete the
VOptionpointer for us when it's finished with it.
Instead of returning
NULLon error, this constructor will raise a
VErrorexception.
There are a series of similar constructors which parallel the other
constructors in the C API, see VImage::
new_from_memory(),
VImage::
new_from_buffer(), and VImage::
new_matrix(). There's also
VImage::
new_memory() and VImage::
new_temp_file(), which when written to
with VImage::
write() will create whole images on memory or on disc.
The next line finds the average pixel value, it's the equivalent of the
vips_avg() function. The differences from the C API are:
VImage::
avg()is a member function: the
thisparameter is the first (the only, in this case) input image.
The function returns the first output parameter, in this case the average pixel value. Other return values are via pointer arguments, as in the C API.
Like VImage::
new_from_file(), function raises the
VErrorexception on error.
Like VImage::
new_from_file(), extra arguments are passed via an optional
VOptionparameter. There are none in this case, so the function brackets can be left empty.
All other operations follow the same pattern, for example the C API call
vips_add():
int vips_add( VipsImage *left, VipsImage *right, VipsImage **out, ... );
appears in C++ as:
VImage VImage::add( VImage right, VOption *options = 0 );
The next line uses VImage::
width() to get the image width in pixels.
There are similar functions paralleling
vips_image_get_format() and
friends. Use VImage::
set() to set metadata fields, VImage::
get_int() and
c. to fetch metadata.
Next we reload the image. The VImage::
avg() will have scanned the image
and reached the end of the file, we need to scan again for the next
operation. If we'd selected random access mode (the default) in the
original VImage::
new_from_file(), we would not need to reload.
The next line runs
vips_embed() with two optional parameters. The first
sets the value to an enum (here we use a string to set the value, it'll
be looked up in the list of possible enum values, or you can use the
symbols from the C API), the
second sets the value to an
int. The
"background"
parameter is actually a VipsArrayDouble: if you pass an
int instead, it will be automatically converted to a
one-element array for you. You can pass a
std::vector<double> too: the utility function
VImage::
to_vectorv() is a convenient way to make one.
Finally, VImage::
write_to_file() will write the new image to the
filesystem. You can add a VOption as a final parameter and set options
for the writer if you wish. Again, the operation will throw a VError
exception on error. The other writers from the C API are also present:
you can write to a memory array, to a formatted image in memory, or to
another image.
The API docs have a handy table of all vips operations, if you want to find out how to do something, try searching that.
Automatic constant expansion
The C++ API will automatically turn constants into images in some cases. For example, you can join two images together bandwise (the bandwise join of two RGB images would be a six-band image) with:
VImage rgb = ...; VImage six_band = rgb.bandjoin( rgb );
You can also bandjoin a constant, for example:
VImage rgb_with_alpha = rgb.bandjoin( 255 );
Will add an extra band to an image, with every element in the new band having the value 255. This is quite a general feature. You can use a constant in most places where you can use an image and it will be converted. For example:
VImage a = (a < 128).ifthenelse( 128, a );
Will set every band element of
a less than 128 to 128.
The C++ API includes the usual range of arithmetic operator overloads. You can mix constants, vectors and images freely.
The API overloads
[] to be
vips_extract_band(). You can
write:
VImage xyz = VImage::xyz( 256, 256 ) - VImage::to_vectorv( 2, 128.0, 128.0 ); VImage mask = (xyz[0].pow( 2 ) + xyz[1].pow( 2 )).pow( 0.5 ) < 100;
to make a circular mask, for example.
The API overloads
() to be
vips_getpoint(). You can
write:
VImage xyz = VImage::xyz( 256, 256 ) - VImage::to_vectorv( 2, 128.0, 128.0 ); // this will have the value [0, 0] std::vector<double> point = xyz(128, 128);
Enum expansion
VIPS operations which implement several functions with a controlling
enum, such as
vips_math(), are expanded to a set of member functions
named after the enum. For example, the C function:
int vips_math( VipsImage *in, VipsImage **out, VipsOperationMath math, ... );
where VipsOperationMath has the member VIPS_OPERATION_MATH_SIN, has a
C convenience function
vips_sin():
int vips_sin( VipsImage *in, VipsImage **out, ... );
and a C++ member function VImage::
sin():
VImage VImage::sin( VOption *options = 0 );
Image metadata
VIPS images can have a lot of metadata attached to them, giving things
like ICC profiles, EXIF data, and so on. You can use the command-line
program
vipsheader with the
-a flag to list
all the fields.
You can read metadata items with the member functions
,
get_int()
,
get_double()
and
get_string()
. Use
get_blob()
to call
get_typeof()
vips_image_get_typeof() and read the
type of an item. This will return 0 for undefined fields.
const char *VImage::get_string( const char *field ) throw( VError );
You can use the
family of overloaded members to set
metadata, for example:
set()
void VImage::set( const char *field, const char *value );
You can use these functions to manipulate exif metadata, for example:
VImage im = VImage::new_from_file( "x.jpg" ) int orientation = atoi( im.get_string( "exif-ifd0-Orientation" ) ); im.set( "exif-ifd0-Orientation", "2" ); im.write_to_file( "y.jpg" );
Extending the C++ interface
The C++ interface comes in two parts. First,
VImage8.h
defines a simple layer over GObject for automatic reference counting,
then a generic way to call any vips8 operation with VImage::
call(),
then a few convenience functions, then a set of overloads.
The member function for each operation, for example VImage::
add(), is
generated by a small Python program called
gen-operators.py,
and its companion,
gen-operators-h.py to generate the
headers. If you write a new VIPS operator, you'll need to rerun these
programs to make the new member function.
You can write the wrapper yourself, of course, they are very simple.
The one for VImage::
add() looks like this:
VImage VImage::add(VImage right, VOption *options) { VImage out; call("add" , (options ? options : VImage::option()) -> set("out", &out) -> set("left", *this) -> set("right", right)); return out; }
Where VImage::
call() is the generic call-a-vips8-operation function. | http://www.manpagez.com/html/libvips/libvips-8.5.9/using-from-cpp.php | CC-MAIN-2018-30 | refinedweb | 1,408 | 55.84 |
Friday the thirteenth! What has gone wrong so far today? Keeping my fingers crossed ...
We recently discussed the issue of determining the wall area adjacent to a room and mentioned the fact that the simplest way to calculate such an overlapping area might be the use of a free-standing library for performing Boolean set operations on two-dimensional polygons. As said, there are many such libraries available, as you can see by googling for "polygon boolean" or by looking at the Wikipedia article on Boolean operations on polygons. I suggested possibly using the Generic Polygon Clipper (gpc) and its C# wrapper GpcWrapper. Now my colleague Adam Nagy – the pronunciation is 'nadj', according to Adam, and an interesting topic in itself – went ahead and wrote a sample application demonstrating the use of this tool in a Revit add-in.
Adam's sample application is named GpcNET. It defines an external command within the namespace GpcNET. It also includes the GpcWrapper code in the same namespace, so that all its classes are immediately available to the command class.
You need to select two floors before running the command. If not, it will prompt you to do so and abort. The two floors are used to define a two-dimensional polygon each. The intersection of the two polygons is computed. If the result is a valid polygon, a new third floor is created. It uses the intersection result to define its profile CurveArray, and the same floor type and level as the first selected floor.
Here is the code that extracts the profile from a selected floor and creates a GPC polygon object from it:
Polygon getPolygon( Floor floor ) { Options geomOptions = app.Create.NewGeometryOptions(); GeoElement elem = floor.get_Geometry( geomOptions ); List<Vertex> vertices = new List<Vertex>(); foreach( object obj in elem.Objects ) { Solid, p.Y ) ); } } break; } } VertexList vertexList = new VertexList(); vertexList.NofVertices = vertices.Count; vertexList.Vertex = vertices.ToArray(); Polygon poly = new Polygon(); poly.AddContour( vertexList, false ); return poly; }
Here is the code for the Execute method of the command, i.e. the command mainline:
CmdResult rc = CmdResult.Failed; app = commandData.Application; doc = app.ActiveDocument; Floor[] floors = new Floor[2] { null, null }; // get the first 2 floors of the selection foreach( RvtElement e in doc.Selection.Elements ) { if( null == floors[0] ) { floors[0] = e as Floor; } else if( null == floors[1] ) { floors[1] = e as Floor; } else { break; } } // if the selction did not contain two floors, return if( null == floors[0] || null == floors[1] ) { MessageBox.Show( "Please select two floors before" + " running this command.", "GpcNET" ); } else { // get the intersection Polygon poly1 = getPolygon( floors[0] ); Polygon poly2 = getPolygon( floors[1] ); Polygon poly3 = poly1.Clip( GpcOperation.Intersection, poly2 ); // if it looks like a valid polygon, create a new floor if( 0 < poly3.NofContours ) { CurveArray curves = app.Create.NewCurveArray(); VertexList v = poly3.Contour[0]; int i, j, n = v.NofVertices; for( i = 0; i < n; ++i ) { j = ( i + 1 ) % n; Vertex p = v.Vertex[i]; Vertex q = v.Vertex[j]; curves.Append( app.Create.NewLineBound( app.Create.NewXYZ( p.X, p.Y, 0 ), app.Create.NewXYZ( q.X, q.Y, 0 ) ) ); } doc.Create.NewFloor( curves, floors[0].FloorType, floors[0].Level, false ); rc = CmdResult.Succeeded; } } return rc;
A short readme file and sample Revit.ini snippet are included with the project. Here are the steps to rebuild and install it:
- In the Visual Studio project, adjust the Properties > Build > Output Path to point to the Revit.exe folder, e.g. "C:\Program Files\Revit Architecture 2009\Program".
- Compile the project.
- Copy the gpc.dll file from the project folder to the Revit.exe folder.
- Adjust your Revit.ini file, for instance using the text in the sample Revit.ini file provided.
Please note that the GPC library is only free to use for non-commercial use. Please contact the vendor if you are thinking of using it in a commercial product.
The zip file includes a sample project named floors.rvt containing two floors. Here is what they look like before running the command:
Here is the third floor created using the profile resulting from the intersection of the two, which have been temporarily half-toned:
To apply these results to the problem we started the discussion with, the wall area adjacent to a given room, we would need to transform the vertical wall and room faces into 2D, as described in the discussion on polygon transformation.
Here is the complete Visual Studio GpcNET solution. | http://thebuildingcoder.typepad.com/blog/2009/02/boolean-operations-for-2d-polygons.html | CC-MAIN-2014-15 | refinedweb | 738 | 59.7 |
Gaming: Battle on the High Seas, Part 2By Jeff Friesen
Battle on the High Seas
- Gaming: Battle on the High Seas, Part 1
- Gaming: Battle on the High Seas, Part 2
- Gaming: Battle on the High Seas, Part 3
- Gaming: Battle on the High Seas, Part 4
- Gaming: Battle on the High Seas, Part 5
Last week, I introduced an HTML5 game known as SeaBattle, as a demonstration of what you can accomplish with HTML5’s Audio, Canvas, and Web Storage APIs. I then showed you how to embed this game in a Web page, and overviewed its architecture. This article starts to dig into this architecture by focusing on initialization. It explores the
SeaBattle object’s
init(width, height) and related functions.
Initializing SeaBattle
Listing 1 presents the implementation of the
init(width, height) function.
init: function(width, height) { var canvas = $("<canvas width='"+width+"' height='"+height+"'></canvas>"); canvas.appendTo("body"); SeaBattle.ctx = canvas.get(0).getContext("2d"); SeaBattle.ctx.font = "30px Arial"; SeaBattle.ctx.textAlign = "center"; var seed = 5*height/6; SeaBattle.hillTops = new Array(); for (var i = 0; i < width; i++) { SeaBattle.hillTops.push(seed); var x = SeaBattle.rnd(seed); if (x < seed/4) { if (--seed < 2*height/3) seed = 2*height/3; } else if (x > 3*seed/4) { if (++seed > height-1) seed = height-1; } } SeaBattle.width = width; SeaBattle.height = height; SeaBattle.dc = new Array(SeaBattle.MAX_DC); SeaBattle.torp = new Array(SeaBattle.MAX_TORP); SeaBattle.explosion = null; SeaBattle.msg = ""; SeaBattle.score = 0; SeaBattle.hiScore = 0; if (SeaBattle.supports_html5_storage()) { var temp = localStorage.getItem("hiScore"); if (temp != undefined) SeaBattle.hiScore = temp; } SeaBattle.lives = 4; window.keydown = {}; function keyName(event) { return jQuery.hotkeys.specialKeys[event.which] || String.fromCharCode(event.which).toLowerCase(); } $(document).bind("keydown", function(event) { keydown[keyName(event)] = true; }); $(document).bind("keyup", function(event) { keydown[keyName(event)] = false; }); SeaBattle.imgTitle = new Image(); SeaBattle.imgTitle.src = "images/title.png"; SeaBattle.imgSky = new Image(); SeaBattle.imgSky.src = "images/sky.png"; SeaBattle.imgMoon = new Image(); SeaBattle.imgMoon.src = "images/moon.png"; SeaBattle.imgShipLeft = new Image(); SeaBattle.imgShipLeft.src = "images/shipLeft.png"; SeaBattle.imgShipRight = new Image(); SeaBattle.imgShipRight.src = "images/shipRight.png"; SeaBattle.imgSubLeft = new Image(); SeaBattle.imgSubLeft.src = "images/subLeft.png"; SeaBattle.imgSubRight = new Image(); SeaBattle.imgSubRight.src = "images/subRight.png"; SeaBattle.imgExplosion = new Array(); for (var i = 0; i < 17; i++) { var image = new Image(); image.src = "images/ex"+i+".png"; SeaBattle.imgExplosion.push(image); } SeaBattle.imgTorpedo = new Image(); SeaBattle.imgTorpedo.src = "images/torpedo.png"; SeaBattle.imgDC = new Image(); SeaBattle.imgDC.src = "images/dc.png"; SeaBattle.audBombLoaded = false; SeaBattle.audBomb = document.createElement("audio"); SeaBattle.audBomb.onloadeddata = new function() { SeaBattle.audBombLoaded = true; }; SeaBattle.audBomb.src = (navigator.userAgent.indexOf("MSIE") == -1) ? "audio/bomb.wav" : "audio/bomb.mp3"; SeaBattle.state = SeaBattle.STATE_INIT; }
Listing 1: Game initialization involves canvas and undersea terrain creation/initialization, hotkey binding, game resource loading, and more.
Listing 1 first uses jQuery to create a
<canvas> element node, and then install it in the browser’s Document Object Model (DOM) tree. It accomplishes this task as follows:
- Invoke the
jQuery(html)constructor to parse the
htmlstring, create DOM nodes from the parsed HTML, and create/return a
jQueryobject that refers to these nodes. Listing 1 creates a single
<canvas>DOM node.
- Invoke
appendTo("body")on this new
jQueryobject to attach the parsed HTML’s DOM nodes to the Web page’s
<body>element node. Listing 1 attaches the
<canvas>node to the page’s
<body>node.
The canvas’s context is obtained via
canvas.get(0).getContext("2d") and assigned to
SeaBattle‘s
ctx property. Next, the 2D drawing context’s
font and
textAlign properties are initialized to specify that text is to be drawn in the Arial font with a 30-pixel height, and to make it easy to horizontally center the text.
Listing 1 proceeds to generate undersea terrain by randomly choosing the top locations of hills. The leftmost hill top is at the midpoint of the bottom third of the canvas. Each hill top to the right is relative to the previous hill top.
Continuing, the
width and
height values passed to
init(width, height) are saved in same-named
SeaBattle properties so that they can be accessed from other functions. Additionally, the following
SeaBattle properties are initialized:
dcis initialized to an array that will store at most
MAX_DCdepth charge objects.
torpis initialized to an array that will store at most
MAX_TORPtorpedo objects.
explosionis initialized to
null. The
update()function tests this property to find out if an explosion is in progress. When an explosion is occurring,
explosionis assigned a reference to an explosion object.
msgis initialized to the empty string. When the ship or submarine wins, a suitable message is assigned to this property, for subsequent display in the
draw()function.
scoreis initialized to zero and reflects the player’s current score. This score appears in the upper-left corner of the canvas.
hiScoreis initialized to zero and reflects the player’s highest previous score. If the current browser supports the local aspect of HTML5 Web Storage, and if this score was previously saved,
hiScoreis set to the saved value. The high score appears in parentheses after the current score.
livesis initialized to four and reflects the total number of destroyer lives that can be lived out before the game ends. This count decrements by one each time the destroyer is destroyed.
Games that involve keyboard input typically recognize hotkeys, which are keys that trigger various operations when pressed. Also, each operation usually repeats while its hotkey is held down. For example, an object keeps moving left until the left arrow key is released.
Differences in how browsers interpret a key event object’s
keyCode and
charCode properties along with other factors make it challenging to implement your own logic for responding to hotkeys. However, this task needn’t be too difficult to accomplish, as the following steps reveal:
- Attach key down and up event listeners to the canvas, as in
canvas.onkeydown = keyDown;and
canvas.onkeydown = keyUp;.
keyDownand
keyUpidentify functions that respond to key down and up events, respectively.
- Create an initially empty associative array and assign it to the
windowobject, as in
window.keydown = {}. Each entry’s key will be the name of a key that has been pressed, and its value will be true when the key is down or false when the key is up.
- For each of
keyDown()and
keyUp(), invoke a function that returns the name of the key, which is either a character key or a non-character (a special) key. Then, use the result as an index into the
keydownarray. For
keyDown(), assign true to this array entry. For
keyUp(), assign false instead.
Implementing this solution can be bothersome. For example,
charCode is always undefined in Opera. Why not let jQuery and the jQuery HotKeys plugin handle most of this work for you?
jQuery offers a powerful binding capability that makes it easy to register event-handling functions. Furthermore, the HotKeys plugin facilitates returning the name of a character or special key. Listing 1 leverages these capabilities to install key event handling as previously discussed.
Listing 1 now starts to load image resources, which are stored in the
images directory, by instantiating the
Image object and assigning the location and name of the image to the object’s
src property. It also starts loading an audio resource, which is stored in the
audio directory. Unlike in other browsers, Safari doesn’t provide an
Audio object. To ensure consistent cross-browser behavior,
document.createElement("audio") is used to create an equivalent object.
When an image finishes loading, the
Image object assigns true to its
complete property. To detect that an audio file has finished loading, an
onloadeddata handler function that assigns true to
SeaBattle‘s
audBombLoaded property is assigned to the “
Audio” object.
Except for Internet Explorer, all browsers mentioned in the first part of this series support the WAV format. Instead, Internet Explorer supports MP3. Listing 1 detects whether or not the current browser is Internet Explorer before choosing the proper audio file to load. The expression
navigator.userAgent.indexOf("MSIE") returns a value other than -1 when the current browser is Internet Explorer. This fact helps Listing 1 choose between
audio/bomb.wav and
audio/bomb.mp3, which is assigned to the “
Audio” object’s
src property.
Listing 1’s final task is to add a
state property to the
SeaBattle object and assign
STATE_INIT to this property. This state results in the canvas presenting a centered
Initializing... message until all game resources have finished loading.
Obtaining Random Integers
The
init(width, height) function relies on
SeaBattle‘s
rnd(limit) function to return random integers so that it can generate terrain. Listing 2 presents
rnd(limit)‘s implementation.
rnd: function(limit) { return (Math.random()*limit)|0; }
Listing 2: Bitwise operators cause JavaScript to convert floating-point numbers to integers.
Listing 2 returns a randomly selected integer from zero through
limit - 1. Because an integer result is desired, and because
Math.random()*limit returns a number with a fraction,
|0 is used to truncate the result to an integer. To learn more about JavaScript’s conversion to integer capability, check out the Javascript Type-Conversion FAQ. Specifically, read the FAQ’s ToInt32 section to learn about a JavaScript implementation’s
ToInt32 function.
Detecting HTML5 Local Storage
The
init(width, height) function also relies on
SeaBattle‘s
supports_html5_storage() function to detect the local aspect of Web storage. Listing 3 presents
supports_html5_storage()‘s implementation.
supports_html5_storage: function() { try { return 'localStorage' in window && window['localStorage'] !== null && window['localStorage'] !== undefined; } catch (e) { return false; } }
Listing 3: Older versions of Firefox raise an exception when cookies are disabled.
Listing 3 detects support for the local aspect of Web storage by checking the global
window object for the presence of a
localStorage property. When this property exists and isn’t
null or
undefined, this function returns true; otherwise, it returns false.
Conclusion
The
init(width, height) function works with the
rnd(limit) and
supports_html5_storage() functions to properly initialize the
SeaBattle object. The next step in understanding the SeaBattle gaming experience is to explore the
update() function, which is the subject of the third part in this series. Next Friday, you’ll also learn how the ship object is implemented.
No Reader comments | https://www.sitepoint.com/gaming-battle-on-the-high-seas-part-2/ | CC-MAIN-2016-44 | refinedweb | 1,705 | 50.63 |
It is often useful to be able to relate datasets with their real-world context. You can plot geographic data just like any other type of data, as in the Texas Unemployment example, but Bokeh also Bokeh provides several specialized mechanisms for plotting data in geographic coordinates:
GMapPlot: Bokeh Plots on top of Google Maps
TileSource, especially WMTSTileSource: allows data to be overlaid on data from any map tile server, including Google Maps, Stamen, MapQuest, OpenStreetMap, ESRI, and custom servers.
GeoJSONDataSource: Allows reading data in GeoJSON format for use with Bokeh plots and glyphs, similar to
ColumnDataSource.
WTMS is the most common web standard for tiled map data, i.e. maps supplied as standard-sized image patches from which the overall map can be constructed at a given zoom level. WTMS uses Web Mercator format, measuring distances from Greenwich, England as meters north and meters west, which is easy to compute but does distort the global shape.
First let's create an empty Bokeh plot covering the USA, with bounds specified in meters:
from bokeh.plotting import figure from bokeh.models import WMTSTileSource # web mercator coordinates USA = x_range,y_range = ((-13884029,-7453304), (2698291,6455972)) p = figure(tools='pan, wheel_zoom', x_range=x_range, y_range=y_range) p.axis.visible = False
A few WTMS tile sources are already defined in
bokeh.tile_providers, but here we'll show how to specify the interface using a format string showing Bokeh how to request a tile with the required zoom, x, and y values from a given tile provider:
url = '{Z}/{X}/{Y}.png' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" p.add_tile(WMTSTileSource(url=url, attribution=attribution))
If you show the figure, you can then use the wheel zoom and pan tools to navigate over any zoom level, and Bokeh will request the appropriate tiles from the server and insert them at the correct locations in the plot:
show(p)
That's all it takes to put map data into your plot! Of course, you'll usually want to show other data as well, or you could just use the tile server's own web address. You can now add anything you would normally use in a Bokeh plot, as long as you can obtain coordinates for it in Web Mercator format. For example:
import pandas as pd import numpy as np def wgs84_to_web_mercator(df, lon="lon", lat="lat"): """Converts decimal longitude/latitude to Web Mercator format""" k = 6378137 df["x"] = df[lon] * (k * np.pi/180.0) df["y"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k return df df = pd.DataFrame(dict(name=["Austin", "NYC"], lon=[-97.7431,-74.0059], lat=[30.2672,40.7128])) wgs84_to_web_mercator(df)
p.circle(x=df['x'], y=df['y'], fill_color='orange', size=10) show(p)
# EXERCISE: find some data in lat, lon (e.g. at), # import it into a dataframe or data source, and add it on the map above. | https://nbviewer.jupyter.org/github/bokeh/bokeh-notebooks/blob/master/tutorial/09%20-%20Geographic%20Plots.ipynb | CC-MAIN-2018-13 | refinedweb | 492 | 62.17 |
#include <mlVector3.h>
Definition at line 65 of file mlVector3.h.
A typedef to "export" the type of components.
Reimplemented from ml::FloatingPointVector< DT, 3, Vector3DataContainer< DT > >.
Definition at line 71 of file mlVector3.h.
Default and value constructor.
Set all entries to a user given value. value is the init value for all entries. 0 is the default value.
Definition at line 79 of file mlVector3.h.
Copy constructor from FloatingPointVector.
This allows the usage of SclarVectorTemplate objects of the same DT in operators using the Tvec3, because the FloatingPointVector objects can implicitly be cast.
Definition at line 87 of file mlVector3.h.
Constructor building the vector x (first entry), y (second entry) and z (third entry).
Definition at line 94 of file mlVector3.h.
Build a Tvec3 from a Tvec2 and a scalar. Set third entry to user given value z.
Definition at line 104 of file mlVector3.h.
If normalize is true then the first three components are divided by the last one to implement a homogeneous cast. In that case it is up to the caller to avoid a division by zero. If normalize if false then the first three components are taken unchanged.
Definition at line 118 of file mlVector3.h.
axis specifies component to be thrown away. All other components are copied sequentially. If axis is not within [0,3] then the last component is thrown away.
Definition at line 153 of file mlVector3.h.
Build a homogeneous Tvec4 point from *this and return it, i.e.
leave all components unchanged and set the fourth component to 1.
Definition at line 228 of file mlVector3.h.
Referenced by ml::operator*(), and ml::Tmat4< MLdouble >::transformPoint().
Build a homogeneous Tvec4 vector from *this and return it, i.e.
leave all components unchanged and set the fourth component to 0.
Definition at line 219 of file mlVector3.h.
Set all components to the passed values.
Definition at line 183 of file mlVector3.h.
Divide all vector components by its last component and return it as Tvec3 which then has a 1 as last component.
It is useful to scale the vector from homogeneous space to normal space. It's up to the caller to avoid a division by zero if last component is 0.
Definition at line 196 of file mlVector3.h.
Definition at line 240 of file mlVector3.h. | http://www.mevislab.de/fileadmin/docs/current/MeVisLab/Resources/Documentation/Publish/SDK/ToolBoxReference/classml_1_1Tvec3.html | crawl-003 | refinedweb | 394 | 61.73 |
import a form.Asked by waldson on November 16, 2014 at 06:23 PM
Dear Sirs,
I'm not able to regenerate this html script like a form
<script type="text/javascript" src=""></script>
when I use import form option from a web page,
It does the operation, but jotform transforms it in a wronged way not able to modify it.
Note content formisc.html contains
<script type="text/javascript" src=""></script>
Thks.
- JotForm Support
Hello waldson,
I am not sure if I have understood your question correctly.
Do you want to import the above form. Please be noted that to be able to import a form, you should use its direct URL. The code above you have mentioned is the form's embed code and not direct URL.
Please use the following URL to clone this form in your account :
Hope this helps.
Do get back to us if you have any questions.
Thank you!
It took a time but at the end It has solved.
Thank you!
- JotForm Support
Hello waldson,
You are welcome.
I am glad to know that you were able to clone your form/
Do get back to us if you have any questions.
Thank you!
- | https://www.jotform.com/answers/460101-Not-able-to-import-a-form- | CC-MAIN-2017-34 | refinedweb | 201 | 82.04 |
Write a C++ program that asks the user to enter an integer n followed by n numbers. The program will use 2 stacks to enter the numbers entered by the user. In every iteration the program will balance the total of the numbers stored in every stack. For example, if the user already entered 10 (the program stores this value in stack 1) and 23.5 (the program stores this value in stack 2) and then enters the value 4.7 then the program will store this value in stack 1 since 10<23.5. If the user enters 12.3, then the program will store it in stack 1 since the total in stack 1 is 14.7 (10+4.7) and 14.7<23.5. If the user enter 7, then the program will store this value in stack 2 since the total in stack 1 is 27 (14.7+12.3) and 27>23.5.
At the end, the program will display on the screen the content of every stack.
i try this
#include<iostream> #include<stack> using namespace std; int main() { int n ,m1,m2; cout<<"Enter an integer:"; cin>>n; stack<double> q; stack<double>w; for( int i=0;i<n;i++) { cin>>m1; q.push(m1); } for( int i=0;i<n;i++) { q.push(m1); q.pop(); } for( int j=0;j<n;j++) { cin>>m2; w.push(m2); } for( int j=0;j<n;j++) { w.push(m2); w.pop(); } double k=q.front(); while( !q.empty()) {if(q.front()>m2) q.top( ); q.pop(); cout<<"The content of stack 1 is :"<<q.top()<endl; } cout<<endl; cout<<"The content of stack 2 is :"<<w<<endl; system("pause"); return 0; } | https://www.daniweb.com/programming/software-development/threads/420885/data-structure-stack | CC-MAIN-2021-25 | refinedweb | 289 | 76.52 |
30 June 2010 22:44 [Source: ICIS news]
WASHINGTON (ICIS news)--US bioplastic producer NatureWorks will select a site for its second polylactic acid (PLA) plastic facility in early 2011, a company official said on Wednesday.
NatureWorks is looking at Europe, Asia Pacific and ?xml:namespace>
The planned facility will have a capacity of 140,000 tonnes/year and is projected to come online between 2013 and 2014.
The company’s existing PLA production plant in
“The selection of our new site will depend on feedstock availability, end market access and market incentives,” said Peter Clysdale, chief marketing officer for NatureWorks.
He spoke at the World Congress on Industrial Biotech and Bioprocessing, sponsored by the Biotechnology Industry Organization (BIO).
“Despite 2009 being a difficult year, we were still able to grow at 10% rate,” Clysdale said.
“Long term, we continue to see global growth for bioplastics demand between 30% and 40% year on year,” he added.
NatureWorks’ Ingeo bioplastic brand already is on a price par with petroleum-based polypropylene (PP) and polystyrene (PS), Clysdale said.
NatureWorks is based in
The BIO congress ends | http://www.icis.com/Articles/2010/06/30/9372693/natureworks-to-select-new-bioplastic-plant-site-in-2011.html | CC-MAIN-2014-41 | refinedweb | 184 | 51.48 |
What can cause this SIGSEGV error?
I received a crash log that I cannot explain. I have searched around and it appears that the SIGSEGV has something to do with memory. But in my case there is nothing of my own code except for the main.m in the stacktrace. Also it doesn't seem to symbolicate any of the system libraries.
The crash so far only happened on one iPhone. On other phones I haven't been able to reproduce it. Right now I'm completely stuck and don't know where to continue so if anyone has seen something like this before it would be good to hear their problem and resolution.
The crash log:
Incident Identifier: TODO CrashReporter Key: TODO Hardware Model: iPhone4,1 OS Version: iPhone OS 6.1.3 (10B329) Report Version: 104 Exception Type: SIGSEGV Exception Codes: SEGV_ACCERR at 0x41fd5903 Crashed Thread: 0 Thread 0 Crashed: 0 libobjc.A.dylib 0x3b0b9564 0x3b0b6000 + 13668 1 libobjc.A.dylib 0x3b0bb1d7 0x3b0b6000 + 20951 2 CoreFoundation 0x33396605 0x332d4000 + 796165 3 CoreFoundation 0x3339635d 0x332d4000 + 795485 4 libobjc.A.dylib 0x3b0bea65 0x3b0b6000 + 35429 5 libc++abi.dylib 0x3ab0b07b 0x3ab0a000 + 4219 6 libc++abi.dylib 0x3ab0b114 0x3ab0a000 + 4372 7 libc++abi.dylib 0x3ab0c599 0x3ab0a000 + 9625 8 libobjc.A.dylib 0x3b0be9d1 0x3b0b6000 + 35281 9 CoreFoundation 0x332dcf21 0x332d4000 + 36641 10 CoreFoundation 0x332dcd49 0x332d4000 + 36169 11 GraphicsServices 0x36eb52eb 0x36eb0000 + 21227 12 UIKit 0x351f2301 0x3519b000 + 357121 13 Stylbar 0x0007109f main (main.m:21)
Edit 3th of May:
The crash log is sent by a user. I haven't been able to reproduce the issue myself unfortunately, which is why it's so difficult for me to figure out what went wrong with just this crash log.
It appeared to have happened about 15 times in a row for the same user when opening a certain view controller. The view controller does several calls to a server to load a post, comments and images and profile pictures. All the code that's executed when this view controller is opened is probably over 2000 lines of code (excluding the RestKit and SBWebImage libraries that are used within this code). Posting that code here wouldn't help anyone I'm afraid.
Answers
The most simple and useful way to spend your time hunting for the cause of the crash is to look at your code and focus on places where UIKit has a delegate that points back into your code. For example, I found that the most common place this sort of thing would show up was in UITableView. The reason these problems are so hard to track down is that they might only happen in a low memory situation or in some uncommon UI condition that is very hard to reproduce. It is better to just do a code review and make sure that delegate that are set to point to your classes are set back to nil in your own object destructors. If you have many developers, it is often better to work on some higher level abstractions like a generic table and cell class that is used throughout the project than to have every developer coding up a UITableView and making mistakes like forgetting to nil out the delegate that are very difficult to find.
SIGSEGV is a problem the occurs when your application tries to access an address of memory that doesn't exists or some address where is already reserved to another program. I have the same issue with an application right now but I have to review my code to figure it out better. One clue for this kind of problem could be something equivalent to this (found in wikipedia):
#include <stdlib.h>
int main(void) { char p = NULL; / p is a pointer to char that initializes poiting to "nowhere"*/ * p = 'x'; /* Tries to save the char 'x' in 'no address'*/ return 0; }
I hope this can help someone.
Need Your Help
Splitting Strings by slashes
Deleting an associated record through a remote_form
ruby-on-rails ruby model associationsI have built a ruby on rails app that lets users track their workouts. User has_many workouts. In addition, a User can create a box (gym) if they are a gym owner. Users can then associate with that... | http://unixresources.net/faq/16320955.shtml | CC-MAIN-2018-43 | refinedweb | 704 | 70.02 |
Comparing floats and double variables depends on what your end goal is. If you want a runnable function without going too much in details and won't have a problem in some inaccurate calculations you can use the following function −
#include<iostream> using namespace std; // Define the error that you can tolerate #define EPSILON 0.000001 bool areSame(double a, double b) { return fabs(a - b) < EPSILON; } int main() { double a = 1.005; double b = 1.006; cout << areSame(a, a); cout << areSame(a, b); }
This will give the output −
1 0
This function takes your tolerance for error and checks if the threshold is greater than the difference between the numbers you're comparing. If you need something much more accurate, you're better off reading this excellent blog post: | https://www.tutorialspoint.com/How-to-compare-float-and-double-in-Cplusplus | CC-MAIN-2021-39 | refinedweb | 131 | 59.64 |
The description of the challenge was as follows:
There’s some valuable data on the server. However, to retrieve it we can only execute “signed” commands. We have the server script and some other files. Dare to take a look at it?
nc lazy.2016.volgactf.ru 8889
As usual in CTFs, the RSA-flavoured challenge was one of the simpler crypto tasks, mainly consisting of algebraic manipulation. The system used two functions
and
embodied in Python as below:
def sign(data, p, q, g, x, k): r = pow(g, k, p) % q s = (invert(k, q) * (SHA1(data) + x * r)) % q return (r, s) def verify(data, p, q, g, y, r, s): if not (r > 0 and r < q): return False if not (s > 0 and s < q): return False w = invert(s, q) u1 = (SHA1(data) * w) % q u2 = (r * w) % q v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q if v == r: return True else: return False
We are also given two signatures
and
, where
. Looking at the equation for signing, we note that the only thing which differs is
SHA(data) from two different signatures. Here,
are unknown values. Let
be the known signed strings. So, if we compute
,
we have something which only depends on
. It is now easy to determine the unknown
.
k = invert(((s1 - s2)*invert(SHA1(d1) - SHA1(d2), q)) % q, q)
Next, we can also find the unknown
by computing
x = ((s1 * k - SHA1(d1))*invert(r1,q)) % q
These unknowns can now be used to generate valid signatures for any command one would like to send to the server, so the rest is trivial. Using the code below, we connect to the server and unravel the flag:
import string import hashlib import itertools import socket import struct from server import * def bruteforce(prefix): print "[ ] Running proof-of-work bruteforce routine..." for lsuffix in itertools.product(string.printable,repeat=5): suffix = ''.join(lsuffix) sha_hash = hashlib.sha1(prefix+suffix).digest() if sha_hash[-3:] == '\xff\xff\xff': return prefix+suffix addr = 'lazy.2016.volgactf.ru' sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((addr, 8889)) print "[+] Connected to", addr data = read_message(sock) challenge = data[-16:].replace("\n","") print "[+] Challenge:", challenge response = bruteforce(challenge) send_message(sock, response) print "[+] Response:", response # pre-signed command, using sign() and the unravelled secrets cmd = ['618115531371374705088478644225735834217345085623', \ '108118980045367256474213546635114425133447666132', \ 'cat flag.txt'] send_message(sock, '\n'.join(cmd)) print read_message(sock)
This gives us
VolgaCTF{Do_not_be_lazy_use_nonce_only_once}. Great 🙂 | https://grocid.net/2016/03/27/volgactf-lazy/ | CC-MAIN-2017-17 | refinedweb | 410 | 54.73 |
Infinite Scrolling is a way to implement pagination in mobile devices. It is common among mobile interfaces due to the limited amount of space. If you use social media applications like Instagram or Twitter, this implementation is commonly used across those apps.
In this tutorial, let's learn how to implement an infinite scroll using the FlatList component in React Native. To fetch data, we will use a real REST API service provided by RAWG. It is one of the largest video game databases, and they have a free tier when it comes to using their API for personal or hobby projects.Then the React Query library will help us make the process of fetching data a lot smoother.
Prerequisites
To follow this tutorial, please make sure you have the following tools and utilities installed on your local development environment and have access to the services mentioned below:
- Node.js version
12.x.xor above installed
- Have access to one package manager such as npm or yarn or npx
- RAWG API key
You can also check the complete source code for this example at this GitHub repo.
Creating a new React Native app
To create a new React Native app, let's generate a project using the create-react-native-app command-line tool. This tool helps create universal React Native apps, supports React Native Web, and you can use native modules. It is currently being maintained by the awesome Expo team.
Open up a terminal window and execute the following command:
npx create-react-native-app # when prompted following questions What is your app named? infinite-scroll-with-react-query How would you like to start › Default new app # navigate inside the project directory after it has been created cd infinite-scroll-with-react-query
Then, let's install all the dependencies that will be used to create the demo app. In the same terminal window:
yarn add native-base react-query && expo install expo-linear-gradient react-native-safe-area-context react-native-svg
This command should download all the required dependencies. To run the app in its vanilla state, you can execute either of the following commands (depending on the mobile OS you're using). These commands will build the app.
# for iOS yarn ios # for android yarn android
Creating a Home Screen
Let's create a new directory called
/src. This directory will contain all the code related to the demo app. Inside it, create a sub-directory called
/screens that will contain the component file,
HomeScreen.js.
In this file, let's add some JSX code to display the title of the app screen.
import React from 'react'; import { Box, Text, Divider } from 'native-base'; export const HomeScreen = () => { return ( <Box flex={1} safeAreaTop <Box height={16} justifyContent={'center'} px={2}> <Text fontSize={28} fontWeight={'600'} color={'emerald.500'}> Explore Games </Text> </Box> <Divider /> </Box> ); };
The
Box component from NativeBase is a generic component. It comes with many props, a few of them are to apply the SafeAreaView of the device. The prop
safeAreaTop applies padding from the top of the device's screen. One advantage of using the NativeBase library is its built-in components provide props like handling safe area views.
Most NativeBase components also use utility props for most commonly used styled properties such as
justifyContent,
backgroundColor, etc., and shorthands for these utility props such as
px for padding horizontally.
Setting up providers
Both the NativeBase and React Query libraries require their corresponding providers to be set up at the root of the app. Open the
App.js file and add the following:
import React from 'react'; import { StatusBar } from 'expo-status-bar'; import { NativeBaseProvider } from 'native-base'; import { QueryClient, QueryClientProvider } from 'react-query'; import { HomeScreen } from './src/screens/HomeScreen'; const queryClient = new QueryClient(); export default function App() { return ( <> <StatusBar style='auto' /> <NativeBaseProvider> <QueryClientProvider client={queryClient}> <HomeScreen /> </QueryClientProvider> </NativeBaseProvider> </> ); }
All the providers must wrap the entry point or the first screen of the application. In the above snippet, there is only one screen, so all the providers are wrapping
HomeScreen.
The
QueryClientProvider component provides an instance in the form of
QueryClient that can be further used to interact with the cache.
After modifying the
App.js file, you will get the following output on a device:
Add a Base URL to use RAWG REST API
If you want to continue reading this post and build along with the demo app, make sure you have access to the API key for your RAWG account. Once you've done that, create a new file called
index.js inside the
/src/config directory. This file will export the base URL of the API and API key.
const BASE_URL = ''; // Replace the Xs below with your own API key const API_KEY = 'XXXXXX'; export { BASE_URL, API_KEY };
Replace the Xs in the above snippet with your own API key.
Fetching data from the API
To fetch the data, we will use the JavaScript
fetch API method. Create a new file called
index.js inside
/src/api. It will import the base URL and the API key from the
/config directory and expose a function that fetches the data.
import { BASE_URL, API_KEY } from '../config'; export const gamesApi = { // later convert this url to infinite scrolling fetchAllGames: () => fetch(`${BASE_URL}/games?key=${API_KEY}`).then(res => { return res.json(); }) };
Next, in the
HomeScreen.js file, import the React Query hook called
useQuery. This hook accepts two arguments. The first argument is a unique key. This key is a unique identifier in the form of a string, and it tracks the result of the query and caches it.
The second argument is a function that returns a promise. This promise is resolved when there is data or throws an error when there is something wrong when fetching the data. We've already created the promise function that fetches data asynchronously from the API's base Url in the form of
gamesApi.fetchAllGames(). Let's import the
gamesApi as well.
Inside the
HomeScreen, let's call this hook to get the data.
import React from 'react'; import { Box, Text, FlatList, Divider, Spinner } from 'native-base'; import { useQuery } from 'react-query'; import { gamesApi } from '../api'; export const HomeScreen = () => { const { isLoading, data } = useQuery('games', gamesApi.fetchAllGames); const gameItemExtractorKey = (item, index) => { return index.toString(); }; const renderData = item => { return ( <Text fontSize='20' py='2'> {item.item.name} </Text> ); };.results} keyExtractor={gameItemExtractorKey} renderItem={renderData} /> </Box> </Box> ); };
In the above snippet, take a note that React Query comes with the implementation of request states such as
isLoading. The
isLoading state implies that there is no data and is currently in the "fetching" state. To improve the user experience, while the
isLoading state is true, a loading indicator or a spinner component can be displayed (as did in the above snippet using the
Spinner component from NativeBase).
Here is the output after this step:
Adding pagination to the API request
The
useInfiniteQuery hook provided by the React Query library is a modified version of the
useQuery hook. In addition to the request states such as
isLoading and
data, it utilizes a function to get the next page number using
getNextPageParam.
In the case of RAWG REST API, the data fetch on each request contains the following keys:
count: the total count of games.
next: the URL to the next page.
previous: the URL of the previous page. Is
nullif the current page is first.
results: the array of items on an individual page.
The key names
next, and
previous will depend on the response structure of the API request. Make sure to check your data response what are the key names and what are their values.
Currently, the API request made in the
/api/index.js file does not consider the number of the current page. Modify as shown below to fetch the data based on the page number.
export const gamesApi = { // later convert this url to infinite scrolling fetchAllGames: ({ pageParam = 1 }) => fetch(`${BASE_URL}/games?key=${API_KEY}&page=${pageParam}`).then(res => { return res.json(); }) };
The addition
&page=${pageParam} in the above snippet is how the
getNextPageParam function will traverse to the next page if the current page number is passed in the request endpoint. Initially, the value of
pageParam is
1.
Using useInfiniteQuery hook
Let's import the
useInfiniteQuery hook in the
HomeScreen.js file.
// rest of the import statements remain same import { useInfiniteQuery } from 'react-query';
Next, inside the
HomeScreen component, replace the
useQuery hook with the
useInfiniteQuery hook as shown below. Along with the two arguments, the new hook will also contain an object as the third argument. This object contains the logic to fetch the data from the next page using the
getNextPageParam function.
The function retrieves the page number of the next page. It accepts a parameter called
lastPage that contains the response of the last query. As per the response structure we discussed earlier in the previous section, check the value of
lastPage.next. If it is not
null, return the next page's number. If it is
null, return the response from the last query.
const { isLoading, data, hasNextPage, fetchNextPage } = useInfiniteQuery( 'games', gamesApi.fetchAllGames, { getNextPageParam: lastPage => { if (lastPage.next !== null) { return lastPage.next; } return lastPage; } } );
Implementing infinite scroll on FlatList
In the previous snippet, the
hasNextPage and the
fetchNextPage are essential. The
hasNextPage contains a boolean. If it is
true, it indicates that more data can be fetched. The
fetchNextPage is the function provided by the
useInfiniteQuery to fetch the data of the next page.
Add a handle method inside the
HomeScreen component called
loadMore. This function will be used on the FlatList prop called
onEndReached. This prop is called when the scroll position reaches a threshold value.
const loadMore = () => { if (hasNextPage) { fetchNextPage(); } };
Another difference between
useInfiniteQuery and
useQuery is that the former's response structure includes an array of fetched pages in the form of
data.pages. Using JavaScript
map function, get the
results array of each page.
Modify the
FlatList component as shown below:
<FlatList data={data.pages.map(page => page.results).flat()} keyExtractor={gameItemExtractorKey} renderItem={renderData} onEndReached={loadMore} />
Here is the output after this step. Notice the scroll indicator on the right-hand side of the screen. As soon as it reaches a little below half of the list, it repositions itself. This repositioning indicates that the data from the next page is fetched by the
useInfiniteQuery hook.
The default value of the threshold is
0.5. This means that the
loadMore will get triggered at the half-visible length of the list. To modify this value, you can add another prop,
onEndReachedThreshold. It accepts a value between 0 and 1, where 0 is the end of the list.
<FlatList data={data.pages.map(page => page.results).flat()} keyExtractor={gameItemExtractorKey} renderItem={renderData} onEndReached={loadMore} onEndReachedThreshold={0.3} />
Display a spinner when fetching next page data
Another way to enhance the user experience is when the end of the list is reached, and the data of the next page is still being fetched (let's say, the network is weak). While the app user waits for the data, it is good to display a loading indicator.
The
useInfiniteQuery hook provides a state called
isFetchingNextPage. Its value will be true when the data from the next page is fetched using
fetchNextPage.
Modify the
HomeScreen component as shown below. The loading spinner renders when the value of
isFetchingNextPage is true. The
ListFooterComponent on the FlatList component is used to display the loading indicator at the end of the list items.
export const HomeScreen = () => { const { isLoading, data, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery('games', gamesApi.fetchAllGames, { getNextPageParam: lastPage => { if (lastPage.next !== null) { return lastPage.next; } return lastPage; } }); const loadMore = () => { if (hasNextPage) { fetchNextPage(); } }; const renderSpinner = () => { return <Spinner color='emerald.500' size='lg' />; }; const gameItemExtractorKey = (item, index) => { return index.toString(); }; const renderData = item => { return ( <Box px={2} mb={8}> <Text fontSize='20'>{item.item.name}</Text> </Box> ); };.pages.map(page => page.results).flat()} keyExtractor={gameItemExtractorKey} renderItem={renderData} onEndReached={loadMore} onEndReachedThreshold={0.3} ListFooterComponent={isFetchingNextPage ? renderSpinner : null} /> </Box> </Box> ); };
Here is the output:
Wrapping up
In this tutorial, you've successfully implemented infinite scroll using
useInfiniteQuery from React Query. Using this library for fetching and managing data inside a React Native app takes away a lot of pain points. Make sure to check out the Infinite Queries documentation here.
You can also check the complete source code for this example at this GitHub repo.
Finally, don't forget to pay special attention if you're developing commercial React Native apps that contain sensitive logic. You can protect them against code theft, tampering, and reverse engineering by following our guide. | https://blog.jscrambler.com/implementing-infinite-scroll-with-react-query-and-flatlist-in-react-native/ | CC-MAIN-2022-27 | refinedweb | 2,095 | 56.55 |
DotNetStories
Τhis is the second post in a series of posts on how to design and implement an ASP.Net 4.5 Web Forms store that sells posters on line.
Make sure you read the first post in the series.You can find it here.
In all these posts I am going to publish, I will change the layout. That means I will make changes to the .master,.css,.aspx files and images. In the final post I will add the whole solution so you can download everything.
Have a look at the picture below to see the new slightly changed layout
Now that we have made the necessary changes to the .aspx pages,the master page,the .css files and adding some more images to our site we are ready to move forward and implement the data access layer.
I will use Entity Framework 5.0 in order to create the data access layer.
Obviously I cannot go into much detail on what EF is and what it does. I
will give a short introduction though.
For this project I will use the Code First approach to build the data access layer.
The Code First approach is the more code-centric than the other two (Database First, Model First). Basically we write POCO classes and then we persist to a database using something called DBContext.
Code First relies on DbContext. We create 2,3 classes (e.g Person,Product) with properties and then these classes interact with the DbContext class and we can create a new database based upon our POCOS classes and have tables generated from those classes.We do not have an .edmx file in this approach.By using this approach we can write much easier unit tests.
DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First).
Let's implement our POCO classes
1) Launch Visual Studio and open your solution where your project lives
2) Create a new folder. Name it DAL or any other name you think it is appropriate.We will place in there our entity classes
3) Obviously you must include EF in your solution. The good news is that EF is included in any ASP.Net Web Forms Application. If you are not sure whether you have the latest version or not of the EF then just use NuGet.
In my case the EF version is 5.0. Have a look at the picture below
4) We also need to add a reference to the System.Data.Entity namespace.Select References from the Solution Explorer and then choose Add Reference... You have to browse through the assemblies in the .Net Framework until you locate the System.Data.Entity and the click OK.
Have a look at the picture below
5) Select the DAL folder, then right-click and then select Add -> New Item.We will add a class file, Poster.cs. Have a look at the picture below
6) Now we need to write the code for the Poster.cs Entity class.Please bear in mind that every instance of the Poster class (an object) will represent a row in the database table and every property in the class declaration will represent a table column. The code followspublic class Poster
7) Select the DAL folder, then right-click and then select Add -> New Item.We will add a class file, PosterCategory.cs. The code follows
public class PosterCategory
{
[ScaffoldColumn(false)]
public int PosterCategoryID { get; set; }
[Required, StringLength(50), Display(Name = "Category Name")]
public string PosterCategoryName { get; set; }
[Required,StringLength(200),Display(Name = "Category Description")]
public string CategoryDescription { get; set; }
public List<Poster> Posters { get; set; }
}
8) Select the DAL folder, then right-click and then select Add -> New Item.We will add another entity class called PosterContext.cs. This class will inherit from DbContext. Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.
This class manages the domain classes and provides data access to the database.Think of it as an orchestrator class.
The code for this class follows
public class PosterContext:DbContext
{
public DbSet<PosterCategory> PosterCategories { get; set; }
public DbSet<Poster> Posters { get; set; }
}
Do not forget to add (using System.Data.Entity;) in the beginning of the class file.
I would like to talk at this point a little bit about Code First Data Annotations.With Data Annotations we can configure our domain-entity classes so that they can take best advantage of the EF.We will decorate our entity classes with declarative attributes.Let me give you an insight on how EF Code First works.EF Code First at run time, looks at the entity-domain classes and infers from them the in-memory data that it needs to interpret the queries and interact with the database.For example it assumes that any property named ID represents the key property of the class.Please have a look at this post of mine to find out more about Data Annotations.
public class PosterInsert : DropCreateDatabaseIfModelChanges<PosterContext>
{
protected override void Seed(PosterContext context)
{
var pcategory = new List<PosterCategory>
{
new PosterCategory {
PosterCategoryName = "Midfielders",CategoryDescription="Posters of active and past Liverpool Midfielders",
Posters = new List<Poster>
{
new Poster {PosterName = "King Kenny", PosterDescription="King Kenny lifting the European Cup",PosterImgpath="Images/posters/kenny-dalglish.jpg",PosterPrice=18.95},
new Poster {PosterName = "John Barnes", PosterDescription="El mago-a true genius in the midfield",PosterImgpath="Images/posters/john-barnes.jpg",PosterPrice=16.95},
new Poster {PosterName = "Steven Gerrard", PosterDescription="The Captain",PosterImgpath="Images/posters/steven-gerrard.jpg",PosterPrice=28.95},
}
},
new PosterCategory {
PosterCategoryName = "Defenders",CategoryDescription="Posters of active and past Liverpool Defenders",
Posters = new List<Poster>
{
new Poster {PosterName = "Jamie Carragher", PosterDescription="Th greatest defender in the last ten years",PosterImgpath="Images/posters/jamie-carragher.jpg",PosterPrice=21.95},
new Poster {PosterName = "Alan Hansen", PosterDescription="The legendary defender Alan Hansen",PosterImgpath="Images/posters/alan-hansen.jpg",PosterPrice=13.95},
new Poster {PosterName = "Martin Skrtel", PosterDescription="The most promising defender playing right now",PosterImgpath="Images/posters/martin-skrtel.jpg",PosterPrice=19.95},
}
},
new PosterCategory {
PosterCategoryName = "Strikers",CategoryDescription="Posters of active and past Liverpool Strikers",
Posters = new List<Poster>
{
new Poster {PosterName = "Ian Rush", PosterDescription="The greatest striker to wear a Liverpool shirt",PosterImgpath="Images/posters/ian-rush.jpg",PosterPrice=18.45},
new Poster {PosterName = "Robbie Fowler", PosterDescription="Robbie, a goal scoring machine",PosterImgpath="Images/posters/robbie-fowler.jpg",PosterPrice=18.45},
new Poster {PosterName = "Michael Owen", PosterDescription="The youngest deadliest striker Anfield has even known",PosterImgpath="Images/posters/michael-owen.jpg",PosterPrice=16.95},
}
}
};
pcategory.ForEach(post => context.PosterCategories.Add(post));
base.Seed(context);
}
}
In this class I inherit from the DropCreateDatabaseIfModelChanges<PosterContext> class and I will override the default behaviour of that class with my class.
I will ovverride the Seed method with some data.Then I create 3 instances of the PosterCategory entity and 9 entities of the Poster entity.
Then through a simple lambda expression I add the data to the database using this last line of code,
base.Seed(context);
10) Now we need to make one more change.in the Global.asax.cs.
In the Application_Start event handler routine (runs when the application starts) we will add this code
Database.SetInitializer(new PosterInsert());
11) I have also created a Posters folder inside the Images folder and placed in it the 9 images.
12) Build and run your application. Everything should compile now. Have a look at the picture below to see the structure of the web application so far.
13) Now we will create a test page to see if the database is created and populated with values.Add a web form page to the application.Name it PostersTest.Add a gridview web server control on the page. Make the page as the Start Page
In the Page_Load event handling routine type
PosterContext ctx = new PosterContext();
var query = from postcat in ctx.PosterCategories select postcat.PosterCategoryName;
GridView1.DataSource = query.ToList();
GridView1.DataBind();
Build and run your application. Have a look below to see the result I have got.
It seems to work. The database is created and populated through the magic of EF Code First. Have a look at the web.config for the connection string. In the Solution Explorer look into the App_Data folder.
If you open the Server Explorer and open the connection to the database (in my case PostersOnLine.DAL.PosterContext.mdf).I am using LocalDB, which is anew version of SQL Express.For more information have a look here.
Have a look at the picture below.These are the results when I query the tables.
We can also have a look at the table's definitions.I select the PosterCategories table in the Server Explorer window and then choose "Open table definition".Have a look at the picture below.Please note that the table's definition is influenced by the data annotation attributes set in the domain classes.
I will do the same for the Posters table.In this case I also choose to show the T-SQL that is created for the table
Have a look at the picture below.EF Code First does a great job creating the database objects that reflect the definition and attributes in the domain classes.
Please make sure you follow all the steps.I will post soon part 3.
Hope it helps!!!! | http://weblogs.asp.net/dotnetstories/building-an-asp-net-4-5-web-forms-application-part-2 | CC-MAIN-2015-06 | refinedweb | 1,569 | 50.23 |
Being a newbie for Clojure, the problem I met when trying to use its other core library –
clojure.core.reducers is the “namespace not found…”.
Get this:
clojure.lang.Compiler$CompilerException: java.lang.Exception: namespace ‘clojure.core.reducers’ not found, compiling: … … … Caused by: java.lang.Exception: namespace ‘clojure.core.reducers’ not found
From the docs,
It seems like we need Java version that support fork/join operation. Let’s see what version do we have?
Our system show we’re using Java 6 which does not meet the requirement for
clojure.core.reducers. We need a to upgrade our JDK. Coming from non Java background, I do not even know the JRE or JDK thing. But in this case what we need is for development, so it makes sense to just download the JDK. So let’s download and install it from the official page.
Once we finished installation, the latest version is loaded default.
If you start your repl again, you will see it’s using the latest verison.
Ok so we are cool now: | http://yang-wei.github.io/blog/2015/10/01/update-jvm-version-in-mac/ | CC-MAIN-2018-51 | refinedweb | 176 | 69.99 |
Okay,), so there shouldn’t be any problems with notes in the slides or other metadata. Also note that I made this entire presentation the day of the conference, so let me know if there are unclear parts.
“But Matt, some of that talk is just bullet points! Where’s the context?” you might comment. Ah, I’m glad you mentioned that. John Pozadzides attended WordCamp and taped the talks, and he recently put up a video of the talk.
“But Matt, I don’t have an hour to spare to watch the video!” you might comment. Ah, I’m glad that you mentioned that. David Klein was at WordCamp, and he transcribed the talk into text form.
“But Matt, that transcript has a lot of words. It could take me 20-30 minutes to read all that!” you might comment. Well, I’ve already pointed to Stephanie Booth’s write-up of the session. You could also read the summary that Lisa Barone wrote. Or check out Stephan Spencer’s coverage for CNET.
Now you understand why I blogged about Alex Chiu a while ago; I used him as an example in my talk, so I wanted to explain what those two urls in my PowerPoint meant.
If you read Stephan Spencer’s write-up,
he says some also wanted to point out something I’m pretty proud of. If you were at the site review session at Pubcon last year in Vegas, you might remember that there was a chiropractor who wanted to do well for the query [san diego chiropractor]. At the time, Danny Sullivan teased him a bit and said “Well, you might want to put the words ‘San Diego Chiropractor’ together on the page that you want to rank.”
Well Danny, that site owner was David Klein and he took all the PubCon advice from the panel to heart. He started a blog, tweaked the copy on his site, and has even started to learn great linkbaiting techniques. For one thing, he transcribed the video of my talk, which traded some effort on his part to create a useful resource. Even better, he came to WordCamp with a creative idea, a pad of paper, and a digital camera. As he met folks at WordCamp, he had each person write their name, their website, and something that they wanted to do. Then he created an original cartoon of that person doing that thing. Go to the post with Matt Mullenweg and click on the picture of Matt to see what I mean. Matt said he wanted to be a writer, so David posted a cartoon of Matt as a writer.
How is this smart? People love to talk about themselves, and love to see themselves in the spotlight. So these little cartoons are natural linkbait: “Hey look, he drew me as a Photoshop plug-in developer!” How much did it cost to do this particular idea? Practically nothing: just the initial creative brainstorming and a little bit of elbow grease.
It was neat to see a regular site owner go from not knowing much about SEO in November 2006 to really improving his traffic with some creativity and straightforward changes. A good SEO can tune up your web site. But if someone is willing to take the time to study SEO, look for fresh ideas, and put in some effort, a regular person can definitely improve their website (and rankings!) as well. To see that come true with a chiropractor that several of us gave feedback to just last year was really exciting. That’s one of the big things that has stayed with me from WordCamp.
Update: Clarifying that Stephan’s write-up didn’t say that dashes and underscores were the same. Thanks, Stephan!
178 Responses to Whitehat SEO tips for bloggers (Leave a comment)
Matt
Great post! next post maybe SEO tips for large news sites 🙂
However, when would you start using only “SEO” instead “Whitehat SEO”?
You see there is either “SEO” or “Spam” 🙂
Great post!
very interesting read.
i have a lot of work and learning to do.
Thanks, Matt.
The notepad idea was pretty cool. I would have requested they write their names down too but thats probably cause I forget names so easily.
On a separate note, Are you feeling any better Matt?
I think you meant to link to the cartoon at not the photograph. Unless you’re demonstrating a way to get people like me to add yet another link to the guy’s website.
Any direct downloadable video available Matt ?
Thanks for the slides Matt.
Best,
Mani
Butt Matt, I’ve devoured all of the video and transcripts and want more!
It’s REALLY nice to see so much creativity in blogging circles recently, and so many new tradeshows to do with webmasters, blogging, seo etc. Copying others and repeating news is so web 1.0!
Can’t wait to see you at pubcon.
Nice article Matt, I love a ‘guy on the street’ story, good for him!
Amen to that and thanks. After the recent flurry of conversations surrounding this topic in various blogs it was becoming a little hazy on what was best way forward. Thanks for confirming this as this puts to rest a debate with our small team.
[quote]I think you meant to link to the cartoon[/quote]
Now I think you meant to link to what you linked to because you already explained how to see the cartoons.
I hope my quote works. There are no quoting instructions. I don’t even see what blog software this is, but I guess it’s Google’s, whatever it’s called.
I knew little about SEO before reading this and other type blogs. I am now much more aware and enlightened.
Good on this chap and Danny is a bad boy for teasing him.
Cheers,
Steve
Hey Matt, great post, but the San Diego Chiropractic business has pretty much nothing to do with the topics he’s talking about in his blog — the blog is just personal anecdotes as far as I can tell. I like how you keep re-inforcing the link bait idea, but are you suggesting that a link to a page like is really useful for his business website?
Hi Matt
Thanks for the powerpoint presentation, it did give me some useful ideas I want to thank you for it!
best regards
Frank
Great post Matt. It’s so informative.
You should host your presentation on YouTube. Some excellent nuggets of info here!
SearchEnginesWeb disagrees with several points in this theme:
It is one thing to have a site that ranks for very non competative keywords that may only bring one visitor every few weeks, but it is an entirely different ballgame as the keywords get more competative.
Many people who resort to Gray Hat strategies have no other choice because of budgets and the fact that their competitors can dwarf them in every conceivable way. Because many firms are expanding into more and more areas – many smaller people are being squeezed out to the point of invisibility.
It simply does very very very very little good to have a ranking far away from page one. And even so, there are sponsor links and adwords competing for attention on virtually every page.
On the subject of link bait – IT DOES NOT REFLECT ON THE PRODUCTS OR SERVICES THAT SOMEONE IS PUSHING. Sure, you can use creative tactics to get eyeballs to your domain, but that has nothing to do with whether the product or service that is being pushed is any good.
What SearchEnginesWeb just can not make you or Google Engineers understand is that…..
…..there has to be a reworking of the entire system from the ground up.
The eco-system is being irreversibly altered because the rich are just as hungry to get richer, as the newbie is to get a foothole. Who is likely to win in the competition???!!!
You talk about IMPROVING a site – but what is being lost is that there was NOTHING to begin with. Any effort will be a technical improvement, but it does not mean that someone will get prospects after debuting at page 4 from page 20.
Gray Hat and Black Hat evolved out of desperation and cynicism. They will continue to get more advanced until some understanding is demonstrated and some compassion is shown in the ALGOS.
These rebuttals are not to be taken personally. SearchEnginesWeb is quite aware of what you and the rest of the Google Engineers are saying about these passionate posts and incessant pleas for mutual understanding.
Thanks Matt, Nice Post and PPT…..:-)
Hi Matt,
Very interesting post. It couldn’t have come at a better time too. I have just recently “persuaded” my manager (SEO Dept Head) to allow me to implement a blog into our sites.
This, along with my information that I have passed on will definitely help me give this addition (the blog) a bit more weight in his eyes.
Presentation was great, and thanks for the links and listing of the plugins you use. Will watch the video a little later.
Byron
What an absurd idea: Publishing cartoons to add so-called “valuable” content for a chiropractic’s site.
How does this fit into Google guidelines for webmasters:
Tell me that this is a joke, please…
Thanks for posting the PPT file. What, no Google Presently? 🙂
> Don’t put blog at root page of domain
I’d say consider to *do* put the blog at the root. Don’t even think of creating a subdomain for it. You can still have your “normal” homepage be at a different domain. I’ve some experience with making the wrong choice on this issue with “blog.outer-court.com”…
And look at, which is a rather blank, unused page, so people must enter longer URLs to get to the content, or do an extra click.
And the argument “you get some extra links that way”, well, forget about thinking about links, and focus on the reader, isn’t that better?
> ALT tags
Must not nitpick… must not nitpick… 🙂
But serious, alt texts aren’t meant to be title texts. They’re two different things, and using alt text like “Company Logo” is really more hurtful (as is using alt to keyword-stuff… not in SEO terms, but in accessibility terms, e.g. for non-visual browsing scenarios).
> SEO tips: Usability
> – Make sure your site is crawlable
> …
> – Check your blog on a cell phone/iPhone
That’s accessibility, not usability. OK, I AM nitpicking now 😉
> Creativity creates buzz/word-of-mouth
> – Lonelygirl15
> – Million pixel home page
Agreed, though by stating specific examples of past buzz-creating approaches, people can fall into a trap and e.g. create another million-dollar-homepage spin-off (a good way to look like a spammer). The part about the million-dollar homepage that was interesting was not its specific concept, but the fact that this specific concept was new. I think it’s cool to get partly inspired by these things, especially in terms of craft or “media uses” if you will (the million dollar guy invested in a not-so-cheap press release, for instance), but you need to mix it with your own passion and angles.
> Create controversy
> – Mention Robert Scoble
Sigh. “How to be a troll to get higher PageRank 101”?
Why not say “Don’t shy away from controversy IF you truly believe in what you say”?
I have decided I don’t need SEO anymore, in any way, shape or form…
My site has been taken over by a strange religious force who has moved me to the top of Google!
Here’s the article, see for yourself…
I don’t believe Matt did say “alt texts aren’t meant to be title texts”.
Alt=Alternative Text for those who cannot see images for whatever reason. They should briefly and concisely describe the image and should always be used. Unfortunately most Browsers erroneously show the Alt attribute as tool-tip text.
The Title attribute can be used if the image is linked to another page or bookmark. In this case is should be used to briefly and concisely describe the landing page/bookmark.
Nice Work!
These are easy things to make a nice seo on your blog for those don’t have much experience on Advanced SEO.
Anyway I miss something, quite easy, for everyone. Disallow certain pages on robots…
That may depend on whether you’re targeting businesses. According to False Oracles: Consumer Reaction to Learning the Truth About How Search Engines Work at you’re right when it comes to consumers.
“Not one participant explored search results beyond the fifth delivered page. Of the 163 searches in which a participant selected a link to explore, the majority or 88 percent of the result links selected were located on the first page. The number of pages explored by participants decreased considerably after page one. There were only 16 cases in which a participant viewed the second page of results, two cases where the third page was reviewed, and one case in which the fifth page was scanned.”
But look at this Q and A from WebAdvantage.net’s “Business Users Search Engine Survey” at :
Question 5:
If you don’t find what you’re looking for on the first page of search results, do you typically quit at that point or continue on?
Quit after 1st Page: 37 (8%)
Continue on to 2nd Page: 125 (28%)
Continue on to 3rd Page: 125 (28%)
Continue on past the 4th page until I find what I’m looking for: 164 (36%)
I also found some alleged AOL search engine data but the above seems more reliable.
Hi Matt,
This is really a very good presentation and gives many good ideas, 10x
A lot of nice hints, but iam not sure about all of them. some points contingently collide with googles webmaster guidelines. what’s it all about Matt?
C’mon Matt, you missed the most important part about David. He’s ranking tops for the term now 🙂
Good presentation 🙂
But blog not in the root of domain … only if you have another project in the root!
Thank you Matt! Great PowerPoint. Thank you for the tips.
Can I ask for a suggestion?
I see you have 5 posts on your page and I guess in that case there is no need for the to avoid duplicate content on your own site since you are very active and the index does not have a “more” and your blog archives quickly , but what about those blogs that have 25 or even 50 posts on the index? Yes the will avoid having GoogleBot seeing it as duplicate but is there a suggestion you can recommend on how much content should be posted before the and also how many posts should be put on the index?
Hi Matt
Thank you for clarifying the _ – issue… it’s lovely to go into the weekend with at least one aspect of SEO clear in our minds!
Cheers
G
Nice Presentation Matt. It is very usefull for SEO.
@Matt
Hi Matt, cool presentation 🙂
You talked among other things about not putting blogs in the root, and later about redirects.
After that, I was wondering why you don’t redirect your root to /blog, instead of the short text with hyperlinks pointing to /blog. Is there a SEO reason for not redirecting (using 301 or 302) to the blog directory, or a just personal preference?
(At the moment my website faces the same question. Since my website doesn’t have a homepage, but I do want to point the root to my blog, I’m wondering if I should redirect or create a almost empty root with links, like you have.)
i think the cartoons are a great idea. but i almost wonder if it wouldn’t be better to have these types of things in a personal blog off the main site. this way there is a separation between the business and the personal side.
OFF TOPIC COMMENT AHEAD!!
Now for the real meat of my post! with the google dance and ses 07 coming up very soon the question begs to be asked about if you will be there. since for many SEO’s you are the face and the voice of google i know many people, my self included, would love to meet you in person and talk about things like “Why did google take my spam site out of the index” and other fun stuff.
> I don’t believe Matt did say “alt texts aren’t meant to be title texts”.
Yes, you’re right. It was more of a general remark, because Matt’s item on this wasn’t very detailed. Matt’s presentation says, “ALT tags are handy (3-4 relevant words)”. And I think that advice is not conforming to alt-attribute-the-way-it’s-meant to be. And if you’re at that point, you’re writing your HTML for search engines, not conforming to the W3C specifications, which are meant for all user agents (including search engines, but also e.g. non-visual browsing contexts, your “normal” big resolution IE7 with all kinds of plugins, mobile browsers, etc.). The best tip for alt texts IMO is “if necessary and possible communicate the message the image, when rendered/ seen, was intended to communicate”.
And again, the title attribute fits much more with the “3-4 relevant words” advice, at least outside of doing-something-just-for-searche-engines advice. If I have a painting of Vermeer then the title attribute can be something like “Vermeer van Delft: Girl with a Pearl Earring”. There you have the keywords (and a search bot may look at this for image search etc.). But these words mostly should also appear below that painting, as normal text outside the image. And if you’d include the same words as alt text, a non-image rendering context will display or speak the following:
Vermeer van Delft: Girl with a Pearl Earring
Vermeer van Delft: Girl with a Pearl Earring
And that’s bad accessibility because it’s repetitive. Instead, the alt text in this case should be e.g. “The lady, who looks to be in her early twenties, has her face directed towards… etc. etc.”. (*If* you’re serious about replacing the intent of showing the painting through an alt-text.)
@Matt
As truly fantastic a plugin as it is, over the past year I’ve found Akismet becoming less and less effective. I recently learned about the Spam Karma 2 antispam plugin and I find it to be far superior. The configurable options and complex weighting system make it an exceptionally versatile comment analysis utility.
@SearchEnginesWeb
That was a fantastic rebuttal. Everyone wants a piece of the pie but there isn’t enough dessert to go around. I oversimplify this to make my point, but as a Technical Writer I’ve often observed engineers putting too much focus on the technical side and not enough on the human side. Some people will do anything – even skip dinner – to get pie, but engineers often advise these people to simply sharpen their forks and wait for the pie to come to them.
I also have a write up of your presentation on my blog, plus 17 other steps to optimize your WordPress Blog for SEO.
To Davids credit he had a good ranking before Matt made this post. I know Dave and he’s likely peeing his pants know with excitement. This guy has worked hard to learn the stuff from the ground up.
Matt_Not_Cutts: I believe there is only so much David can say about his business. That gets boring day in and day out. We now get to see a human side “the non clinical white coat guy” of this fellow and that is good for his business (at least in MHO).
Great post!
Thanks Matt…Great PPT/Tips.
I remember that in the Pubcon 2006. I had a big Local Listing issue solved for sarasota massage therapy listing as well. Thats when I realized how Google and the team response to issue like quickly. Thanks Matt
p.s., Matt, I love your term “blindingly loud”!
Thanks for the powerpoint Matt. A lot of good reminders in there for folks to consider. See you in San Jose. Stop by the Enquiro booth (if you get a moment) and say hello.
Harith, I’m comfortable with SEO being whitehat/blackhat; I don’t think you’d get many blackhats to say “I don’t do SEO; I do spam!”
Colin Colehour, thanks for asking. Right now I’m in bed with a pack of frozen peas again. I start to get a little better and stress da back too much. I’m hoping to get some lie-down-for-long-stretches-of-time cycles soon.
Barry, I didn’t want to copy the photos without permission, but also wanted people to see the photos first. But your link will cause people to see it.
Anjanesh, you’d have to check with John; he uploaded it, not me. If I did it, I would have put it up on Google Video. 🙂
Barry, I use WordPress (that’s part of why I was speaking at WordCamp) I think using the “blockquote” tag is the way to quote in a box.
Steve Hill, Danny always teases gently. And in fact I teased a bit for the site using Comic Sans as the font. It’s still around on the site a little bit, but not on the main page now. Alls well that ends the use of Comic Sans, I always say.
Matt_Not_Cutts and Robert, normally I get the question in the exact opposite way: “Suppose I run a heavy farm equipment blog. There’s clearly nothing interesting to talk about or linkbait to do in the farm equipment space.” David’s blog proves that just taking part in web-wide conversations can stir up interest. Blogs are a great way to humanize, to participate, and yes, to get links. People sometimes link to my Firefox posts more than my SEO posts, for example. That’s not a horrible thing. And simply by putting on his thinking cap and participating in the conversation (David sometimes comments over here, although I didn’t connect it in my mind until we talked in person), that contributes to your web savviness and success.
SEarCHEnGinESWEB, this was not a search/SEO conference. This was a room full of bloggers who had different levels of SEO awareness. If you watch the talk, one of the big themes I tried to hit was creativity for post ideas. I do think that’s a useful skill that will pay off for the people that were in the audience.
Philipp Lenssen, my “root page” point was to leave yourself room for future expansion; if you ever want to do something on your root page *other* than a blog, it’s a pain to migrate all those urls. So I recommend adding a qualifying namespace (e.g. /blog/) so that you’ve got room to grow beyond just a blog. On ALT tags, my point was more to do them and have them accurately describe the image, rather than not do them. I love that WordPress asks you for ALT text for each image you add. I would run the risk of getting lazy if I were adding the tag myself.
Philipp, On the whole “controversy” and “make lists” ways of link baiting, if you read the talk transcript, I said things like “Ah, I don’t care as much for creative controversy.” and “Use this sparingly, cause, boy, you can give up some credibility as well.” So I tried to convey that if linkbait is in tiers of goodness, creativity is at the top, and just being controversial is definitely one of the lower forms of linkbaiting in my book. Given that this was a room full of bloggers, I thought it appropriate to point out that people do things like “slip the name Robert Scoble” into a post, but it’s better to come up with creative ideas of your own.
Danny Sullivan, absolutely, he’s doing much better for his terms. David talked to me at WordCamp about some of the success he’s had with SEO, but I wasn’t going to remark on his success; I’ll leave that up to David to decide whether/how to comment. But the people who said “I don’t think some of this stuff would help,” — David has done well with the search engine optimization that he’s taught himself.
Michael Wilson SEO, ten posts on the front page is pretty good for lots of folks. I lowered mine to five mainly for mobile/iPhone readers. I think 25 or 50 is a bit much, but that’s more my personal opinion. Depending on your industry, I’d experiment for a week or two with different numbers of posts on the front-page, and go with whatever seems to work well.
Philipp Lenssen, I covered ALT tags a bit earlier in this comment but my short three points would be
1. Use them
2. Make them accurate
3. After the first two, it doesn’t hurt to be aware and use keywords that users might type.
Brian, thanks for the plugin advice! I heard good things about Spam Karma and also Bad Behavior at the conference.
Michael Dorausch, but it’s also true that David has at least a couple online resources that are directly work-specific that I found interesting.
OMG! Matt broke Viddler.com.
If you read John Pozadzides ‘s post he says:
“I first made this video available on Viddler.com, but their entire site went down shortly after I created this post”
Unfortunately, your post points to a deficiency of Google. As far as I can tell, you’re saying that because there is no great way to differentiate yourself for the “San Diego Chiropractor” search, in that most people aren’t going on the Internet and raving about their local chiropractor with links that will then boost the chiropractor’s rankings, that the thing to do is create a lot of unrelated content that WILL build links back, thus making you rank better for “San Diego Chiropractor”, even though nothing you’ve done offers the least suggestion that you deserve to show up first when someone is searching for a chiropractor in San Diego.
Granted, if you’re looking for a chiropractor in San Diego, it’s difficult for a search engine to discern which one is the best, but it’s not difficult for a search engine to discern which one is the best at creating unrelated content and having people who know nothing about the chiropractic services link back to that content. This guy could be the worst chiropractor in the world but good at making fun cartoons, but is that the best thing for my aching back?
We all know this is often how SEO works, but it’s certainly not the ideal, and it’s strange to see you touting this person’s SEO strategy as if this is a good thing for Google’s end customer, the searcher.
I am fairly new to the whole SEO game but I have to ask the same question a few of the dissenters have – how do cartoons make a Chiropractor’s site any more relevant for the service he’s trying to promote? I get the idea behind LinkBaiting, but in this case isn’t it just trying to work the system and in the end generating non-relevant links back to his site?
Great post Matt,
This sort of stuff helps the small DIY webmaster whether for blogging or other types of websites.
Our vertical is the sort of thing detractors say “its boring – you cant link bait that” – but I disagree. You just need to think out of the box and make your “boring commodity” interesting.
In fact – if your “boring commodity” is no more interesting than the 10 others already on page 1 why should they make way for you?
We have just commisioned a custom flash game to be written as link bait and “fun” for our “boring commodity” site. May work/may not work (and darn its gonna take a month to write) – but at least we are trying.
So, Matt – thanks for posts like these – they are extremely helpful to the DIY Webmaster/SEO like me who are learning the ropes (the hard way)
Great Post Matt,
Perhaps sometime soon you could post something for Realtors who are trying to help their own site in white hat SEO ways. For me personally I am getting kind of exausted with Active Rain, RealEstateWebmasters Blogs, WordPress, … Just getting to be very very time consuming and seems like their must be some other things that would give equal or better benefit as the above listed. Any ideas???
Just wanted to thank you for posting it all. Some good reminders, and a few newish things.
One question regarding domain.com and – I was just about to use a 301 rewrite to force use of one. Can I leave it at that, or should I also register my site with google/webmasters and choose the same one?
Ray Burn, happy if it helps. 🙂
Adam Jusko, I think you’re focusing disproportionately on the linkbait aspect. David wanted to show up for the words “A B C” and when he brought it to the site review panel, I don’t think the page even had the words “A B C” on it, let alone together as a phrase of adjacent words. Then there’s improving your ROI by improving your conversion rate. I mentioned that the site would probably want to look as professional as possible, which is a good reason to minimize the Comic Sans font. Hopefully a few extra visitors converted because of changes like that.
Did David get creative? Sure. But much of that creativity was completely on-topic. For example, he posted the full content of two books her wrote about his subject area:
That’s the sort of thing that stacks up well against an empty or brochure-like site. So David did a ton of things to tweak his sites, improve his conversion rates, and bolster his reputation in a relevant, on-topic way.
Things like starting a blog can attract links, but the bedrock of SEO is still having a great site, and David focused on that first.
Agree with everything you just wrote, Matt. But I think your post focused disproportionately on the link bait aspect, which is why I had the reaction I did, and a few others seem to have as well.
I think your response to me sounds more like what I think of as Google’s attitude, which is that you become highly ranked by being an expert or “the best” at something. If his site’s content makes it persuasive that he’s the go-to chiropractor in San Diego, then by all means he should rank highly. I’d rather go to a doctor that makes me comfortable that he knows what he’s doing through his Web site content than a random Web site with a name, some clip art, and a list of services. (The stuff about putting the words “San Diego chiropractor” on your Web page if you want to rank for that search is obviously nothing to argue about.)
It sounds like we agree, but I think your post does make it seem as if he’s used some trickery unrelated to his core service in order to rank well for his desired search phrase. That’s the part that I think rubs your average searchers the wrong way (if they even understand it).
Hey Matt. I just recently watched the video on Viddler yesterday when it was featured on the home page. I watched the whole thing and learned a lot more than I already knew. Thanks for presenting the video!
Sly
I remember that session very well. One of the things he said stuck with me and I’ve followed his example on my floor plan pages. He said he had a surfer that was blind visit his site and loved it because the descriptions were so well written he knew exactly what everything was. Its funny the different things people have taken out of that conference.
Hmmm. I think I agree with Adam Jusko. There is something not quite right about all this cartooning and linkbaiting as the path to rankings.
Shouldn’t something like this rank well?
Other than Yelp’s increasingly atrocious link structure and architecture, of course. For individual business listings, they appear to have encoded strings as URL’s, with session ID’s thrown in for good measure. Even their hard-coded category pages seem unwieldy. But I digress.
I have a site that needs some updating. We are removing a product, and didn’t know how we should handle the redirect for the page (which has some pagerank). We can’t do a 301 because it is on a static html file under IIS. What would you recommend? I read meta refreshes are marked as spam and javascript refreshes can be as well, we just want the rank to pass, not the keywords.
I thought you said something very interesting at the very end of the 2nd video about WordPress not allowing PayPerPost – so I wrote a blog post about it today.
After about an hour a person (who appears to work for PPP) commented on my blog that I was a bit confused and that only applied to blogs on the WordPress.com domain. So I checked into it and it appears that he is correct.
I love to spin my blog post against my competitors (which they od course hate) so I couldn’t resist writing that post. 🙂
BTW, get video who ever filmed it.
Dave
Thanks for the slides. I’m glad you clarified a few things that have been circulating on the internet, for example, Google is now treating underscores the same as dashes, and Google will penalize your site if you have more than 2 dashes in the URL or whatever.
Regarding the use of good and creative (but totally unrelated) cartoons to promote a chiropractor website, maybe it is more reasonable for a blog, but does the same technique help content-rich websites? I’m interested in learning more about Google’s view of a site’s main topic vs. unrelated contents. If a site covers three separate topics A, B and C, will backlinks to B help the ranking of A and C pages as well? This will definitely be one factor in terms of building three niche websites or one that covers all three.
Thanks again. BTW, any chance your next blog will be about toolbar PR? Its purpose and usefulness? Even in or out?
Hart
Matt
“Harith, I’m comfortable with SEO being whitehat/blackhat; I don’t think you’d get many blackhats to say “I don’t do SEO; I do spam!” ”
Maybe within a year or so you would realize that the efforts of fighting SE spam need the collaboration of search engines and ethical SEOs. In fact ethical SEOs are the most “natural” partners of search engines.
As such associating something negative to the term SEO as blackhat wouldn’t encourage the said collaboration at all.
You may call me a dreamer but I do believe that at some point in near future both search engines and ethical SEOs would work together toward some kind of SEOs certification standards. Maybe an ethical SEO cerification badge would emerge.
Google is the leader of search and I wouldn’t be surprised to see Google inviting ethical SEOs to the first conference to work together to establishing Ethical SEO Certification Standards 🙂
Wow! There comments suggest there is not much of a middle ground here. My opinion, if he wants to post cartoons on his blog, where is the harm as long as they are not offensive. If someone else chooses to set up a link to those pictures from their blog, even yours Matt. Where is the harm? It’s your blog and you can link to whoever you want to with it. Thanks for the post Matt. It was a pretty entertaining read.
Hi Matt, First off, thanks for the link. 🙂
My apologies if you feel my coverage about the underscores wasn’t completely accurate. For the record, I never said that underscores were the same as dashes. Indeed, in your talk you recommend dashes/hyphens as the preferred method of separating words in URLs. Also for the record, what I said in my write-up was: “underscores in URLs are now (or at least very soon to be) treated as word separators by Google”. That was based on your statements in your talk (taken verbatim from the video recording of your talk, at approx. the 17 minute mark):
So I still don’t see where I misreported your announcement. Please clarify where I went astray. Thanks!
Thanks for the links and very good slides.
Many of web creators in my country prefer Black Hat SEO because they want to make more money without thinking about quality of contents or how long they will stay in SERPs.
I try not to do anything with black hat, although white hat is more difficult and take longer time. But with your suggestions and many of good articles, I think I will do White Hat SEO with good guidelines.
thanks so much.
Thanks for the free honest SEO tips not only for bloggers but also for webmasters and web publishers.
Thanks for the tips, Matt. I really enjoyed the video of your presentation that John put up on Viddler, and I’ve already begun to implement some changes on my site, based on your suggestions (only a few minutes after watching the video, in fact).
Thank You Matt !
You have really answered to my suggestion in your last article about WordCamp
I understand how keyword stuffing has influenced the google algo over the past several years especially the Jagger update. But, what happened to the hard line on link spam? Is there a major link spam update coming? Here is an example went from 26 BL’s to 862 BL’s in 4 months! I looked into it and a company called Text-Link Ads is selling links to this guy hand over fist. This company even published Link Buying guide! Of course Google Pr was a major selling point you can see it for yourself at. It is very hard building links and these link spam guys really get my goat.
Hi Matt, thanks for the post/presentation! I just installed some recomended plugins 🙂
I would like to ask you one question i simply can’t find an answer. With lots of links in the blogroll and throught a blog. What happens if a page has more then 100 links. do just the first 100 links get spidered by the google bot?
Just to follow up on one of the earliest comments, he uses WordPress and you have to use html for blockquotes as he does not have a bbs code added to the program ( I am almost sure)
Adaml
PS: I do see that it brings lots more people sending links, but not for the real reason of the site, does that matter?
PSS: I will read the rest of the comments now as well sorry if this is a dupe comment.
Morristown NJ Real Estate Guy, buying a house is a blizzard of crazy forms that a new buyer doesn’t understand. A series of posts like “What are the forms you sign when you buy a house?” would be great. Each post could be about one form and give a little background/history on why people have that form, when it started, etc.
For example, my wife and I just went through the process of selling our Honda Civic to someone, and I did a bunch of searches to find out “What needs to be done to sell a car?” There’s a bill of sale, the certificate of title, the odometer certification, the notice of release of liability which the seller mails to the DMV. It’s a hassle. The site that I ended up at did a really good job of walking through all of that, and probably got a lot of links as a result.
David, I would register your preference in the Google webmaster console *and* do 301s as well. The 301s will help other search engines.
Adam Jusko, I agree with your points. David Klein did a lot of on-topic stuff as well. I was this close to adding the link to David Klein’s two books that he wrote and put online about his area of expertise, but I was doing a lot of links to his site and didn’t want it to be rah rah link link to everything on his page. I could have pointed out more in the post that David also did a bunch of work to improve his site, including on-topic resources that also acted as extremely-relevant linkbait.
Sly from Slyvisions.com, glad if it helped. 🙂
Andrew Goodman, see my comment to Adam Jusko just above. In addition, your point about Yelp is what we refer to internally as the “grocery store” problem. If someone does the query “grocery store,” is it better to return lots of examples of grocery stores? Or is it better to return hub/directory sites that list grocery stores? Different people will have different preferences. Teoma/Ask leans much more toward the former, for example. I can respect that both can be useful, and a good result page might including a smattering of concrete sites + hub pages that point to concrete sites. Good question.
Dave Dugdale, when discussing PPP, the point I was making was that WordPress didn’t allow PPP on their own wordpress.com site.
Harith, we’ve discussed that topic within the Googleplex. My only point is that if you try to move “whitehat SEO vs. blackhat SEO” into “SEO vs. spam” then you’ll be trying to pry a bunch of people from one naming scheme to another, and quite a few won’t want to go. I view the terminology issue as orthogonal to the idea of agreeing on best practices or certification.
Stephan, I see where you’re coming from. Some people read your write-up and concluded that they were the same, but that doesn’t mean that you said it yourself. I’ll update my post.
Efren A., glad you enjoyed it!
Matt,
Fair enough. And thanks for taking the time to reply 😉
Btw, I have just finished reading this book, though in Danish. Highly recommended reading for both busy ethical SEOs as well as busy Googlers 🙂
Excellent post and links here Matt.
However I have a “beef” with the emphasis on linkbaiting and basic SEO as good ways to rise in the ranks (they ARE, but should not be). I’d argue that in an ideal search environment SEO would have effectively *zero* effect on ranks (because it’s communicating with the bot not the user), and linkbaiting things would have only a minor effect unless they were highly relevant to the query.
We now see a lot of SERPS where you see a bunch of sites, all similar, ranked more according to how their SEO, history, links, structure match Google’s expectations rather than how a user would view them. Google generally argues that these are essentially the same but they are probably only roughly correlated.
The fix for this would be greater transparency in the ranking process combined with greater penalties for being deceptive. If Google is going to aggressively defend the integrity of the algorithm the ranking process should be more accessible, especially to mom and pops who will increasingly flirt with disaster as they try to find ranking advantages.
No, they evolved out of greed, vested interest, and egomaniacism. There’s a difference.
Personally, I think the cartoon idea is cool. It’s like the whole Simpsonize Me thing.
Hi Matt
Great blog but (and of course there always is!) I have a couple of points.
1) I manage a site which sells cookware. We’re doing pretty well, lots of repeat custom etc etc, even some 1st place ratings in Googe for specific terms. Now, I could start a blog. I could write about cookware, after all I know a fair amount about it and I could tinker with keywords eg ‘cheese grater, cheese graters, graters, grater’ etc etc. But doesn’t that hit back at the heart of the original definition of ‘pagerank’.
I come from a scientific/academic background and I understand the concept of citations and I think using links as a form of online version of that makes sense. But one thing I do know is that when I produced my papers my tutors weren’t interested in 1000 references that I’d pulled the odd word from, what they were interested in is my using 100 references which made sense.
2) The products my site sells are largely ‘everyday’ items. Take my cheese grater example. I could write the following:
‘Stainless steel box cheese grater, measures 20cm’ or I can write
‘This marvellous stainless cheese grater is a king amongst cheese graters. This cheese grater measures a useful 20cm in the finest grade stainless steel. You can use any of our cheese graters to grate cheese and all manner of other food stuff. Use our grater and you will be sure to have the greatest cheese ever.’
Speaking personally, if I’m buying a cheese grater I don’t want or need the word(s) repeated 20 times in the description. I want a great image and I want a brief description which tells me what its made of and its dimensions.
So, on my site, do I write content for a busy user who wants to choose between the 20 different cheese graters we sell or do I write content that will suit a search engine?
PS: While the example is somwhat tongue in cheek I really would be interested to hear thoughts on this.
That wouldn’t benefit Google’s users and would only help the GIANTS over the small. Mom & Pop sites in Google have a level & objective playing field already. I see pages from Mom & Pop sites out ranking, or VERY close behind the GIANTS all the time. No site NEEDS to “flirt with disaster” in order to rank well, it takes common sense, a good grasp of the said topic and out-of-the-box thinking. There is only 10 spots on page 1, 2….
The aim should be to become THE site on the chosen topic. NEVER rely on a few pages for the bulk of traffic, rely on a few hundred/thousand (blogs, forums etc). That, combined good old fashioned hard work, which many Webmasters are adverse to.
I guess it’s human nature to want a free ride, magic pills and tools etc, whether it be weight loss or ranking. TIME TO WAKE UP A SMELL THE COFFEE 🙂
Great PPT Matt, it was good to see everything I had done for my blog be roughly what you prescribe. Personally though I’m a write it custom or go home kinda guy. Cheers.
Matt, you mention on slide #25:
“Don’t use sponsored theme – can lose all your trust in different search engines.”
What exactly do you mean by sponsored theme? To avoid themes that have a link back to the designers home page? (they ALL want it 😉 )
Matt, great stuff. Very informative. But that’s what you’re all about :p
SEarCHEnGinESWEB
[quote]
SearchEnginesWeb is quite aware of what you and the rest of the Google Engineers are saying about these passionate posts and incessant pleas for mutual understanding.[/quote]
Dude. Stop talking about yourself in 3rd person. Seriously. I see you lurking Matt’s blog on just about every post the guy makes. Let him do his job, and you do whatever it is you do for a living. Thanks.
Thanks for working to get the PowerPoint released. I saw the presentation and was hoping I’d be able to see the slides again.
thank you for your great tips.
now i understand how much more i need to learn
Seriously, if all you are going to do is answer the questions from your buddies and SEO A-listers why even bother posting on your blog? I’d just send a bulk email to all your friends, then you don’t need to bother ignoring all of the actual questions from real people. If I, “joe-six-pack” toss you some softball questions will you answer them? NOT! Will you ignore them because I don’t kiss your ego every day on my blog?
How about you step up and answer the real meaty questions and ignore who asked them. Pathetic.
Hey Matt
I found your mom’s blog and website. She is doing a great charity work. Power to her! You must be a proud son.
Don’t you think the cause she is working for deserves some visibility in your next post introducing her blog and site 😉
Mr. David Klein had even StreetView photographed is office 😉
Sorry..
The link went bad..
Thanks for the power point and was good to see the video. Thanks for the tips for writing content 🙂
The Power Point presentation was really helpful. Thanks for motivating me into finding new SEO ideas! I was getting stale.
Kind Regards
Great info Matt….cheers 🙂
Great post, Matt
Thanks for sharing!!
I just read Stephanie Booth’s write-up of the session, and learn the PPT. It was great. Thank you very much.
Sorry to hear that your back is still bad enough to need the frozen veg treatment. I put out my back a couple of times, lifting my small kids… look after yourself – trying to get back to work and going mobile too quickly can slow the whole healing process, IME. FWIW, I’m typing this on my back having injured my knee – and I failed to take my own advice and delaying full recovery.
IMO, Adam Jusko and Andrew Goodman are on the right track, and I think you’ve slightly sidestepped the issue. It’s actually pretty crucial, and is part of the reason for the success of at least smudged-hat techniques.
Because Google uses a citation model, but doesn’t pay so much attention to relevance, or even whether the content is human-derived, it encourages the generation of irrelevant or only marginally relevant content. The ultimate expression of that is the automated generation of entire sites through AI spawned text or scraping, RSS snippet capture, and the automated submission of high entropy text to blogs, forums and even webmail enquiry forms with embedded links to attempt to defeat Bayesian and simple spam rejection tools. Interesting comments on “Lambda The Ultimate” about this ().
The effect of Google’s ranking model is that businesses do expend effort that isn’t directly relevant to user needs. Example: take a competitive term. Imagine that you blog about it constantly, and gain readership and links. Your competitors will then use grey or black hat techniques, web and blog spam, machine generated sites on aged domains, etc… Google respects these and so the business doing the right things, now has to consider doing stuff that is not directly anything to do with the business or in the interests of users.
If you explain the evolution of the strategy, the obvious question for the marketing director of the client business is “well, we shouldn’t blog – let’s cut that activity and just pay for links”. It’s really hard to resist this and I’m becoming less and less convinced that I should. If *my* competitor can promise that the client will get ranking, without the effort to write about the business (which has a pretty high cost and may have only marginal utility to users and the business), then the economics will push the client towards a darker route for ranking. And everyone involved with administering the web faces higher costs because Google believes spam submitted to blogs and fora, and duplicated content aged sites with high entropy differentiation text (e.g. the MFA site with RSS choice).
The Google guidelines are pretty good, but the algorithm doesn’t encourage the right behaviour, and web/link spam detection appears insufficiently severe. I’ve written this up in more detail, a few weeks ago, as – yeah, linkbait…
Cheers, JeremyC.
Thanks for the tips!
Would you say your math spam protection is more efficient than captchas? (at least they’re much more readable!)
Being an ardent Blogger user, I am a little bit jealous that WordPress guys get to talk to/listen to/read you but not us Blogger guys.
Blogger widgets yet don’t cover spam (like Akismet), there is no widget for title switch that you mentioned in your presentation, and the templates I am not sure are good enough for bigger computer screens?
So I guess my question is when are you going to talk about Blogger like that?
So the secret is to appease google search engineers?
Hi Matt:
Thanks for all the great information. It’s great to hear this kind of information from you. When I hear this kind of thing from one the million “SEO experts” out there – I never truly know how accurate it is. SEO for a beginner like myself can really be frustrating in that way.
Hey Matt,
My name is Orie Roberts, I am actually the cartoonist for Dr. David Klein and I really appreciate the stance you have taken on our efforts at WordCamp. Ever since I have started my work for him we have been continually brain storming new ways for our site to be seen and I have learned a lot in the process.
I think the thing that a lot of people miss by not knowing him and our practice is that at the root of all these creative ideas and SEO tactics isn’t financial, by doing this his ultimate goal is to help as many people as he can. Our office is a great environment for our patients and has continually produced healthy and happy people. For everyone that is worried about a bad chiropractor getting all of this exposure because of some cartoons, put your worries to rest. There is only good that can come from this, as more people learn about our office the more people can be helped.
Dr. Klein has worked tirelessly in the area of internet marketing, and most of the content is completely linked to chiropractic information, this was just a great idea that worked out better than we could have imagined. It was creative simple and wasn’t forced upon anyone to look at or link to. If it makes people happy seeing their cartoons then i don’t see much harm in it. I thank everyone for their input and I’m glad that our ideas have found their way into your discussions.
It seems Matt is at an all-week offsite with his team 😉
Hi Matt:
Great post Matt and thanks for the powerpoint presentation…‼
Best Regards.
Matt, your PPT answered a lot of questions about WordPress that I’ve had. However, I have a question in reference to the way wordpress categorizes posts. Is Google going to have a problem with a post being in multiple categories. Technically this is creating duplicate content, and an article may fall into many categories.
Will Google penalized for this?
The same holds true for article directories as well does it not? If I publish an article on my site or blog and also submit it to a free trading directory giving rights up for it to be republished, how does Google see this?
Thank you so much for your insight!
Thanks Matt. Very useful power point presentation for white hat seo even though it simple.
Waiting more tips from you 😉
Matt-
Thanks for posting this up. Very interesting and fun indeed.
Matt – Thanks for the post. The slideshow was very educational. I’ve split my urls with some being www and some not; I’m not to have to fix that now…
Thanks again!
Hi Matt,
Can you tell me if Google is (already) following the approach for blog rankings suggested in the articles below? And if so, what implications does this have for optimizing blogs?
New Metrics for Newsblog Credibility – Brian Ulicny, Ken Baclawski
New Metrics for Blog Mining – Brian Ulicny, Ken Baclawski, Amy Magnus
Hi Matt. First of all, great, great article.
Second: GOOGLE HATES ME!!!
Ok, probably no, probably just happen that I don’t do something very well so the pagerank of my blog is stuck, even if I had more and more incoming links.
I know you are a very busy man, so I will going straight to the the point, and I will try to put my question in a way you can just respond selecting one option.
There are two things that perhaps make my page rank drop a little. One is duplicate content, subject that you talk briefly in your conference, and it seems that you want to talk some more, but sadly didn’t happen 🙁
So this is the first question: Should I block in my robots.txt all the url of my wordpress tags, archive, category, etc to avoid all duplicate content? Or should I take advantage of the keywords in the url that those url offer me, and trust that google will “know” what happen?
And the second question: What is best to google? Keep the html structure as it come in most wordpress themes (Blog Title=h1, post titles=h2, sidebar titles=h3, etc) or change it to, for example, single post title=h1, blog description=h2, sidebar titles to h5 or so, etc?
Ok, that’s all. Believe me, is not that I don’t search this information. I search and I find so much (contradictory) information, that is very hard to choose what option is the right one. So that’s why I choose to go directly to the source.
Thank you very much.
PD. Yes, I know, my english is not perfect 🙁
I always thought a tosser was a sex fiend in British slang. I guess that’s what I get for watching Showcase.
I really liked your presentation….
But Matt, this post was toooo long…If i took time to read this whole one I couldnt read the rest.
Thanks Matt,
Nice Post and PPT =)
Hi Matt,
I was just wondering why you use WordPress instead of Google’s own Blogger. Do WordPress blogs get ranked higher than blogspot blogs? I’ve got a blogspot blog (see above) but use my own domain name for it. Is there anything inherent within a WordPress blog that brings in more traffic? And if there is, is Google doing anything to improve the blogspot blogs? Thanks. Vic
Underscore vs. hyphen is a done deal,
Craig
Great post thanks for the PPT!
Hi Matt,
I’ve a question for you, maybe it’s a stupid one but I’m quite curious about it.
If on my blog I schedule the posts to be published at fixed intervals (for example, one post every day at 9:00), could Google guess that my blog has been created only for positioning reasons and therefore, is there the risk that my blog could be considered spam and be penalized? Or instead, the fixed frequency in posting doesn’t have any meaning for Google?
Thanks in advance for your help
Kind regards
Matt, I like you are posting the secrets lol. But explain this one then?
why is better than?
looks like google likes directories, because this is pure a directory and not a page.
wish i could get your comment on it? i know out of expierence that your hints in the powerpoint presentation are right, but this one i could not understand.
Fantastic post. This will be useful to bloggers and webmasters as they can learn a lot from this.
2,890 on Alexa ! excellent blog Matt…How do you do it?
Amazing work…
Best Regards,
Sajjid Manuel
If you don’t have much time seeing the full video or reading the whole script, read the simplified summary I prepared:
Please add the important points I missed in the comment area. Thanks.
Hello Matts,
Nice tips…
Thanx to Dr Andy Williams to direct me to this page.
Anish
Hello
I do not know if this is the right place to post but here goes 🙂
I have been a webmaster since 1998 and have worked very hard to create a quality website that has a ton of content and many community features. In the past year I have seen inferior websites rise to the top of search keywords who have completely disregarded any quality guidelines and utilize many black hat tricks , with no obvious penalty
or loss of pr or organic keyword placement. I have also been the victim of false paid link reports (apparently a competing website using my url in link schemes ), copyright infringement, proxy highjacking and outright blatant hack attempts that have taken down my server even though I have changed my dedicated server 3 times in the last 12 months.
What can a legitimate website owner do to ensure that they are not victims of hackers that proxy highjack ( I have reported these urls to google twice and I still see my entire website title, description and all in my inurl results) , webmasters that make false reports or add your url without permission to link schemes and people who steal your content with no remorse ? I feel like a one woman cyber cop at times… Obvioulsy this is an unanswerable question … as the web is to big to police … but it is very frustrating for me : ) but alas this is my job how I feed my family and my chosen path in life.
So I will continue to put my white hat on in the morning and do my best to keep creating a quality well designed websites in my little corner of cyberspace.
Thanks for all of the great info in this blog post Matt … sorry for venting but I am very upset over the blatant black hat seo that goes on !
Thanks for all of the infos & discussions in your blog Matt … a very usefull lecture for me 😉
Best Regards from europe
Nathalie Laurent aka N-at-Work
This awesome power point presentation! This is what a beginner need to know about SEO. Thanks Matt!
This is a very interesting post. Man I learn a lot from your blog. Thanks for the hard work!
*** “Harith, I’m comfortable with SEO being whitehat/blackhat; I don’t think you’d get many blackhats to say “I don’t do SEO; I do spam!” ***
I am sure that you will not, in just the same way that a con-man is always going to insist that he is a legitimate business owner.
Hi Matt,
This thread and all the other useful stuff you post has inspired me to add a blog to our “boring” B2B ecommerce site.
Playing with WordPress and all the cool plugins is fun too 🙂
I’m really excited about the opportunities and I’m fizzing with ideas for posts that I know our customers will find useful – albeit in a very narrow niche market that the wider blogging community will not be so interested in!
With all these possibilities to hand it beats me why anyone feels the need to engage in black hat stuff – the “Dark Side” never wins in the long term.
May The Force be with you……….:)
Great stuff. To me SEO comes down to:
1.Valid HTML and valid CSS
2.Keyword Research and content that matches your research
3.Quality inbound links.
There is no reason to do anything but white hat SEO. Why bother with all that junk when SEO is really about quality content and quality links.
I watched your session from the WordCamp conference on the official website and really enjoyed it. I’ve even written a post about it. 🙂
There are too many so called experts and also books about SEO, it’s really a jungle. Some of the info in these books may be true, but in reality, I don’t think one needs more than a copy of your PowerPoint show.
The most reliable source of info for a topic like this is someone from Google – it has to be. Thanks a lot for sharing this info with us.
Thanks for the excellent post Matt. I think I can shift my blog to another domain now 🙂
Cheers,
Paul
Our wiccan/pagan online store needed some ‘white hat link bait’. As serendipity would have it, a group of local pagans was trying to build a “Pagan Talking Dictionary” , but needed hosting space and technical assistance.
Since most Pagans are self-taught through books and the internet, pronunciation of magical terms with Hebrew, Latin, Welsh, and Sanskrit roots was a problem for many. We sponsored the dictionary (it really is pretty cool), at . It not only pronounces difficult words (like “Athame”, and “Samhain”), but the syllables actually seem to ‘swell-up’ as the word is pronounced.
We sent out a few hundred press releases (online and via snail mail), and our hit rate went through the roof. We also gained hundreds of inbound links. At the same time we helped to create a genuinely valuable resource for the community.
‘White Hat’ tactics are the only way to get hits and links without regrets!!
-bob
This is still one of the most referenced articles in my bookmarks. I have written an article called 50 Easy Tips to Keep your Blog Search Engine Optimized, at and linked to this post as a reference. Take a look!
Thanks,
Brian
Nice article Matt. I will be applying this idea on my new marketing blog. Cheers 🙂 And thanks Brian Whaley for the link. that was a great read infact.
The power point presentation is awesome.. Thanks Matt..
Now that was a superb collection of SEO tips for a blogger. Very good specially if you use a Google Blogger
Found this via bloggingtips.com, useful tips!
Hi Matt
I am still learning. Over the last few days I came to your blog and you really have alot of great information. Well I guess I would not expect anything less. Thank you for playing such a great role in my learning process
Have an abseolutely exseollent year.
Matt you have done excellent job by providing these tips, but i think it need a bit more explanation in order to benefit the freshers.
Hi Matt
Have heard much about you but have never found this blog before!
You give some very useful tips here, I have added this to my favourites, will give it a good read every now and again.
My SEO left me therefore am on my own, so could do with all the help I can get. One thing you do say is 100% correct, anybody can do SEO as long as it is done the right way.
Glad I found your site, i’m sure there will be plenty of more tips to be found. Wish me luck to get to the top!
Asif
Great tips matt !!
Wow, very great tips. I will use this for my blog. Thanks Matt 🙂
I was very impressed by your talk and it definitely helped out a lot. I especially liked how you went out of your way to send some great vibes David Klein’s way. I looked over his site and he’s done a great job with it.
Thanks for the multiple links to summaries of your presentation. For us poor and over worked white hats, this is great information.
Matt, great tips and info, I’m as everybody always have good things to learn from your blog.
In the end it comes down to the old mantra about quality content. Thanks once again Matt.
Matt, thank you for your concise presentation. As an admittedly semi-new-to-the-online-writing-world writer, it is very much appreciated. Bookmarked.
ProCW
Hi Matt, just tumbled across your site when searching on google for underscore vs. hyphens in preparation for creating a personal url for my Twitter and LinkedIn pages. You say that hypens are best and that no spaces are worst for searchability, yet this website and both your Twitter and FriendFeed urls have no spaces… why?!
Thanks
Jon
Hey Matt,
As usual, your tips are simple and rich at the same time. It must be Ozzie’s supervision… Cheers!
I think using cartoons is a wonderful idea, what fantastic thinking! Nive to hear you (Matt) are proud of the fact the chiropractor in question was inspired in such a way WTG!
Matt Cutts – on the subject of cartoons would you or Google have any problem with a website using cartoon strips to advertise other Businesses?
The reason I ask is because I have registered a TM in the UK and it is all about using some teddy bear characters called the Double T Ted’s to advertise products/services and of course the relevant URL’s on websites using five plate cartoon strips initially on TVWorlds forum as it is our busiest site as far as I am presently aware.
I can show you an example of the plan on another site if you are interested in seeing what I have in mind and need or want to know more to answer properly?
White Hat SEO Technique is for Long Term, but other Bloggers difficult to focused at this one, instead they are using of black hat seo.
White Hat SEO is really just common sense in some ways. The problem is when you try White Hat and you still get nowhere or even worse when you are penalized with no explanation. There is no worse feeling than when you were ranking pretty good with a site that you work really hard at and it gets spanked. This punishment by the search engines is the tipping point that sends many webmasters over to the dark side of Black Hat.
Oh well, many of SEOs cant able to get their websites to the top without any doing of dirty tricks, Matt Cutts teach us on how we can use Long Term and safe optimization Process….
Hey Matt it seems that you are great as a writer :). Apart from jokes, it’s nice to read about such bloggers who are so innovative and passionate about their blogs. And now a days it’s must for every blogger to learn something about seo.
Hi Matt,
Thanks for such a lovely post. However, going through your presentation I have question to ask you. You asked the users for prevention of same content on different pages. In this regard, a certain question arises about submitting articles to different article directories. I think most of the people will be benefited with this answer on how to prevent duplicate content (if at all) by submitting an article to different article directory
Think this is one great read.
Some bloggers look only to short term, and want hits now, and dont care how they get them.
Faster you get traffic, faster you loose it in my book.
I also think that using short term tactics will give you a short term blog, and no return.
Put the time in, and get the right content, get good content, and get a following, and then you’ll get some place.
I have tried these get traffic fast methods, and they have ended up doing way more harm than good.
I enjoy following what you have to say Matt. I wish you would have attended the denver wordcamp earlier this year. I like your style of writing and I hope you will continue to make more Matt Cutts videos! If you ever need a job, we’re hiring!
denver seo, USWebCentral.com
Great post Matt as always. Still shows the same old adage, the simplest ideas are always the most effective…its just the thinking of them which proves more difficult!
Here are a couple tools to improving your SEO. Go to Spyfu and Keyword Elite that should be a good start in researching keywords in your niche. There are so many ways to really get ranking. I am a true believer in tools to help you get the job done.
Let me know if you like more tips or tools.
Later
Vanjuan Vladimirov
I dont understand why use .htaccess at wp-admin ??
This is an awesome post! I really enjoyed the Wordcamp 09 presentation. I have picked up some great ideas from the two presentations. Thanks Matt.
Guessing that a regular guy can achieve as much as a so called proffessional I attempted doing seo on my own site. I tried a number of seo’s who seemed to do very little! I have learnt quiet a lot and am now ranking on the first page for terms like cheap printing and even printing! Suprising seen as 6 months ago I knew……. NOTHING!
Hi Matt
Thanks for sharing SEO tips.However, it seems these tips are in theory. I have always seen some of the websites artificially optimized fro SEO and Google displays top results on Ist page. For example, eleapsoftware.com is a website that sucks in its content and evaluate the entire site from SEO perspective you’ll get to know how these guys have used blackhat technique , keyword stuffing and double key phrases inside the URLs. I have brought this matter to Google many times yet to no avail.
I always find such distracting website intentionality optimized to cheat on Google and the soc called Google gets cheated despite ifs and buts rules…..r u listening?
Its a nice idea on to put notepad in creating on it. this maybe an easier way to create something like that, and it would help so much in your doing.
If you are used with white hat techniques then that would be great for long term relationship with your SEO Projects. 🙂 thanks Matt Cutts.
If you are using black hat make sure that your seo client dont know what you are doing because once they will know your secret then you will get into trouble. If you are using white hat then no worries, you will make your seo world as happy 🙂
Thanks for the free honest SEO tips not only for bloggers but also for webmasters and web publishers.
Adding really valuable content, well thought off internal linking, site structure, AND a lot of external references to your site is the only way to rank consistently in the long run. Of course, if you do not have patience and the budget, do not even start!
You are missing the big picture:
Don’t be blackhat, play by the rules.
If people can’t make time to watch an hour long video, then SEO and blogging might not be good for them to spend time on.
Go for White Hat. Not only because you’ll get a Google slap, but just because otherwise, you’re compromising your own work if you use Black hat techniques.
White hat tactics are easier to use and tend to last much longer too. I never understood the point of black hat tactics. Your gains are short lived, and you spend all day trying to hide what you’re doing. If you devote the same effort to white hat tactics you’d be light years ahead.
Yeah it definately helps to play by the rules. When Google changes their search algorithym even slightly, you are out of luck if you went the black hat way. Here is a great cartoon that illustrates this.
I would like to clear something up. I understand that article spinning, using software that really destroys the readability of the article – or just renders it not-understandable, is bad. But what about manually entering different possibilities of sentences/words/paragraphs to make several ways to say the same thing? I don’t think there’s anything morally wrong with that, as in this case – I’d be trying to reach out to as many article directories as possible – as not everyone follows the same ones. But they often check for plagiarism from others, hence the need for spinning.
So is this penalized in Google? Isn’t this white-hat? If it’s readable, valuable content, etc.
Of course I don’t simply use the raw data, I usually read through, make changes, etc. So as to keep it’s value.
Please let me know!
I’ve been researching a number of sites to see who links into them – having seen comments for a number of the sites I’m researching from this very blog post I thought I’d check it out.
I’m curious Matt, do you review the people who comment on your blog to see if they are blog spamming as well? I was a little worried about putting my site in the website field but figured it was worth the risk to get an answer.
You do great work and we appreciate it – we’ve been fighting the stigma of seo’s who are really just looking for the short cuts (and they subsequently hurt their client’s business) rather than working with you in order to help the results be more relevant so that people who are actually INTERESTED in our pages are finding the right content.
Thanks! 🙂
White Hat techniques are the only way to guarantee on going sales and traffic figures. There is no point in trying to play with Google, you just have to stick to the rules. When your competitors try to use Black Hat they will soon be tripped up by the Google Algorithm!
hii Matt cutt one question for u.
is this true for Blog commenting
In my view there are money makers and there are business builders. Those who use black hat tactics are just a flash in the pan. Those of us doing things the right way will stand the test of time.
I was actually wondering the same thing as Paul Benoit above. I came across this particular post as I was searching the backlinks of a few of my client’s sites. This actually proved to be a great lesson in white hat SEO and I’m glad I stumbled upon it. I wish I would have found this sooner before I migrated a 580-page site over from underscores to dashes! Argh, oh well. Thanks for the solid 411.
Although it’s an old post I guess the advice is more relevant than ever – especially after the recent Panda update…
I think it is hysterical taht a black hat SEO has come to this forum to get a link. Wow Matt things must have really been cut in your engineering department. When site A lets call it “l8m.org” 301 redirects to site B with stealth DNS. And, then site B gets “authority links” from sites like “” and from comment spam like “” or the 500 other spam link blog comments that site B posted. I say oh just another black hate SEO trying to beat the index. But when site B lets call it “psychicreviewonline.com” gets a number 1 rank in Google. Something is truly awry in the search engineering department. These archaic black hat SEO techniques really need to be revisited, in a big way. Oh by the way it is truly ironic that site B posted about white hat Seo on this very blog post. I am surprised it did not burst into flames after that burner posted (lol).
I am also sad to hear about the inabilty to flag spam links tha Black Hat SEO’s like to use to disparrigae reputable sites (You know the type GotLinks, Telalinks…). I tried to make sure I blocked any site like this in my .htaccess and in my firewall, but I am not sure that actually works to block incoming bots from following links to my site. Anyhow, good luck with the hiring Matt! I know I am not a perfect web master, but at least I try to play by the rules.
There is a lot of controversy about whether Black Hat SEO is really “bad” in the ethical sense.
This is very informative post. I like the way you defined the material and that makes your post more interesting and easy to understand. I would conclude my words by just saying three words “well done Matt”.
white hat seo may take some time to show its results but it is more effective than black hat…
Matt, thank you so much. You’ve helped me tremendously in formulating my own ideas for posts. I truly owe you! 🙂 You should get a donation button.
I love the whitehat methods, these are very good!
There is a lot of controversy about whether Black Hat SEO is really “bad” in the ethical sense.
Thanks Matt. Your blog helped me a lot.
I built website for my start-up company (internet marketing and social media consulting). I installed blog and attached it to my company domain.
With 3 months, I had been appearing in 1st page of Google results for some keywords. Now after almost year, most keywords searches show my website or blog within 1st page of results.
My investment in the blog content paid its ROI quickly and effectively. | https://www.mattcutts.com/blog/whitehat-seo-tips-for-bloggers/ | CC-MAIN-2018-17 | refinedweb | 13,738 | 79.8 |
28 December 2011 16:25 [Source: ICIS news]
LONDON (ICIS)--?xml:namespace>
The KOF economics research institute at the ETH
“This suggests that Swiss economic growth on a year-on-year perspective is going to stagnate over the first months of 2012,” the institute said.
The KOF indicator has been falling since May 2011.
The technical indicator aims to estimate how the Swiss economy will perform in the next three to six months. It is comprised of 25 “multi-sectoral bundled individual indicators.” The indicator’s key measurements include Swiss industry performance, Swiss consumption rates, and Swiss exports to the EU.
Earlier this month, KOF said the Swiss economy would develop “at a snail's pace” in 2012, with year-on-year GDP growth of only 0.2%, as the eurozone debt crisis and its consequences stifled demand worldwide.
During the winter quarters – the 2011 fourth and 2012 first quarter -
The institute predicted 13,000 jobs losses by the end of the second quarter of 2012.
It also warned of continuing effects from the strong Swiss franc on
In a related development, Switzerland-based independent refiner Petroplus said this week its lenders froze about $1bn (€770m) in uncommitted credit lines that are “critical” to the firms’ continued operations.
( | http://www.icis.com/Articles/2011/12/28/9519374/swiss-economy-to-stagnate-in-coming-months-institute.html | CC-MAIN-2015-11 | refinedweb | 208 | 51.68 |
One of the things distinguishing Jamstack sites from plain static sites is their use of data from APIs.
While a traditional static site might use file-based data like Markdown and YAML, a Jamstack site frequently uses things like a headless CMS, headless ecommerce or third-party APIs. Headless CMS and API-driven services like Algolia fill many needs but are built for particular purposes. Your Jamstack site might need to store and access data that doesn't fit into the CMS archetype, for instance. In those cases, you might need a... database!
Fauna is one solid option. It is a cloud-based transactional serverless database that makes that data available via a data API. This makes it ideal for use in a Jamstack application.
A great piece about FaunaDB with its CEO here.
This article will explore how to get started using FaunaDB and Next.js to connect a database to a Jamstack site built in the React framework.
We'll cover:
More about serverless architectures here
Setting up FaunaDB
Fauna databases provide many ways to get started. You can use the web-based admin to create and manage new databases. However, you can also do most actions via the Fauna Shell, a CLI for interacting with Fauna, which is what we'll use for this tutorial.
npm install -g fauna-shell
Now we can log in.
fauna cloud-login
You'll need to enter your email and password. If you signed up using third-party authentication like Netlify or GitHub, you need to create the database via the web admin and get a security key in the security tab of the database.
Fauna documentation about cloud-login here
We'll create a simple application using Next.js that will be a list of shows that I want to watch. Let's create a new database to store this data.
fauna create-database my_shows
At this point, we can use the shell to interact with the database and create new collections, which are Fauna's equivalent of a table.
fauna shell my_shows
You should see something like the following:
Starting shell for database my_shows Connected to Type Ctrl + D or .exit to exit the shell my_shows>
Using FQL (Fauna Query Language) to create and query data
Once inside the shell, you can interact with your new database using FQL (Fauna Query Language). FQL is essentially Fauna's API language for creating, updating, and querying data. However, it isn't an API in the way you're probably used to using one. It includes things like data types, built in functions and even user defined functions that make it feel more like a programming language than a typical API. There's a lot you can do with FQL, more than we can cover in-depth here. Be sure to refer to the documentation for a full overview.
Let's start by creating a collection called "shows."
CreateCollection({ name: "shows" })
A collection in Fauna stores documents. If you are more comfortable with a traditional relational database model, you can think of these as table rows. We could create a single document using the
Create() method, but instead, populate multiple documents using the
Map() method. We'll map over a nested array of values. Each of the nested arrays represents the values of one document. We'll use these to populate the two properties in our document,
title and
watched. For now, we'll set
watched on all these dummy items to
false to indicate we have not yet watched them.
Map( [ ["Kim's Convenience",false], ["I'm Sorry",false], ["The Good Place",false] ], Lambda(["title","watched"], Create( Collection("shows"), { data: { title: Var("title"), watched: Var("watched")} } ) ) )
Lastly, let's query for all the documents in our "shows" collection. In this case, we'll use
Collection() to define which collection we are pulling from,
Documents() to say that we want all the references to each document in our shows collection, and then
Paginate() to convert these references to Page objects. Each page will be passed to the
Lambda() function, where they will be used to
Get() the full record.
Map( Paginate(Documents(Collection("shows"))), Lambda(show => Get(show)) )
You should see a result like:
{ data: [ { ref: Ref(Collection("shows"), "293065998672593408"), ts: 1615748366168000, data: { title: "I'm Sorry", watched: false } }, { ref: Ref(Collection("shows"), "293065998672594432"), ts: 1615748366168000, data: { title: 'The Good Place', watched: false } }, { ref: Ref(Collection("shows"), "293065998672595456"), ts: 1615748366168000, data: { title: "Kim's Convenience", watched: false } } ] }
Finally, before we move on, we should create an index for this collection. Among other things, the index will make it easier to locate a document, updating the records easier.
CreateIndex({ name: "shows_by_title", source: Collection("shows"), terms: [{ field: ["data", "title"] }] })
Now that we have our database created and populated let's move to use it within a Next.js app.
Getting data in Next.js with FaunaDB
We're going to walk through creating a simple web app using Next.js that uses our Fauna table to allow us to add shows we want to watch and mark the shows we've watched as done. This will demonstrate how to read data from Fauna and display it in Next.js, create new records in Fauna, and update an existing record.
The code for this sample is available in GitHub. It borrows the layout from this CodePen. You can see what the app looks like below.
To use the sample yourself, you'll need to provide a
.env file with a value for
FAUNADB_SECRET that contains a key from Fauna to connect to your
shows collection. To obtain a key, go to the "Security" tab within your collection on the Fauna dashboard and create a new key.
We won't cover every detail of building a Next.js app here as it is just a single page. We'll explore some of the basic pieces that you need to understand to use Fauna.
You can follow this tutorial from Vercel to get started with Next.js
Fauna JavaScript driver
To query Fauna within our app, we're going to use the Fauna JavaScript driver. This is a Node.js library for integrating with Fauna. It allows you to run the same FQL queries that we ran within the Fauna Shell from your Node application. To add this to a new Next.js application, you need to run:
npm install faunadb
Within Node, you need to instantiate the client with your Fauna key. We can do this from within a
/lib/fauna.js file that we will include wherever we need to access data in Fauna. It gets the key from an environment variable called
FAUNADB_SECRET that is within a
.env.local file.
import faunadb from 'faunadb'; export const faunaClient = new faunadb.Client({ secret: process.env.FAUNADB_SECRET, });
Protecting your API key
Before we begin getting data, there's one area of concern. Since our application data is all user-generated, it is getting all of its Fauna data client-side rather than at build time. This means that anyone inspecting the API call would have access to the Fauna key.
There are two ways to handle this:
- Create a key that has very restricted permissions set within the Fauna dashboard to limit misuse.
This still exposes the key but limits the potential for misuse. It's handy if you are reading data and limit the key to read-only.
- Create a serverless function that is an intermediary for calling the Fauna API, thereby hiding your key entirely.
This is the more secure option because it never exposes the key at all. Users can still call the endpoint if they inspect how, but the API limits what they can do.
Luckily, within Next.js, there is an easy way to accomplish the second option by using Nextjs API routes.
All of the interaction with Fauna within this sample app will go through one of three API routes:
getShows;
addShows; or
updateShows.
Getting data from Fauna database
From a Fauna Query Language standpoint, reading data from Fauna is pretty straightforward. We'll use the same
Map() function we used within the Fauna Shell earlier. We need to do it in the context of the client that we instantiated earlier.
The methods are all derived from an instance of the
query object from the Fauna JavaScript driver. Otherwise, the query itself is the same.
import { query as q } from 'faunadb'; import { faunaClient } from '../../lib/fauna'; export default async (req, res) => { if (req.method == 'GET') { let query = await faunaClient.query( q.Map( q.Paginate(q.Documents(q.Collection('shows'))), q.Lambda((show) => q.Get(show)) ) ); res.status(200).json({ data: query.data }); } };
To call this from within our app when the page loads, we'll first instantiate a new state variable with our shows array:
let [shows, setShows] = useState([]);
Then from within the
useEffect React hook, we can call the API endpoint and populate the results with the data returned from Fauna.
useEffect(async () => { let showData = await fetcher('/api/getShows'); setShows(showData.data); }, []);
Adding data to FaunaDB
Next, let's look at the
createShows API endpoint. To add a single row to our
shows collection, we'll use the
Create() method within FQL. We provide it an instance of the collection we are writing to and a structure containing the data we want to write.
export default async (req, res) => { if (req.method == 'POST') { const body = JSON.parse(req.body); let query = await faunaClient.query( q.Create(q.Collection('shows'), { data: { title: body.title, watched: false }, }) ); res.status(200).json({ data: query }); } };
We're defaulting a new show to
watched: false but populating the title with whatever is passed.
(Note: for the sake of simplicity, I have not added a lot of error checking to this application, meaning calling this method without a title will fail).
Now let's use this API endpoint by first instantiating another state variable to hold the new show data entered into the form.
let [newShow, setNewShow] = useState('');
We also need to add a function that will be the
onChange handler for the form input.
function handleNewShow(e) { setNewShow(e.target.value); }
Finally, we need a method to handle when the user clicks on the "Add" button to submit a new show. This method calls our
addShows API endpoint. That endpoint returns the new show data that was just added to Fauna.
We then append that to the array of shows so that our UI will update with the show we just added.
Finally, we clear the form input by emptying the value of the
newShow state variable.
async function handleAddShow() { const res = await fetch('/api/addShows', { method: 'POST', body: JSON.stringify({ title: newShow, }), }); const body = await res.json(); // add the new show to the existing list let newShows = shows.slice(); newShows.push(body.data); setShows(newShows); setNewShow(''); }
Updating data in Fauna
Finally, we want to be able to check and uncheck a show as having been watched. To do that, we need to update a record in Fauna.
This is where the index we added earlier will come in handy as it allows us to easily get a reference to the record using the show title. We use that reference to get an instance of the record and then update the record with the new data, which is watched as either true or false.
export default async (req, res) => { if (req.method == 'POST') { const body = JSON.parse(req.body); let query = await faunaClient.query( q.Update( q.Select( ['ref'], q.Get(q.Match(q.Index('shows_by_title'), body.title)) ), { data: { watched: body.watched, }, } ) ); res.status(200).json({ data: query }); } };
Next, we'll add a click handler for the checkbox inputs that will call the
updateShow API endpoint.
To update the UI, we loop through the show state variable and update the
watched value on the proper show. Once the state is updated, the show will mark as watched or unwatched accordingly.
async function handleUpdateShow(e) { const res = await fetch('/api/updateShow', { method: 'POST', body: JSON.stringify({ title: e.target.value, watched: e.target.checked, }), }); let newShows = shows.slice(); newShows = newShows.map((show) => { if (show.data.title == e.target.value) { return Object.assign({}, show, { data: { title: e.target.value, watched: e.target.checked }, }); } return show; }); setShows(newShows); }
Where to go from here
Obviously, this is a simple example, but hopefully, it gave you a solid sense of working with Fauna. There is much more that you can do with Fauna than we've covered here.
For example, if you prefer to work with GraphQL rather than Fauna's FQL for querying, Fauna gives you the ability to upload a GraphQL schema and then use GraphQL for querying rather than FQL.
There's even a Next.js starter providing an example of how to use Fauna with GraphQL inside a Next.js app.
Fauna offers built-in identity and authentication that you can use to add a login to your Jamstack site. And there's also a streaming feature in the preview that allows you to subscribe to a document so that any time it is updated or deleted, the stream is notified. Basically, this lets you push changes from Fauna to the client whenever data is updated.
It's worth giving Fauna a try - there's a generous free tier that you can do quite a lot with. Go ahead and put some data in your Jam.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/remotesynth/using-next-js-with-faunadb-how-to-query-the-database-from-your-app-27gm | CC-MAIN-2021-25 | refinedweb | 2,232 | 65.42 |
Using JSONP With $resource In AngularJS
The other day, I was tracking down an "Access Denied" error when I came across an AngularJS $resource that was making a Cross-Domain request. It seemed that this was only happening in IE9 (if memory serves me correctly), so I assumed that it was a limitation with CORS (Cross-Origin Resource Sharing) in older IE browsers. To slap some duct tape on the problem, I switched it from a regular GET request to a JSONP (JavaScript Object Notation with Padding) request. But, getting JSONP to work with the $resource was a bit of a hurdle.
Ultimately, the problem was really one of documentation. JSONP (or JSON with Padding) is mentioned in the $resource API; but, it's really only documented well in the $http API, which I have yet to dig into.
When I converted the $resource from a GET request to a JSONP request, I started off by simply switching the method to "JSONP". Coming from a jQuery background, I assumed that the "callback" parameter would get automatically generated and applied to the outgoing request. But, it did not.
Then, I tried adding an explicit "callback" parameter to the JSONP request configuration. But, this still didn't work. The network activity looked right; but, AngularJS was rejecting the request with an error.
Finally, I jumped over to the $http documentation and figured out where I was going wrong. Not only do I have to explicitly define my "callback" parameter in AngularJS, the callback parameter has to have the set value, "JSON_CALLBACK". Once I added this to the outgoing request configuration, the JSONP request started working.
?callback=angular.callbacks._2
?callback=angular.callbacks._3
As you can see, AngularJS generates functions that are accessible off the global angular namespace.
To pull this post together, I put together a simple little demo that makes a JSONP request for a list of friends and then renders the list on the page:
- <!doctype html>
- <html ng-
- <head>
- <meta charset="utf-8" />
- <title>
- Using JSONP With $resource In AngularJS
- </title>
- <style type="text/css">
- a[ ng-click ] {
- color: red ;
- cursor: pointer ;
- text-decoration: underline ;
- }
- </style>
- </head>
- <body ng-
- <h1>
- Using JSONP With $resource In AngularJS
- </h1>
- <p>
- I have the most awesome friends!
- </p>
- <!-- Show when data is loading. -->
- <p ng-
- <em>Loading data...</em>
- </p>
- <!-- Show when data has finished loading. -->
- <div ng-
- <ul>
- <li ng-
- {{ friend.name }}
- </li>
- </ul>
- <p>
- <a ng-Refresh List</a>
- </p>
- </div>
- <!-- Load scripts. -->
- <script type="text/javascript" src="../jquery/jquery-2.1.0.min.js"></script>
- <script type="text/javascript" src="../angular-1.2.16/angular.min.js"></script>
- <script type="text/javascript" src="../angular-1.2.16/angular-resource.min.js"></script>
- <script type="text/javascript">
- // Define our AnuglarJS module.
- var app = angular.module( "Demo", [ "ngResource" ] );
- // -------------------------------------------------- //
- // -------------------------------------------------- //
- // I controll the demo.
- app.controller(
- "DemoController",
- function( $scope, $resource ) {
- // I determine if the page is currently in a loading state.
- $scope.isLoading = false;
- // I hold the list of friends to render.
- $scope.friends = [];
- // When defining the JSONP-oriented resource, you need to define the
- // request such that it contains the string "JSON_CALLBACK". When you
- // do this, AngularJS will replace said string on a per-request basis
- // with a new and unique callback instance.
- var resource = $resource(
- "api.cfm",
- {
- callback: "JSON_CALLBACK"
- },
- {
- getFriends: {
- method: "JSONP",
- isArray: true
- }
- }
- );
- // Get the list of friends.
- loadRemoteData();
- // ---
- // PUBLIC METHODS.
- // ---
- // I re-request the data from the server (using JSONP).
- $scope.refresh = function() {
- loadRemoteData();
- };
- // ---
- // PRIVATE METHODS.
- // ---
- // I load the remote data.
- function loadRemoteData() {
- $scope.isLoading = true;
- resource.getFriends().$promise.then(
- function( friends ) {
- $scope.isLoading = false;
- $scope.friends = friends;
- },
- function( error ) {
- // If something goes wrong with a JSONP request in AngularJS,
- // the status code is always reported as a "0". As such, it's
- // a bit of black-box, programmatically speaking.
- alert( "Something went wrong!" );
- }
- );
- }
- }
- );
- </script>
- </body>
- </html>
As you can see, the $resource instance is defined with the default parameter, callback: "JSON_CALLBACK". I'm then binding to the underlying $promise object of the response which will be resolved when the JSONP callback is invoked.
On a side-note, if a JSONP request fails, it's a little bit of a blackbox in AngularJS. Remember, JSONP requests aren't AJAX (Asynchronous JavaScript and XML) requests - they're Script-tag requests. This means that they either load or they error; and, when they error, AngularJS reports the status code as a "0", regardless of what the server returns.
NOTE: jQuery seems to be able to access the proper status code in Firefox. As such, I assume the issue is one of cross-browser normalization? Or maybe a bug in AngularJS? I'm not sure.
While it's not really relevant to this blog post, here is the API page that I was hitting with my JSONP request. As you can see, it simply takes the data and passes it back as JavaScript code that invokes the requested callback.
- <cfscript>
- // I am the name of the JavaScript method to invoke with the response data.
- param name="url.callback" type="string";
- // I am here to simulate HTTP latency (and to make the demo more interesting).
- sleep( 1000 );
- data = [
- {
- "id" = 1,
- "name" = "Kim"
- },
- {
- "id" = 2,
- "name" = "Heather"
- },
- {
- "id" = 3,
- "name" = "Tricia"
- }
- ];
- // When serializing the data, create an actual line of JavaScript code:
- response = "#url.callback#( #serializeJson( data )# )";
- </cfscript>
- <!--- Reset the output buffer and return the byte array. --->
- <cfcontent
- type="text/javascript; charset=utf-8"
- variable="#charsetDecode( response, 'utf-8' )#"
- />
Ultimately, I probably shouldn't use the $resource service with a JSONP request. $resource provided a level of abstraction that doesn't really add much value with the limited functionality of a JSONP request. I used it primarily because it was already in place; and, because I'm not super familiar with the underlying $http service... yet.
Looking For A New Job?
Ooops, there are no jobs. Post one now for only $29 and own this real estate!
Reader Comments
Hi Ben,
Any idea how to remove the auto-generate feature of JSON_CALLBACK. I would like to cache the service urls on the server. It is not working as angular auto creates the angular callbacks dynamically for each call.
Appreciate your help!
Thanks,
Vijay
@Vijay,
I am not sure what auto-generate feature you are talking about? Do you mean that you want to cache the JSONP response locally? If so, it looks like you should be able to provide the "cache" configuration when defining the $resource. That said, I haven't tried it myself."
As you mentioned, the JSON_CALLBACK is been auto generated by angular. But in my case, I would like the Service URL to be cached in the server side.
let say, would be cached if I turn the cache ON. But as the angular adds up the dynamic callbacks, the cache feature is not working in the server as the Url may vary on each request ....
So, I would like to know any alternative that would help me to enable the cache on server. I came across an approach where they suggest to use a custom function that resembles the callback method name.
But I am not sure how efficient this is and how it handles parallel request.
Appreciate your help!
Thanks,
Vijay
Thanks Ben, really helpful article.
Just to confirm though, this will only work with GET methods, correct? there is no way to use jsonp for POST methods? Is there a work around to make POST Cross-Domain request?
Thanks!
puke pukepuke puke
Hi Ben,
Really a nice article. I have a same question as Vijay. Is there a way we can have static callback instead of dynamic callbacks | https://www.bennadel.com/blog/2610-using-jsonp-with-resource-in-angularjs.htm | CC-MAIN-2018-30 | refinedweb | 1,271 | 66.84 |
Hi,
I have written a program to display all twin primes less than 1,000. Could someone please read my code and give me ways to improve, for example: the spacing between code blocks, my choice of variable names, insert comments anywhere??, structure of the program, etc. Please don’t hold anything back. Anything that bothers you, please tell me. I’d really appreciate the advice and improvements. Thanks!
So, my program starts with prime1 which I assign 2 to. Then it enters a while loop and calls the function find_the_next_prime to find the next prime. So it starts with prime1 + 1 to check if it’s prime and keeps adding 1’s until it’s prime and returns that number. Then the rest I think is clear.
def is_twin_prime(prime1, prime2): return abs(prime1 - prime2) == 2 def find_next_prime(number): while True: is_prime = True for divisor in range(2, (number - 1) + 1): if number % divisor == 0: number += 1 is_prime = False break if is_prime: return number def main(): prime_1 = 2 while prime_1 < 1000: prime_2 = find_next_prime(prime_1 + 1) if is_twin_prime(prime_1, prime_2): print("({0:d},{1:d})".format(prime_1, prime_2)) prime_1 = prime_2 main() | https://discuss.codecademy.com/t/improvements/263552 | CC-MAIN-2018-51 | refinedweb | 191 | 82.24 |
Quite 5(1 review) - 15 Nov 2011 04:13:02 GMT - Search in distribution
Date::Manip::Range parses and holds a date range. The range is defined by a start and end point. The module accepts ranges as a single string of two dates separated by a range operator. Some examples... my $range = Date::Manip::Range->new( {parse => ...RBWOHLFAR/Date-Manip-Range-1.10 - 22 Jul 2015 15:41:08 GMT - Search in distribution
Date::Range::Birth is a subclass of Date::Range, which provides a way to construct range of dates for birthday....MIYAGAWA/Date-Range-Birth-0.02 - 08 Dec 2001 10:55:23 GMT - Search in distribution
Parse dates from Gedcom files....RSAVAGE/Gedcom-Date-0.09 - 29 Nov 2015 02:59:00 GMT - Search in distribution
- Gedcom::Date - Perl class for interpreting dates in Gedcom files
A range of Date::Simple objects....ZUMMO/Date-Simple-Range-1.1 - 18 Dec 2008 08:02:44 GMT - Search in distribution GMT - Search in distribution
- Date::Handler - Easy but complete date object (1.1)
- Date::Handler::Delta - Time lapse object
This module implements ranges of dates using the same API as other Range::Object modules. Input date formats are subset of ISO 8601; only two are supported: YYYY-MM-DD and YYYY-MM for month-only dates....TOKAREV/Range-Object-0.93 - 21 Nov 2011 16:42:24 GMT - Search in distribution
- Range::Object - Basic facilities for manipulating different kinds of object ranges
KAN/DynGig-Range-Time-0.01 - 02 Jul 2012 02:59:22 GMT - Search in distribution
- DynGig::Range::Time - Time ranges
MUTANT/XML-SRS-0.09 - 14 Feb 2011 02:59:59 GMT - Search in distribution
- XML::SRS::Domain::Query - Class representing an SRS DomainDetailsQry transaction
Parses plain-English strings representing date/time ranges...AQUILINA/Date-RangeParser-EN-0.08 - 20 May 2014 21:23:33 GMT - Search in distribution
The module was written as a hack, for the task at hand, to scan a log file and account for the lines within a date range. The initial trivial implementation, for the log file conducted by syslog Feb 4 00:00:01 moof postfix/smtpd[1138]: connect from l...KARASIK/Regexp-Log-DateRange-0.02 - 17 Aug 2007 10:34:33 GMT - Search in distribution
MCRAWFOR/Solstice-1440 - 07 Nov 2007 20:57:59 GMT - Search in distribution
A simple widget for specifying a range of dates. (For example, after '1965-03-12' and before '1989-02-14')...OFEYAIKON/Gtk2-Ex-DateRange-0.07 - 19 Oct 2005 04:00:21 GMT - Search in distribution
NUFFIN/Mail-Summary-Tools-0.06 - 09 Sep 2007 17:07:21 GMT - Search in distribution
- Mail::Summary::Tools - Tools for mailing list summarization.
SHENJ/Yahoo-Marketing-APT-6.01 - 27 Jul 2010 00:12:51 GMT - Search in distribution
Perl data type class for the XML Schema defined complexType DateRange from the namespace. Represents a range of dates that has either an upper or a lower bound. The format for the date is YYYYMMDD. PROPERTIE...JRADCLIFF/GOOGLE-ADWORDS-PERL-CLIENT-2.15.0 - 31 Mar 2014 18:44:23 GMT - Search in distribution
Perl data type class for the XML Schema defined complexType DateRange from the namespace. Represents a range of dates that has either an upper or a lower bound. The format for the date is YYYYMMDD. PROPERTIE...SUNDQUIST/Google-Ads-AdWords-Client-4.3.0 - 02 Feb 2016 21:20:17 GMT - Search in distribution
Rose::HTML::Form::Field::DateTime::Range is a compound field that represents a date range. It is made up of two subfields: a Rose::HTML::Form::Field::DateTime::StartDate field and a Rose::HTML::Form::Field::DateTime::EndDate field. The internal value...JSIRACUSA/Rose-HTML-Objects-0.623 5(1 review) - 18 Mar 2015 00:28:00 GMT - Search in distribution
- Rose::HTML::Object - HTML object base class.
- Rose::HTML::Form::Field::DateTime::EndDate - Text field for an "end date" in a date range.
- Rose::HTML::Form::Field::DateTime::StartDate - Text field for a "start date" in a date range.
- 3 more results from Rose-HTML-Objects » fro...MDOM/App-dategrep-0.54 - 23 Jun 2015 17:54:29 GMT - Search in distribution
This Recipe provides an example based on DateTime object manipulation. Lets say we have a bank with 3 vpns to its data center. When all of the vpns are off line the bank itself is unable to process customer transactions. This example shows how to cal...AKALINUX/Data-Range-Compare-1.031 - 10 Dec 2015 21:37:09 GMT - Search in distribution | https://metacpan.org/search?q=Date-Range | CC-MAIN-2016-07 | refinedweb | 761 | 56.25 |
On Tue, Feb 28, 2012 at 10:01 AM, Ulf Bro <ulf....@web.de> wrote: > Just one thing you can't do is to change the order of files appearing in > the same namespace (physically they are files in the same folder). They > always appear in alphabetical order. If Zim were to be changed so that > pages can be swapped (and thus appear in another order in the index file) > then Zim would actually be an outline editor. We would then just need a > function to export everything into one big text file, or one big html file, > that's all. It would't be difficult to program. >
Advertising
This are issues and you are referring to. I agree that these would be very nice to have features. However solving these is not "minor programming" and are in fact more difficult to add than you seem to think. I'm working towards this goal, but it will take some serious refactoring of the indexing code to get there. Regards, Jaap
_______________________________________________ Mailing list: Post to : zim-wiki@lists.launchpad.net Unsubscribe : More help : | https://www.mail-archive.com/zim-wiki@lists.launchpad.net/msg01569.html | CC-MAIN-2018-09 | refinedweb | 183 | 73.88 |
Tim ) )();
18: }
19: Display( msg );
20: }
Not Just Strings
Of course, you don't have to add just strings. The value is an object and can be anything. Let's make an incredibly simple GeekObject and substitute that for the applicationSettings. We'll start by adding a GeekClass,
1: namespace SimpleIsolatedStorage
2: {
3: public class Geek
4: {:
1: void Add_Click( object sender, RoutedEventArgs e )
2: {
3: try
4: {,
1: void Values_Click( object sender, RoutedEventArgs e )
2: {
3: string header = "Values: ";
4: string msg = header;
5: foreach ( object o in appSettings.Values )
6: {
7: if ( msg.Length > header.Length )
8: msg += ", ";
9:
10: Geek g = o as Geek;
11: msg += g.Name + "(" + g.FavoriteGeekBook + ")";
12:
13: }
Full Source Code SimpleIsolatedStorage.zip
Thanks.
One Response to Isolated Storage – Might Be Easier Than You Think | https://jesseliberty.com/2008/09/29/isolated-storage-%E2%80%93-might-be-easier-than-you-think/ | CC-MAIN-2021-39 | refinedweb | 132 | 64.3 |
I can't figure out how to get this program to work. It compiles fine. It doesn't work at school or on my friends Lan at his house. The purpose of the program is to send anonymous net send messages but the functions don't seem to be doing anything and nothing happens when I run the program (stuff happens, but there is no result). I've read everything about the functions at the MSDN thing, but I don't know what I'm doing wrong. I've even tried manually registering the alias's with the system() function in replace of the NetMessageNameAdd() function. Here is the code (to compile it you have to link it with the netapi32 library):
Any help possible would be greatly appreciated.Any help possible would be greatly appreciated.Code:
#include <iostream>
#include <cstring>
#include <windows.h>
#include <Lm.h>
using namespace std;
int main()
{
char fromName[20];
char computerName[20];
char message[100];
char fake[30];
char completeCommand[140];
int num;
cout<<"Welcome, you are about to have the best fun of"
<<"\nyour typing career at the expense of someone else!"<<endl;
cout<<"Please enter the name of the computer you want to spam: ";
cin.getline(computerName, 20);
char* compConst = computerName;
cout<<"Please enter the message you wish to spam with (must be below 100 chars): ";
cin.getline(message, 100);
cout<<"Please enter the assumed name: ";
cin.getline(fake, 30);
char* nameConst = fake;
cout<<"Please enter the number of messages you wish to send to that alias: ";
cin>>num;
int msg = strlen(message);
NetMessageNameAdd(NULL, LPCWSTR("RECTOR"));
for(int i = 0; i<num; i++){
NetMessageBufferSend(NULL,(LPCWSTR)compConst, (LPCWSTR)nameConst, (BYTE*)message, msg*2);}
cout<<"Done."<<endl;
system("PAUSE");
return 0;
} | http://cboard.cprogramming.com/windows-programming/61915-what-wrong-program-uses-windows-network-functions-printable-thread.html | CC-MAIN-2016-36 | refinedweb | 289 | 64.41 |
<<
test account565 Points
random.randint
Stuck on this one. I have tried 3 different (VERY SIMILAR) variations of the attached code/screenshot and am not getting it solved. I am thinking the problem is that the 'return'?
# EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h" import random def random_item(num): random.randint(0, len(num - 1)) return(random.randint)
1 Answer
Steven Parker215,939 Points
Yes, partly. You want to return an element from the iterable. But to do that, when you call randint (the first time) you will need to save the value it returns in a variable. Then you can use that variable as an index to select an item from the iterable.
Steven Parker215,939 Points
It's hard to understand that unformatted, but it looks like you're calling random.randint twice instead of just once. But it does look like you're saving the first call in a variable named "iterable". Instead of returning that directly, you should use it as an index value for the argument ("
num[iterable]").
And when posting code, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area.
Or watch this video on code formatting.
test account565 Points
test account565 Points
I'm lost. don't know what you just said, but I tried this and it did not work.
import random def random_item(num): iterable = random.randint(0, len(num - 1)) random.randint(0, len(num - 1)) return(iterable) | https://teamtreehouse.com/community/randomrandint-2 | CC-MAIN-2022-27 | refinedweb | 255 | 69.38 |
.editors;21 22 import java.beans.*;23 24 /**25 * Editor for property of type java.lang.Character26 *27 * @author Josef Kozak28 */29 public class CharacterEditor extends WrappersEditor {30 31 public CharacterEditor() {32 super(java.lang.Character.TYPE);33 }34 35 36 //----------------------------------------------------------------------37 38 39 /**40 * This method is intended for use when generating Java code to set41 * the value of the property. It should return a fragment of Java code42 * that can be used to initialize a variable with the current property43 * value.44 * <p>45 * Example results are "2", "new Color(127,127,34)", "Color.orange", etc.46 *47 * @return A fragment of Java code representing an initializer for the48 * current value.49 */50 public String getJavaInitializationString() {51 if ( ((Character )getValue()).charValue() == '\'' )52 return "new java.lang.Character('\\'')"; // NOI18N53 else54 return "new java.lang.Character('" + getAsText() + "')"; // NOI18N55 }56 57 }58
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/netbeans/beaninfo/editors/CharacterEditor.java.htm | CC-MAIN-2013-48 | refinedweb | 156 | 51.75 |
.
If you want to develop and test the code presented here on-the-fly for yourself while working through the text (it is for sure a good idea and even better if you want to play around with certain stuff not literally presented inbetween), you need of course to install GNU Guile (including the appropriate development package containing header files, if necessary for your system) as well as Gnuplot, and have a UNIX-like environment and some C compiler (just use gcc). I worked on a GNU/Linux machine with Guile 1.8.7, Gnuplot 4.2 and gcc 4.3.1, but any recent Guile and Gnuplot should do it.
Guile is an implementation and dialect of the Scheme programming language (Scheme is a dialect of LISP itself). It is intended to be used as the extension language of the GNU project.
That means that Guile is designed as a library you can include into your own project and make the interpreter run code within it; additionally, you can provide special procedures in this Guile environment that interface to the core of your application. This way, Scheme scripts written by a user can manipulate stuff “within” your application.
The point of this all is to provide an easy way for you to make your application extensible and scriptable. For instance, if you need some sort of configuration files or even real scripting support for your application, you can use Guile instead of rolling your own “small” configuration or scripting language and interpreter; it already exists, so don't waste your time on yet another one but instead keep working on the new and exciting parts of your project! Having Guile as some “universal” scripting language (at least that's what the Guile people would like it to be, but I think it's suited to this goal) also means that a user does not have to learn different languages for each application she wants to configure or script. Instead she can do so on all her favourite software with just learning Scheme. Besides, at least my personal opinion is that Scheme is very nice and fun to program in, and very well suited to small pieces of code like scripts.
And the very best: The current development on Guile allows the core Guile “platform” to run not only Scheme code but support other languages as well on top of Guile. So you can just integrate Guile as scripting interpreter into your code, and have it also run scripts in ECMAScript, Emacs Lisp or any other language that Guile will implement in the future (like Perl, Tcl, Python or others) – and you don't have to think a single instant about this!
In concrete terms, installing Guile on your system provides basically two things for you:
First, you can use the guile command-line utility as a Scheme interpreter to write programs (or as a table-top calculator if you want to).
Second, use the libguile programming library to run applications using Guile as scripting extension; or write your own that can access the interpreter and make use of it to script your code.
“Why did you call him Tortoise, if he wasn't one?” Alice asked.
“We called him Tortoise because he taught us,” said the Mock Turtle angrily.
(Lewis Carroll, Alice's Adventures in Wonderland)
As the project to demonstrate Guile, we're going to develop a very simple “Tortoise” graphics program. It will use Gnuplot for graphics output, but should be easy to adapt to any other graphics systems.
It will produce graphics output by assuming that there's a tortoise sitting in the middle of the screen; this tortoise is able to perform some basic instructions given by the user.
You can ask it to turn left by a certain number of degrees (or right by giving a negative number), or you can intstruct it to walk a certain number of steps forward. It has got a pen and you can ask it to carry it either in its paws or behind its ear, so that when it moves it will leave a mark on the ground or not.
Finally, if you got yourself and the poor tortoise completely confused, you can ask it to walk away to a fresh (empty) ground, sit in the middle and face right, just as at the very start.
Let's finally start and implement the core program that will keep track of the tortoise, its movements and the graphics output. This will be implemented in C. As mentioned before, I'm going to use Gnuplot for the graphics output (at first I wanted to use the Gtk+ toolkit, but there were some problems with this approach I will come back to later).
The idea is to start a Gnuplot process in the background and send it commands to draw the lines we want on the screen over a pipe. Here's the code for a program that will start up a Gnuplot process and keep connected to it via a pipe ready to get further plotting commands:
/* Simple backend for a Logo like tortoise drawer. */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> static const int WIDTH = 10; static const int HEIGHT = 10; static FILE* start_gnuplot () { FILE* output; int pipes[2]; pid_t pid; pipe (pipes); pid = fork (); if (!pid) { dup2 (pipes[0], STDIN_FILENO); execlp ("gnuplot", NULL); return; /* Not reached. */ } output = fdopen (pipes[1], "w"); fprintf (output, "set multiplot\n"); fprintf (output, "set parametric\n"); fprintf (output, "set xrange [-%d:%d]\n", WIDTH, WIDTH); fprintf (output, "set yrange [-%d:%d]\n", HEIGHT, HEIGHT); fprintf (output, "set size ratio -1\n"); fprintf (output, "unset xtics\n"); fprintf (output, "unset ytics\n"); fflush (output); return output; } static FILE* global_output; int main (int argc, char* argv[]) { global_output = start_gnuplot (); return EXIT_SUCCESS; }
Note that here we're not doing any error checks on the system routines; you shouldn't be doing this yourself, but it keeps this code as simple as possible. As that so far has nothing to do with what you want to read about in this tutorial, I think this should be the best way to go.
What we're doing here is starting a Gnuplot process with the start_gnuplot routine and opening a pipe that can feed commands to it into global_output, so that we are later able to plot lines.
Gnuplot is started with a fixed coordinate range (-10 to 10 in both x and y directions). We're going to use parametric mode so we won't get any problems drawing vertical lines, and multiplot mode in order to allow building the graphics incrementally by adding single lines each at a time.
Now, this code adds a routine for plotting a line from (x1, y1) to (x2, y2):
static void draw_line (FILE* output, double x1, double y1, double x2, double y2) { fprintf (output, "plot [0:1] %f + %f * t, %f + %f * t notitle\n", x1, x2 - x1, y1, y2 - y1); fflush (output); }
(You may want to read up on parametric plotting in Gnuplot or on parametric equations for lines if you're not sure what's going on here. Or just believe me that this will do what we want for the moment.)
Finally, we can write the routines that will control the tortoise; here's some trigonometry involved, and you will need to #include <math.h>:
static double x, y; static double direction; static int pendown; static void tortoise_reset () { x = y = 0.0; direction = 0.0; pendown = 1; fprintf (global_output, "clear\n"); fflush (global_output); } static void tortoise_pendown () { pendown = 1; } static void tortoise_penup () { pendown = 0; } static void tortoise_turn (double degrees) { direction += M_PI / 180.0 * degrees; } static void tortoise_move (double length) { double newX, newY; newX = x + length * cos (direction); newY = y + length * sin (direction); if (pendown) draw_line (global_output, x, y, newX, newY); x = newX; y = newY; }
That's it, just add a tortoise_reset (); call to the main routine after starting Gnuplot, so that the tortoise starts at a well-defined position.
Of course you want to try it now, don't you? At least I'm burning with excitement... So, we're going to give the tortoise actually some instructions, directly via C code in the main routine:
{ int i; tortoise_pendown (); /* This is unnecessary, but makes it clearer. */ for (i = 1; i <= 4; ++i) { tortoise_move (3.0); tortoise_turn (90.0); } }
As a side-note: This program leaves the Gnuplot process alive when terminating; we could send it a quit command before finishing, but later on we won't be able to do so and instead of cooking up anything more complicated, I'll just leave it like that. It basically works this way and even has the advantage that the Gnuplot window stays open until you close it, despite the fact that our tortoise-program has already finished. And if you get worried about the processes, just do a killall gnuplot afterwards...
I don't know about you, but I myself like using Makefiles; so save the full code we've worked out to tortoise.c and this as Makefile:
# Basic Makefile for the tortoise package. CFLAGS = LIBS = .PHONY: clean build run build: tortoise clean: rm -f tortoise tortoise.o run: tortoise ./tortoise tortoise: tortoise.o gcc $< -o $@ $(LIBS) tortoise.o: tortoise.c gcc -c $< -o $@ $(CFLAGS)
Of course, CFLAGS and LIBS are quite useless at the moment, but they will get some use later, so I just included them right away. Now, doing a make run should compile and run your code and open up a Gnuplot window with the resulting graphics; for me it looks like this:
Congratulations, you've just done your first tortoise-graphics! Still, we don't want to fix and compile the instructions directly with our C code as we just did; instead, the user should be able to interactively control the tortoise.
This is where Guile comes into play. Without it, we could write some additional code that reads, parses and interprets commands to the tortoise, calling the appropriate tortoise primitives as already defined.
Sounds not too bad? Well, probably it isn't. But in the C code we also used a loop to draw the square – otherwise we would have had to repeat the same two lines (movement and turn) four times. And what if we wanted to draw a polygon with, say, 1024 vertices? I hope you are convinced now that to make our tool really useful, we also needed to implement some means of looping.
Hm, while we're at it: Our tortoise-package can also be used to build up a Koch's curve quite elegantly using recursion (try a quick internet search if you can't wait until I'll come back to it in more detail later) – so want to implement some sort of procedures that can recursively call themselves?
All in all, we were probably going to implement a full-fledged tortoise programming language – but think about it: Has this anything to do with our original application and goal? I hate to spoil you all the fun (writing programming languages can be quite fun), but no, it hasn't.
Luckily, we need not go through all this effort; Guile already provides a perfectly good way of making our tortoise programmable. Scheme should be quite a good language to perform all we want (loops, procedures, recursion) – and much more. We just need to link our tortoise to the Guile-world, which will be the topic of the next sections.
First, let's add Guile to our code; you need to #include <libguile.h> as the “master header”. In our main routine, take out again the temporary test code we used to produce the first output, and replace it instead by these lines:
scm_with_guile (®ister_functions, NULL); scm_shell (argc, argv);
scm_with_guile may be a bit weird at first glance; what it does is calling the provided routine (register_functions – we'll create it in a few moments). Additionally, it also “activates” Guile during this call, so that other Guile library functions can be called from within register_functions. Don't worry about what exactly goes on there, you just need to remember that this indirection is necessary if you want to work with Guile.
(As a side-note: There's also a scm_init_guile method that does this “activation” directly and without this peculiar call-back; it may seem more reasonable and easy-to-understand to you, and you can well use that one instead. However, Guile recommends using scm_with_guile for better portability where possible.)
The call to scm_shell actually runs the Guile REPL (Read-Evaluate-Print Loop, that shell-like command prompt for interactive Scheme evaluation you also get when starting up guile directly) – the idea is to do all the initialization we need for our application, and finally run the REPL, where the user can then enter her commands in Scheme code. Actually, this routine does a little more: It also processes the command-line arguments given to our tortoise-program in the way guile handles its arguments; for instance, you can then do tortoise -s foobar.scm and have your commands read from foobar.scm. That's why we need to pass it argc and argv, in case you were interested.
scm_shell does not return, but rather keep on until the user closes the REPL; then our tortoise-program will also finish as a whole. Do you remember that I still owe you an explanation why using the Gtk+ toolkit for graphics would have been more complicated than Gnuplot? The reason I decided against Gtk+ is that for the Gtk+ toolkit you do something similar: After your program's initialization, you call out to a Gtk+ main loop that will process incoming events and also never fully return control to your program – but in this case, we can't run both Gtk+'s main loop and the Guile REPL; at least not without writing a multi-threaded application. That would have been again some unnecessary complication; I hope you agree with me now... But if not, just go ahead and try converting our package to Gtk+! I guess that's an interesting exercise.
Finally, we still have to create register_functions:
static void* register_functions (void* data) { return NULL; }
You're right, it's not really interesting or even useful for now, but we'll fill it in later. Notice the two void*? The argument data gets passed whatever we want from scm_with_guile – that's why there's NULL as second argument in the call, but we could make it a pointer to an integer or even a large struct in case we needed to pass some data to register_functions. In turn, the return value of register_functions, which is also NULL in this case but could be anything as complex as you want, is returned from scm_with_guile – something we also don't need.
Once again, we'll try to compile and run what we have so far. To do so, we have to tell the compiler where to look for libguile.h as well as the linker to include libguile. You can work out the appropriate flags for yourself, but the utility guile-config that comes with Guile can do it for you.
So all we need to do is update the Makefile like this (and now the variables get some meaning!):
CFLAGS = `guile-config compile` LIBS = `guile-config link`
With these adaptions, you should be able to compile and run the program again. This time, the Gnuplot window that pops up should just be empty (and stay so), but on the command-line a Guile REPL will be available just as if you had started guile yourself.
You can do some Scheme programming, but so far nothing to use our little tortoise at all:
guile> (define (foobar a b) (+ a b)) guile> (foobar (* 2 3) 4) 10 guile> (map foobar '(1 2 3) '(4 5 6)) (5 7 9) guile> (tortoise-reset) Backtrace: In current input: 1: 0* (tortoise-reset) <unnamed port>:1:1: In expression (tortoise-reset): <unnamed port>:1:1: Unbound variable: tortoise-reset ABORT: (unbound-variable)
That's quite nice, isn't it? Still, without control over the tortoise, it does not make sense at all; you can just use guile directly without all the effort we went through if you want to program in Scheme. But we can fix this easily.
As I've promised, we'll integrate the tortoise into the Guile environment now. We can simply tell Guile to make our tortoise-procedures available from Scheme with scm_c_define_gsubr; these need to be called from within the activated “Guile mode”, so we add the calls to register_functions:
scm_c_define_gsubr ("tortoise-reset", 0, 0, 0, &tortoise_reset); scm_c_define_gsubr ("tortoise-penup", 0, 0, 0, &tortoise_penup); scm_c_define_gsubr ("tortoise-pendown", 0, 0, 0, &tortoise_pendown); scm_c_define_gsubr ("tortoise-turn", 1, 0, 0, &tortoise_turn); scm_c_define_gsubr ("tortoise-move", 1, 0, 0, &tortoise_move);
The first arguments are the Scheme-names for the procedures we're going to register, the last arguments pointers to the C functions that implement them. The numbers inbetween define the number of arguments the procedures take, namely required, optional and whether there's a rest-list argument nor not – in our case, there are neither optional arguments nor rest-lists, but tortoise-turn and tortoise-move take one required argument (the angle or distance, respectively).
Unfortunatly, this is only one half of the changes needed; Guile represents all Scheme values with the SCM type, and thus both the return values and argument-types of the C procedures need to be SCM's. In order to get the double values out, we need some Guile API functions; our tortoise procedures become:
static SCM tortoise_reset () { x = y = 0.0; direction = 0.0; pendown = 1; fprintf (global_output, "clear\n"); fflush (global_output); return SCM_UNSPECIFIED; } static SCM tortoise_pendown () { SCM result = scm_from_bool (pendown); pendown = 1; return result; } static SCM tortoise_penup () { SCM result = scm_from_bool (pendown); pendown = 0; return result; } static SCM tortoise_turn (SCM degrees) { const double value = scm_to_double (degrees); direction += M_PI / 180.0 * value; return scm_from_double (direction * 180.0 / M_PI); } static SCM tortoise_move (SCM length) { const double value = scm_to_double (length); double newX, newY; newX = x + value * cos (direction); newY = y + value * sin (direction); if (pendown) draw_line (global_output, x, y, newX, newY); x = newX; y = newY; return scm_list_2 (scm_from_double (x), scm_from_double (y)); }
You've already guessed it, scm_to_double gets the value “out of” a Scheme number (if it is a number at all, but we won't care about this and assume we're only fed correct arguments).
You also noticed for sure that I made our procedures return some “reasonable” values, using some other Guile API stuff: SCM_UNSPECIFIED means just that there's no return value (like void in C). If you define a procedure that has no meaningful result, you at least need to return SCM_UNSPECIFIED from it to make Guile happy (and assert this fact).
The penup and pendown commands return (as a Scheme boolean, created by scm_from_bool) the state of the pen before the requested change.
turn and move return the new direction and coordinate (as a Scheme list with two entries), respectively – of course, you already know what scm_from_double and scm_list_2 do, right?
Congratulations, now we've managed to build the whole tortoise package with Guile! And left is all the fun working with it...
Recompile the program (should be easy thanks to our neat Makefile) and run it. Once again, you should get the Guile (Tortoise!) REPL, but now our procedures should really be available. Try out all of the functionality with a session like this:
guile> (tortoise-move 1) (1.0 0.0) guile> (tortoise-turn 90) 90.0 guile> (tortoise-penup) #t guile> (tortoise-move 5) (1.0 5.0) guile> (tortoise-pendown) #f guile> (tortoise-move 1) (1.0 6.0) guile> (tortoise-reset) guile> (tortoise-move (sqrt 2)) (1.4142135623731 0.0) guile> (quit)
(I won't include the expected graphics output, just see for yourself...) I hope everything works for you, too. If not, it's the perfect time to go back to the code and try to find what's going wrong... Otherwise, let's have some fun and do real programming with our tortoise!
For instance, we can automate the task of drawing polygons with a Scheme function; try out this code:
(define (draw-polygon! circumference vertices) (let ((side (/ circumference vertices)) (angle (/ 360 vertices))) (let iterate ((i 1)) (if (<= i vertices) (begin (tortoise-move side) (tortoise-turn angle) (iterate (1+ i))))))) (draw-polygon! 16 4) (tortoise-penup) (tortoise-move 1) (tortoise-turn 30) (tortoise-pendown) (draw-polygon! 12 3) (tortoise-penup) (tortoise-move -2) (tortoise-turn -100) (tortoise-pendown) (draw-polygon! 10 64)
This is what I get, but try for yourself:
Remember that I promised you something about Koch's curve? Now we're going to construct it, using a recursive function. See for instance for details about what Koch's curve is. Anyways, here comes the code; try to find out how it works, if you want:
(define (koch-line length depth) (if (zero? depth) (tortoise-move length) (let ((sub-length (/ length 3)) (sub-depth (1- depth))) (for-each (lambda (angle) (koch-line sub-length sub-depth) (tortoise-turn angle)) '(60 -120 60 0))))) (define (snowflake length depth sign) (let iterate ((i 1)) (if (<= i 3) (begin (koch-line length depth) (tortoise-turn (* sign -120)) (iterate (1+ i)))))) (snowflake 8 3 1) (tortoise-turn 180) (snowflake 8 3 -1)
Are you impressed? I hope at least a little so... Unfortunatly, the Gnuplot-over-a-pipe approach is quite slow (at least on my system), so you could probably have been even more impressed if the graphics would have been there more quickly; but anyways, at least I like this very much! Regarding the Scheme code, I won't comment it further, as not to spoil all your fun thinking about it. I encourage you to do so, I like this recursive construction very much. Oh, and here's my resulting plot:
Looks quite interesting, doesn't it? By the way, this is also for me the first time I constructed the “inverse” snowflake with “negative sign” – I don't know if that's done in general, but I just wanted to know the result, so here it is (the left half of the image, which got constructed by the second call).
I hope this introduction so far gave you an idea about what Guile can do for you and how it basically works. For what I needed with my first Guile project, the stuff so far was nearly enough; however, that was of course only the tip of the iceberg, and there's a lot of things you could still learn.
For instance, there are of course a whole lot of other functions in the Guile library to work with Scheme objects; nearly any primitive that is accessible from Scheme can be used from within a C procedure, also – there's even a routine to capture continuations!
Starting up a REPL as we did is nice, but if you just want to run a user's configuration script at start-up of your application and then continue with your code, there are also routines that evaluate single Scheme commands or even run a file and return afterwards.
And if you decided that one tortoise is not enough, you could introduce some sort of “tortoise object” that can be created and passed to the various routines. This would allow a user to control as many tortoises in parallel as she wants – such a user-defined Scheme object is called a SMOB in Guile and is of course also easy to realize.
If you ever really need any of the stuff I mentioned or are just curious about what else you can do, I strongly suggest you browse the Guile Reference Manual. Surely you can find all you need (and much more) there! And if you need further help, try asking on the Mailing Lists.
I want to thank David Drysdale for his own “Tutorial Introduction to Guile”, upon which this document is largly based (in fact, mostly a rewrite of with some updates and – as I see it, of course – improvements).
Finally, I hope my write-up was useful to you; in case you have any comments, suggestions, tips or just want to drop me some note whatsoever, I look forward to receiving a message. You can contact me as Daniel Kraft, d@domob.eu. Good luck with Guile and hopefully you also enjoyed reading through this tutorial a little bit! | http://www.gnu.org/software/guile/docs/guile-tut/tutorial.html | CC-MAIN-2013-20 | refinedweb | 4,086 | 64.34 |
- 24 Mar 2022 14:59:48 UTC
- Distribution: Image-DecodeQR-WeChat
- Module version: 0.9
- Source (raw)
- Browse (raw)
- Changes
- How to Contribute
- Repository
- Issues
- Testers (8 / 0 / 1)
- KwaliteeBus factor: 1
- % Coverage
- License: artistic_2
- Perl: v5.6.0
- Activity24 month
- Tools
- Download (1.14MB)
- MetaCPAN Explorer
- Permissions
- Permalinks
- This version
- Latest version
- Dependencies
- Data::Roundtrip
- File::ShareDir
- Getopt::Long
- Time::HiRes
- and possibly others
- Reverse dependencies
- CPAN Testers List
- Dependency graph
- NAME
- VERSION
- SYNOPSIS
- EXPORT
- COMMAND LINE SCRIPT
- PREREQUISITES
- SUBROUTINES/METHODS
- IMPLEMENTATION DETAILS
- INSTALLING OpenCV
- INSTALLING THIS MODULE
- AUTHOR
- BUGS
- SUPPORT
- ACKNOWLEDGEMENTS
- LICENSE AND COPYRIGHT
- HUGS
NAME
Image::DecodeQR::WeChat - Decode QR code(s) from images using the OpenCV/WeChat library via XS
VERSION
Version 0.9
SYNOPSIS
This module provides a Perl interface to the OpenCV/WeChat QR code decoder via XS code. OpenCV/WeChat library uses CNN to do this with pre-trained models.
This module has been tested by myself with OpenCV v4.5.5 and Perl v5.32 on Linux. But check the CPANtesters matrix on the left for all the tests done on this module.
The library is relatively successful even for rotated codes. It remains to be tested on the minimum size ofthe code images (60px in my case).
Here is some code to get you started:
# this ensures that both input params can contain utf8 strings # but also results (somehow but beyond me) use Image::DecodeQR::WeChat; # this will be fixed, right now params are hardoded in XS code my $ret = Image::DecodeQR::WeChat::decode_xs( # the input image containing one or more QR-codes 'an-input-image.png', # the dir with model parameters required by the library. # Model files come with this Perl module and are curtesy of WeChat # which is part of OpenCV contrib packages. # They are installed with this module and their default location # is given by Image::DecodeQR::WeChat::modelsdir() # Alternatively, you specify here your own model files: Image::DecodeQR::WeChat::modelsdir(), # outbase for all output files, optional # if more than one QR-codes were detected then an index will # be appended to the filename. And there will be png image files # containing the portion of the image which was detected # and there will be txt files with QR-code text (payload) # and its bounding box. And there will be an overall # text file with all payloads. This last one will be # printed to STDOUT if no outbase was specified: 'output.detected', # verbosity level. 0:mute, 1:C code messages, 10:C+XS code 10, # display results in a window with QR codes found highlighted # make sure you have an interactive shell and GUI 1, # dump image and metadata to files for each QR code detected # only if outbase was specified 1, ); die "failed" unless $ret; # we got back an array-of-2-arrays # * one contains the QR-code-text (called payload) # * one contains bounding boxes, one for each payload # we have as many payloads and bounding boxes as # are the QR-codes detected (some may have been skipped) my ($payloads, $boundingboxes) = @$ret; for (0..$#$payloads){ print "Payload got: '".$payloads->[$_] ."' bbox: @{$boundingboxes->[$_]}" .".\n"; } # The above decode_xs() expects all parameters to be present # while decode() below takes a hash of params and fills the # missing params with defaults. Then it calls decode_xs() # So, it is still calling XS code but via a Perl sub # The important bit is that the modelsdir is filled in automatically # rather than the user looking for it my $ret = Image::DecodeQR::WeChat::decode({ # these are required 'input' => 'input.jpg', 'outbase' => 'outs', # these are optional and have defaults #'modelsdir' => '...', # use it only if you have your own models #'verbosity' => 0, #'graphicaldisplayresult'' => 0, #'dumpqrimagestofile' => 0, }); die "failed" unless $ret; my ($payloads, $boundingboxes) = @$ret; for (0..$#$payloads){ print "Payload got: '".$payloads->[$_] ."' bbox: @{$boundingboxes->[$_]}" .".\n"; } # pre-trained models location (installed with this module) print "my models are in here: ".Image::DecodeQR::WeChat::modelsdir()."\n" # returns 1 or 0 when OpenCV was compiled with highgui or not # and supports GUI display like imshow() which displays an image in a window my $has_highgui_support = opencv_has_highgui_xs();
This code calls functions and methods from OpenCV/WeChat library (written in C++) for decoding one or more QR codes found embedded in images. It's just that: a very thin wrapper of a C++ library written in XS. It only interfaces the OpenCV/WeChat library for QR code decoding.
It can detect multiple QR codes embeded in a single image. And has been successfully tested with as small sizes as 60 x 60 px.
The payload(s) (the QR-code's text) are returned back as an ARRAYref.
Optionally, it can output the portion of the input image corresponding to each QR-code, its bounding box and the payload in separate files, useful for debugging and identification when multiple QR codes exist in a single input image.
Following this code as an example, it will be trivial to interface other parts of the OpenCV library:
Ιδού πεδίον δόξης λαμπρόν (behold a glorious field of glory)
EXPORT
decode()
decode_xs()
modelsdir()
opencv_has_highgui_xs()
COMMAND LINE SCRIPT
image-decodeqr-wechat.pl --input in.jpg image-decodeqr-wechat.pl --help
A CLI script is provided and will be installed by this module. Basic usage is as above.
PREREQUISITES
OpenCV library with contributed modules is required. The contributed modules must include the QR-code decoder library by WeChat. OpenCV must also contain the include dir (headers) - just saying.
A C++ compiler must be installed in your system.
Optionally,
pkg-configor
cmakemust be installed in order to aid discovering the location of OpenCV's library and include dir. If you don't have these installed then you must manually set environment variables
OPENCV_LDFLAGSand
OPENCV_CFLAGSto point to those paths and then attempt to install this module (e.g.
perl Makefile.PL; make all ; make install)
Optionally, OpenCV can contain the Highgui library so that output images can be displayed in their own window. But this is superfluous, because the basic operation of this module allows for saving output files to disk.
SUBROUTINES/METHODS
decode_xs(infile, modelsdir, outbase, verbosity, graphicaldisplayresult, dumpqrimagestofile)
It takes in the filename of an input image which may contain one or more QR codes and returns back an ARRAYref of strings containing all the payloads of the codes which have successfully been decoded (some QR codes may fail to be decoded because of resolution or quality etc.)
It returns undef on failure.
It returns an empty ARRAYref (i.e. a ref to an empty array) if no QR codes were found or decoded successfully.
These are the parameters it requires. They must all be present, with optional parameters allowed to be
undef:
infile: the input image with zero or more QR codes. All the image formats of OpenCV's imread() are supported.
modelsdir: the location of the directory holding all model files (CNN trained models) required for QR code detection. These models are already included with this Perl module and will be installed in a shared dir during installation. Their total size is about 1MB. They have been kindly contributed by WeChat along with their library for QR Code detection. They can be found. The installed models location is returned by modelsdir(). If you do not want to experiment with your own models then just plug the output of modelsdir() to this parameter, else specify your own.
outbase: optionally specify output files basename which will contain detected QR-codes' payloads, bounding boxes and QR-code images extracted from the input image (one set of files for each QR-code detected). If
dumpqrimagestofileis set to 1 all the aforementioned files will be created. If it is set to 0 then only the payloads will be saved in a single file (all in one file). If
outbaseis left
undefthen nothing is written to a file. As usual all detected codes' data is returned back via the returned value of decode_xs().
verbositylevels: 0 is mute, 1 is only for C code, 10 is for C+XS code.
graphicaldisplayresult: if set to 1, it will display a window with the input image and the detected QR-code(s) outlined. This is subject to whether current OpenCV installation was compiled to support
imshow()(with C < highgui > enabled).
dumpqrimagestofile: if set to 0, and
outbaseis specified, then all payloads are written to a single file using the basename specified. If set to 1 a lot more information is written to separate files, one for each detected code. This is mainly for debugging purposes because the returned value contains the payloads and their corresponding QR-codes' bounding boxes. See
outbaseabove.
decode(\%params)
This is a Perl wrapper to the
decode_xs()and allows a user to specify only a minimal set of parameters with the rest to be filled in by defaults.
Like decode_xs(), it returns undef on failure. Or an arrayref of two arrays. The
payloadsarray and the
bounding-boxesarray. Each has a number of items equal to the QR codes detected.
An ARRAYref of two empty arrays will be returned if no QR codes were found or decoded successfully.
The
paramshashref:
input: the name of the input image file which can contain one or more QR codes.
outbase: optional, if specified payloads (QR-code text) will be dumped to a text file. If further,
dumpqrimagestofileis set to 1 then image files with the detected QR-codes will be dumped one for each QR-code as well as text files with payloads and bounding boxes wrt the input image.
modelsdir: optional, use it only if you want to use your own model files (for their format have a look at, they are CNN training files). This Perl module has included the model files kindly submitted by WeChat as a contribution to OpenCV and will be installed in your system with all other files. Use
modelsdir()to see the location of installed model files. Their total size is about 1MB.
verbosity: default is 0 which is muted. 1 is for verbose C code and 10 is for verbose C and XS code.
dumpqrimagestofile: default is 0, set to 1 to have lots of image and text files dumped (relative to
outbase) for each QR code detected.
graphicaldisplayresult: default is 0, set to 1 to have a window popping up with the input image and the QR-code detected highlighted, once for each code detected. This is subject to whether current OpenCV installation was compiled to support
imshow()(with C < highgui > enabled).
modelsdir()
It returns the path where the models included in this Perl module have been installed. This is useful when you want to use
decode_xs()and need to specify the
modelsdir. Just pass the output of this to
decode_xs()as its
modelsdirparameter. However, you can not set the location of your own modelsdir using
modelsdir().
opencv_has_highgui_xs()
It returns 1 or 0 depending on whether current OpenCV installation has support for graphical display of images (the
imshow()function). This affects the option
graphicaldisplayresultto decode() and decode_xs() which will be ignored if there is no highgui support.
Caveat: checking for whether current OpenCV installation has highgui support is currently very lame, it merely tries to find the include file
opencv2/highgui.hppin the Include dirs. I have tried several methods (see ```Makefile.PL```), for example DynaLoader or FFI::CheckLib can search for symbols in any library (e.g. searching for
imshow()in
libopencv_highguior
libopencv_world). This would have been the most straight-forward way but alas, these are C++ libraries and function names are mangled to weird function names like:
ZN2cv3viz6imshowERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKNS_11_InputArrayERKNS_5Size_IiEE()
There's an imshow() in there but without a regex symbol-name search the symbol can not be detected.
Another take is with Devel::CheckLib which supports compiling code snippets when searching for a particular library. This fails because they ... allow only a C compiler but we need a C++ compiler.
Finally, using Inline::CPP to compile our own snippet is totally in vain because of its useless form of running as
use Inline CPP =... >. I could not find any way of telling it to use specific CFLAGS and LDFLAGS with this useless
use Inline CPPform.
IMPLEMENTATION DETAILS
This code demonstrates how to call OpenCV (modern OpenCV v4) C++ methods using the technique suggested by
Botje @ #perlin order to avoid all the function, macro, data structures name clashes between Perl and OpenCV (for example
seed(),
do_open(),
do_close()and most notably
struct cvand
namespace cvin Perl and OpenCV respectively).
The trick suggested is to put all the OpenCV-calling code in a separate C++ file and provide high-level functions to be called by XS. So that the XS code does not see any OpenCV header files.
Makefile.PLwill happily compile any
.c and/or .cppfiles found in the dir it resides by placing
OBJECT => '$(O_FILES)'in
%WriteMakefileArgs. And will have no problems with specifying also these:
CC => 'g++', LD => 'g++', XSOPT => '-C++',
With one caveat,
g++compiler will mangle the names of the functions when placing them in the object files. And that will cause XSLoader to report missing and undefined symbols.
The cure to this is to wrap any function you want to remain unmangled within
#ifdef __cplusplus extern "C" { #endif
and
#ifdef __cplusplus } //extern "C" { #endif
This only need happen in the header file:
wechat_qr_decode_lib.hppand in the XS file where the Perl headers are included.
INSTALLING OpenCV
In my case downloading OpenCV using Linux's package manager was not successful.It required to add another repository which wanted to install its own versions of packages I already had. So I prefered to install OpenCV from sources. This is the procedure I followed:
Download OpenCV sources and also its contributed modules.
Extract the sources and change to the source dir.
From within the source dir extract the contrib archive.
Create a
builddir and change to it.
There are two ways to make
cmakejust tolerable:
cmake-guiand
ccmake. The former is a full-gui interface to setting the billion
cmakevariables. Use it if you are on a machine which offers a GUI like this:
cmake-gui ..If you are on a headless or remote host possibly over telnet or ssh then do not despair because
ccmakeis the CLI, curses-based equivalent to
cmake-gui, use it like:
ccmake ..(from within the build dir).
Once on either of the cmake GUIs, first do a
configure, then check the list of all variables (you can search on both, for searching in the CLI, press
/and then
nfor next hit) to suit you and then
generate, quit and
VERBOSE=1 make -j4 all
I guess, cmake variables you want to modify are
OPENCV_EXTRA_MODULES_PATHand turn ON
OPENCV_ENABLE_NONFREEand anything that has to do with
CNNor
DNN. If you have CUDA installed and a CUDA-capable GPU then enable CUDA (search for CUDA string to find the variable(s)). Also, VTK, Ceres Solver, Eigen3, Intel's TBB, CNN, DNN etc. You need to install all these additional packages first, before finally compiling OpenCV.
I had a problem with compiling OpenCV with a GUI (the
highgui) on a headless host. So, I just disabled it. That's easy to achieve during the above.
I have installed this on a CUDA-capable GPU (with CUDA 10.2 installed) host and on a headless remote host with no GPU or basic. CUDA is not required for building this module.
It is also possible to download a binary distribution of OpenCV. Just make sure that it supports all the things I mentioned above. And that it has all the required headers (in an include dir) - just saying.
Your mileage may vary.
If you are seriously in need of installing this module then consider migrating to a serious operating system such as Linux as your first action.
INSTALLING THIS MODULE
This module depends on the existence of the OpenCV library with all the extensions and contributed modules mentioned in section
PREREQUISITES.
Detecting where this library is located in your system is the weakest link in the installation process of this module.
Makefile.PLcontains code to do this with
pkg-configor
cmake. If these fail, it will look for ENVironment variables:
OPENCV_LDFLAGSand
OPENCV_CFLAGS, which should contain the
CFLAGS(for example:
<-I/usr/include/opencv4/>) and
LDFLAGS(for example:
<-L/usr/lib64 -lopencv_world>). Set these variables manually prior installation if the automatic methods mentioned above fail.
AUTHOR
Andreas Hadjiprocopis,
<bliako at cpan.org>
BUGS
Please report any bugs or feature requests to
bug-image-decodeqr-wechat at rt.cpan.org, or through the web interface at. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Image::DecodeQR::WeChat
You can also look for information at:
RT: CPAN's request tracker (report bugs here)
CPAN Ratings
Search CPAN
ACKNOWLEDGEMENTS
The great Open Source OpenCV image processing library and its contributed module WeChat QRDetector which form the backbone of this module and do all the heavy lifting.
Botje and xenu at #perl for help.
Jiro Nishiguchi (JIRO ) whose (obsolete with modern - at the time of writing - OpenCV) module Image::DecodeQR serves as the skeleton for this module.
Thank you! to all those who responded to this SO question
LICENSE AND COPYRIGHT
This software is Copyright (c) 2022 by Andreas Hadjiprocopis.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
HUGS
!Almaz!
Module Install Instructions
To install Image::DecodeQR::WeChat, copy and paste the appropriate command in to your terminal.
cpanm Image::DecodeQR::WeChat
perl -MCPAN -e shell install Image::DecodeQR::WeChat
For more information on module installation, please visit the detailed CPAN module installation guide. | https://metacpan.org/pod/Image::DecodeQR::WeChat | CC-MAIN-2022-27 | refinedweb | 2,933 | 62.48 |
Remove DB between scheduler and compute nodes
Current way how work Nova.scheduler is not optimal there is the way to make it more scalable & flexible.
New scheduler design doc: https:/
More details about limitations of current scheduler you can see here:
https:/
There is a community effort to make 1 scheduler lib or 1 scheduler as a Service, to reduce amount of duplication of code.
During the H cycle we tried to move all common parts of scheduler to oslo.scheduler:
https:/
But we faced a lot of problems. The main problems was, that host_states are deeply connected with db.models that represent host states. And scheduler use directly projects db.
The second thing that we faced was the bad performance of scheduler. The main reason is the we are storing & updating all data in DB + on each request we are fetching all data from DB.
So as a solution we try to resolve these 2 problems:
1) Each scheduler should store all host_states locally (in some object)
2) There should be mechanism that sync all host_states in different backends
(using memcahced or sqla backends, to store updates)
This is required because another way are fanouts RPC calls, that doesn't scale..
3) There should be namespaces in host_states (to store in the same time data from different services) and be able to use filters from different projects in the same time.
4) host_state is just JSON like object.
5) Scheduler should have RPC calls to update/get host states + nova.manger, nova.api should call them instead calling nova.db.api
Our goal is to make queue of next patches:
1) Add new db.models to implement backend of synchronizer
2) Add synchronizer
3) Switch Scheduler to use synchronizer + add new RPC calls to scheduler + call from compute.manager it
4) Implement in Scheduler all required RPC calls to get/list host states
5) Remove compute_nodes table, and use scheduler in db.api as implementation
6) Remove comupte_* methods from db.api and use directly scheduler
This is the first that will make Scheduler faster, flexible & much more independent from Nova code.
Which will make unification of scheduler (or making scheduler aaS much simpler)
Blueprint information
- Status:
- Started
- Approver:
- Russell Bryant
- Priority:
- Medium
- Drafter:
- Boris Pavlovic
- Direction:
- Needs approval
- Assignee:
- Boris Pavlovic
- Definition:
- Review
- Series goal:
- None
- Implementation:
Needs Code Review
- Started by
- Boris Pavlovic on 2013-12-03
- Completed by
-
Related branches
Related bugs
Sprints
Whiteboard
johnthetubaguy:
I see there are two things the scheduler does...
* compute nodes send updates (currently via the DB)
* scheduler picks what node is required
Basically this introduces using RPC and memcache instead of database calls to perform updates, plus syncing the data between schedulers.
I would like to see the memcache dependency as optional during Icehouse, with a view (if it works well) make it mandatory in J
Gerrit topic: https:/
Addressed by: https:/
Scheduler redesign for in-memory state storage.
Addressed by: https:/
A migration which creates tables for Synchronizer
I just spoke to Boris about this blueprint. i'd like the description to be updated to reduce the scope. This blueprint should not include work on a separate scheduler service. it should also not include anything related to other projects. I'd like to see it specifically limited to no-db work, and just for nova to start with. --russellb
Replaced description, to cover only minimal scope of changes -- boris-42
Addressed by: https:/
Decoupling scheduler from database access.
Addressed by: https:/
Switches to Synchronizer.
Addressed by: https:/
Memcached backend is added.
Its too late for merging this in icehouse, defer to juno. Also we need to re-asses dependencies here, I would like to see the scheduler split merge first, so this can be totally optional. --johnthetubaguy
Unapproved - please re-submit via nova-spec --johnthetubagy (20th March 2014) | https://blueprints.launchpad.net/nova/+spec/no-db-scheduler | CC-MAIN-2020-05 | refinedweb | 640 | 61.56 |
Using OpenVINO with GPU on UP Squared reboot the system
I'm using OpenVINO with GPU for inference my deep learning model. It's very often, the UP squared board automatically reboot when I use GPU. It might because of overheating, after I use the cooling fan to decrease from 65°C to 45°C, the problems disappeared.
Anyone knows about this problem, in my opinion, 65°C is not very hot and the GPU shouldn't make the system reboot right ?
No it shouldn't reboot when the temperature is 65 degrees.
can you provide the sample or application that cause the system to reboot? Can you make the system reboot with another OpenVINO sample while using the GPU?
Thanks for your response. Actually, I think about the temperature because I ran the same program and sometimes it works, sometimes it make the computer reboot. I tested with 2 different models, resnet and SSD and the same things happened. When I ran with cooling fan, everything is ok
Actually, I use sensors command in linux to measure the temperature. And I think it is for the CPU temperature. I don't know how to measure precisely the Intel GPU.
Can someone give me some hints why the system can be reboot when using GPU ? The problem is still there and is unpredictable for me. Thanks
The system should not reboot even if under stress, where eventually it would throttle the frequency down.
Can you tell me how it the UP Squared positioned? Is the heatsink on top, or the board is upside down?
Do you have an example from the OpenVINO samples for GPU that we can use to reproduce the issue?
Also what is the hardware and software complete setup?
BIOS version, Operating System version, kernel version, OpenVINO version etc.
The heatsink is down. One OpenVINO model you can test with is face-detection-retail-0004 (you can find it in OpenVINO example).
I used the UP squared board, VPU attached (but it is not used during the test).
Bios Version: UPA1AM42
OS: Ubuntu 18.04,
Kernel version: 4.15.0-37-generic
OpenVINO version: 2019 R3.1
You need to retest it several times because most of the times it runs ok.
Thank you for your helps
The heatsink should be facing up for better dissipation, especially if you are stressing CPU and GPU.
Try with some spacers if you have some.
About the BIOS, I don't think it is the case, but it is good to update to the latest version available:
About the kernel version, is that the UP Ubuntu kernel installed from our PPA?
Last thing which I forgot to ask, what is the Power Supply that you are using?
The kernel I got from your PPA
Kernel = 4.15.0-37-generic
Patch = #40~upboard04-Ubuntu SMP Thu Feb 14 13:49:37 UTC 2019
Power getting from plugging into normal Europe electricity.
Adapter model FJ-SW0506000
Input 1.5A Max
Output 5V 6000mA
ok, thank you.
What is the CPU/RAM configuration of the Board?
Celeron, Pentium or Atom? 2, 4 or 8GB?
CPU information:
vendor_id : GenuineIntel
cpu family : 6
model : 92
model name : Intel(R) Pentium(R) CPU N4200 @ 1.10GHz
RAM: 8GB
More specific for Ubuntu version: Ubuntu 18.04.3 LTS
Because someone told me maybe there are problems in 18.04.3
Thanks
I minimize the code to reproduce the problem for you guys can see below
import cv2 import numpy as np import time from openvino.inference_engine import IENetwork, IEPlugin net = IENetwork(model='/home/k/face-detection-retail-0004.xml', weights='/home/k/face-detection-retail-0004.bin') plugin = IEPlugin(device="GPU") exec_net = plugin.load(network=net) def _preprocess_face(img, shape=(300,300)): origin_shape = img.shape img_processed = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) img_processed = cv2.resize(img_processed, (shape[0], shape[1])) img_processed = img_processed.transpose((2, 0, 1)) return img_processed image = cv2.imread('/home/k/_.jpg') for i in range(100): img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) img = _preprocess_face(img) start = time.time() res = exec_net.infer({'data': img}) print(time.time()-start)
The output I got is:
$ python gpu.py
0.017605304718017578
0.014819860458374023
It ran 2 times then the system reboot. I have tried many differents things that I can imagine: I use different model, run as asynchronous, synchronous but the problems is always there. sometimes it reboots directly from the 1 try, sometimes after several try.
I would really appreciate if someone can help me on that.
The model I downloaded from Openvino pretrained model for face detection
Sorry for bothering you too much on this unclear problem. I know it's hard to figure out this kind of problem.
I'm thinking maybe it is because of the source power. I also have problem with ssh to the UP and when I change the source power, it is fixed. Maybe the GPU's problem related to it. Can the GPU use to much power and restart the machine ?
Thanks for the detailed instructions.
The reboot seems something related to power but 5V6A is the standard PSU we use and suggest for this platform. If you have another PSU you can try in case the one you have does not provide a stable voltage.
We will try to reproduce the issue and get back to you.
- stykujason New Member Posts: 6 ✭
Hello,
I'm encountering a similar issue when stressing the GPU, running Windows 10. Up Squared board reboots within 5-10 minutes of full GPU usage. I'm using the PSU provided in the dev kit sold by Aaeon. Can you please advise? Here is my original post:
Up^2 with fan, Pentium N4200 crashing/rebooting Win10 with heavy graphics use
Hi @stykujason
I just replied to your topic, we can continue from there, but the issue is different.
We have tested the same code and setup (hardware and software), but with the latest BIOS available R4.6 and the sample was running fine for 3 hours.
Can you please try to update the BIOS and try again?
If it is not working yet, please apply for RMA
Sorry for missing your response. Thank you for your help. I think the problem is related to the PSU. When I used the GPU with the standard PSU, the reboot is quite rare, but very often with our own battery. I have tested with several UP also
Can you help me to clarify how much power should we use for UP Squared board with GPU ? (I think the standard PSU has 65W)
At this moment I'm still using BIOS 4.0 and can not update to 4.6 immediately because the board is in remote (Can I update it remotely ?). But if the system is rebooted by BIOS, do we have some logs somewhere to confirm this ? Because I checked in syslog by journalctl and found no information
Thanks
The latest BIOS available is 5.0, when you get a chance you can try.
ABout the PSU it is 30W, the SoC itself can drain 15W or more when it peaks, then you have to consider all the other components.
The spikes can be the ones causing problems where a battery not powerful enough may lower its voltage when giving more current suddenly. So it is required a proper circuit to make sure the voltage is stable in any situation.
My friend just help me to update the BIOS and it's very likely fix the problems. I need to test more but until now everything seems fine. I've never think about this solution can work but after looking at the changelog for v.4.6
**Change: Set "OS reset select" as "Warm Reset" to fix issue that OS restart becomes cold reset. Patch issue that TPM self-test CMD is timeout sometimes. Enable iTCO as default. Intel uCode update for Intel-SA00233 **
Then I thought that it could be a very nice idea
. Hope that this will fix forever the problem because I've stayed with it for a really long time.
Thank so much for your | https://forum.up-community.org/discussion/4000/using-openvino-with-gpu-on-up-squared-reboot-the-system | CC-MAIN-2022-40 | refinedweb | 1,354 | 75.71 |
Java program to solve Climb Stairs using dynamic programming
Hello Everyone! In this Java tutorial, we are going to discuss the problem of climb stairs using ‘n’ of ways using dynamic programming. We are going to use the recursion method to solve this problem.
How to solve climb stairs using dynamic programming in Java
First, understand what is climb stair problem. In this problem, we have to climb the stair from 0 stairs to nth stair using dynamic programming. In other words, There are n stairs, someone status at the bottom wants to reach the endpoint. The individual can climb both 1 stairs or 2 stairs (or a variable number of jumps)at a time. Count the wide variety of approaches, the person can reach the top. But there are few conditions we have to follow:-
- You are given a number of n, representing the wide variety of stairs in a staircase.
- You are at the 0th step and are required to climb to the top.
- You are given n numbers, where ith detail’s value represents -till how far from the step you could jump to in a single move.
- You can of path soar fewer number of steps inside the circulate.
- You are required to print the range of different paths thru which you could climb to the top.
Java Code for solving Climb Stairs
import java.util.*; public class Main { private static final Scanner mega= new Scanner(System.in); public static void main(String[] args) throws Exception { System.out.println("Enter the number"); int n = mega.nextInt(); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = mega.nextInt(); } mega.close(); int[] dp = new int[n + 1]; dp[n] = 1; for (int i = n - 1; i >= 0; i--) { if (arr[i] > 0) { for (int j = 1; j <= arr[i] && i + j < dp.length; j++) { dp[i] += dp[i + j]; } } } System.out.println("Result:- "+dp[0]); } }
We have to show or define the variety of ways to climb the stairs from zero to top.
Now, run this program see the output.
Input
Enter the number:- 10 3 3 0 2 1 2 4 2 0 0
Output
Result:- 5
Now, You can understand how to solve climb stair problem using dynamic programming. | https://www.codespeedy.com/java-program-to-solve-climb-stairs-using-dynamic-programming/ | CC-MAIN-2022-27 | refinedweb | 379 | 73.47 |
This article describes using a Semaphore for thread pooling.
A semaphore is an enforcement of size limitation to a thread pool. Once it’s full, no more threads can enter the semaphore until one or more threads complete and hence get terminated. A queue builds up outside for other threads. Then, for each thread that leaves the semaphore, another thread enters from the queue.
A semaphore has no owner. Any thread can release any other thread on a semaph
SemaphoreSlim
To use a semaphore in C#, you first need to instantiate an instance of a Semaphore object. The basic constructor.
Use the Semaphore class to control access to a pool of resources. Threads enter the semaphore by calling the WaitOne method, which is inherited from the WaitHandle class, and release the semaphore by calling the Release method.
WaitOne
WaitHandle
Release.
In our example code, we are creating a semaphore with an initial size of 3 and a max size of 5, which means initially two slots will be vacant.
using System;
using System.Threading;
namespace Threading
{
public class SemaphoreImpl
{
// A semaphore that simulates a limited resource pool.
private static Semaphore semaphore = new Semaphore(3,5);
//Empty constructor.
public SemaphoreImpl()
{
}
private void ThreadExcecute(object num)
{
//Thread bigins and waiting for slot in semaphore.
Console.WriteLine("Thread {0} begins " +
"and waits for the semaphore.", num);
semaphore.WaitOne();
Console.WriteLine("Thread {0} enters the semaphore.", num);
//In practical scenario should not call sleep.
//In our case we are stimulating excecution time of method.
Thread.Sleep(1000);
//Method sucessfully excecuted and thread
//is supposed to release from semaphore.
Console.WriteLine("Thread {0} got released from the semaphore.", num);
semaphore.Release();
}
public void ExcecuteSemaphore()
{
// Create and start five numbered threads.
for (int i = 1; i <= 10; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(ThreadExcecute));
t.Start(i);
}
Console.WriteLine("Main thread exits.");
//Wait for some time.
Thread.Sleep(500);
}
}
}
Thread pooling now becomes. | http://www.codeproject.com/Tips/241081/Multithreading-Semaphores-in-Csharp-4-0 | CC-MAIN-2014-35 | refinedweb | 318 | 60.41 |
All I know I learned from GinA (and DGG)
Okay, maybe that’s an exaggeration, but I’ve been digging into Groovy in Action (GinA) and the Definitive Guide to Grails (DGG) more lately and keep finding nuggets that I apparently missed on my first few readings.
(I’m trying not to be annoyed about that, btw. By this stage in my career, I know all too well that I have to re-read things over and over to really “get” them. I just wish I retained more than I apparently do. I guess I’ll always think that.)
Anyway, recently I wrote a blog post about how I was able to iterate over
Dates because Groovy treated them as a
Range (yes, capital R). I thought that was really cool and wasn’t sure exactly why it worked.
Lo and behold, on page 96 of GinA, Listing 4.1 includes
def today = new Date() def yesterday = today - 1 assert (yesterday..today).size() == 2
Page 98 points out that “any datatype can be used with ranges,” provided it implements
next() and
previous() and implements
Comparable. This is equivalent to overriding ++, –, and the good ol’ spaceship operator, <=>.
(As a long-time Java developer, I have to say that any language that has a spaceship operator is inherently cool. Except Perl, of course. :))
I keep finding ways to rewrite my code as more idiomatic Groovy (or maybe I should just say, groovier). I used to calculate the number of days in a training course from the start and end dates using:
int days = 0 for (date in startDate..endDate) { days++ }
Now I realize that since a
Range is an actual object, it’s simpler just to write:
int days = (startDate..endDate).size()
At least when I wrote the first version, I had a feeling I was making it too complicated.
Moving on to Grails, I wanted to have a “days” property on my
Course class, but it’s a dependent property. Its value is determined by the existing
startDate and
endDate properties. That meant I didn’t want to add it as a formal property, because that would imply the existence of a setter method as well as a getter. Also, it doesn’t exist in the database and doesn’t need to.
I couldn’t find an appropriate annotation in DGG, but a quick question on the mailing list cleared it up. My class now looks something like
class Course { int id Date startDate Date endDate String title // associations, toString() override, and constraints as usual transients = ['days'] int getDays() { return (startDate..endDate).size() } }
By providing the getter, I don’t need the attribute, which is a normal JavaBeans convention. By putting the property in the
transients closure, I’m telling Grails that it doesn’t have a corresponding column in the database.
Unfortunately, I found that when I tried using “days” as a property in
in a GSP, sorting on it didn’t work. I think that’s because the tag actually generates a database query with an
order by clause, and that’s going to be a problem with a property that doesn’t exist in the database.
I did realize I could compute my total number of training days in a one-liner:
Course.list()*.days.sum()
That uses the wicked cool spread operator, too. In my
CourseStatistics class I don’t actually make that list query more than once, but it’s nice to know I could.
I’ve been using Groovy and Grails for about a year now, and it’s nice to know they’re starting to sink in. 🙂
One small correction: ‘transients’ is not a closure. It’s a list
Cheers, | https://kousenit.org/2007/12/19/all-i-know-i-learned-from-gina-and-dgg/ | CC-MAIN-2017-34 | refinedweb | 616 | 70.63 |
Creating an SGraph
For the following SGraph exercises, we'll use the countries and results from two groups in the 2014 World Cup to explore SGraph construction, summarization, visualization, and filtering. To model this kind of data as a graph, we'll represent countries by vertices and game outcomes by directed edges. The source vertex for each edge is the losing team, and the destination vertex is the winning team. Ties are represented by including edges in both directions.
The following data was transcribed from the FIFA website.
countries = { 'usa': 'G', 'ghana': 'G', 'germany': 'G', 'portugal': 'G', 'england': 'D', 'italy': 'D', 'costa rica': 'D', 'uruguay': 'D'} results = [ ('portugal', 'germany'), ('ghana', 'usa'), ('portugal', 'usa'), ('usa', 'portugal'), ('usa', 'germany'), ('ghana', 'portugal'), ('ghana', 'germany'), ('germany', 'ghana'), ('england', 'italy'), ('england', 'uruguay'), ('england', 'costa rica'), ('costa rica', 'england'), ('uruguay', 'costa rica'), ('italy', 'costa rica'), ('italy', 'uruguay')]
Question 1:
Construct SFrames for the vertex and edge data.
verts = graphlab.SFrame({'name': countries.keys(), 'group': countries.values()}) print verts
+-------+------------+ | group | name | +-------+------------+ | G | ghana | | G | germany | | G | portugal | | G | usa | | D | uruguay | | D | england | | D | italy | | D | costa rica | +-------+------------+ [8 rows x 2 columns]
losers, winners = zip(*results) edges = graphlab.SFrame({'loser': list(losers), 'winner': list(winners)}) print edges
+----------+----------+ | loser | winner | +----------+----------+ | portugal | germany | | ghana | usa | | portugal | usa | | usa | portugal | | usa | germany | | ghana | portugal | | ghana | germany | | germany | ghana | | england | italy | | england | uruguay | | ... | ... | +----------+----------+ [15 rows x 2 columns]
Question 2: Make an empty SGraph.
sg = graphlab.SGraph()
Question 3: Add the vertices and edges to the graph.
sg = sg.add_vertices(verts, vid_field='name') sg = sg.add_edges(edges, src_field='loser', dst_field='winner')
Summarize and visualize the graph
Question 4: Summarize the graph. How many vertices and eges are there?
The summary method gives the number of vertices and edges in the graph, which is often the best place to start.
print sg.summary()
{'num_edges': 15, 'num_vertices': 8}
Question 5: Show the graph. Highlight the teams from North America, and use arrows to indicate the winner of each match.
sg.show(arrows=True, vlabel='id')
Question 6: Extract the vertices and edges as SFrames. Do the numbers of rows and edges match the summary?
The graph's SFrames for vertices and edges show there are indeed 8 vertices (with a 'group' attribute) and 15 edges (with no attributes).
sf_vert = sg.vertices print sf_vert
+------------+-------+ | __id | group | +------------+-------+ | ghana | G | | costa rica | D | | portugal | G | | usa | G | | england | D | | germany | G | | italy | D | | uruguay | D | +------------+-------+ [8 rows x 2 columns]
sf_edge = sg.edges print sf_edge
+------------+------------+ | __src_id | __dst_id | +------------+------------+ | ghana | portugal | | ghana | usa | | ghana | germany | | costa rica | england | | portugal | usa | | portugal | germany | | usa | portugal | | usa | germany | | germany | ghana | | england | costa rica | | ... | ... | +------------+------------+ [15 rows x 2 columns]
Filter the vertices
Question 7: Extract only the vertices in group H and plot the subgraph.
There are a couple ways to do this. The get_vertices command is the most straightforward, but filtering on the underlying SFrame is more flexible.
sub_verts = sg.vertices[sg.vertices['group'] == 'G'] # option 1 sub_verts = sg.get_vertices(fields={'group': 'G'}) # option 2 print sub_verts
+----------+-------+ | __id | group | +----------+-------+ | ghana | G | | portugal | G | | usa | G | | germany | G | +----------+-------+ [4 rows x 2 columns]
To materialize the subgraph, construct a new SGraph and add the edges of subgraph.
subgraph = graphlab.SGraph() subgraph = subgraph.add_edges(sg.get_edges(src_ids=sub_verts['__id'])) print subgraph.summary()
{'num_edges': 8, 'num_vertices': 4}
subgraph.show(vlabel='id', arrows=True, ewidth=2)
Compute vertex degree
The in-degree of a vertex is the number of edges that point to the vertex, the out-degree is the number of edges that point out from the vertex, and the degree is the sum of these two. In the context of our World Cup example, the in-degree is the number of wins and ties, and the degree is the total number of games for a given team. In this set of exercises, we'll use triple apply to compute the in-degree of each vertex. For more on vertex degree, check out the Wikipedia article.
Question 8: Define a function to increment the degree counts for an arbitrary source-edge-destination triple. This function should simply add 1 to the degree field for each of the source and destination vertices.
def increment_in_degree(src, edge, dst): dst['in_degree'] += 1 return (src, edge, dst)
Question 9: Create a new vertex field with in-degree set to 0 for each vertex.
Add the 'degree' field to the vertex attributes. Note that adding vertices with the same id's to the graph does not cause duplicate entries.
sf_vert['in_degree'] = 0 sg = sg.add_vertices(sf_vert)
Question 10: Use the triple apply function to compute in-degree for all nodes. Which team(s) did the best in the group stage?
sg = sg.triple_apply(increment_in_degree, mutated_fields=['in_degree']) print sg.vertices.sort('in_degree', ascending=False)
+------------+-------+-----------+ | __id | group | in_degree | +------------+-------+-----------+ | costa rica | D | 3 | | germany | G | 3 | | portugal | G | 2 | | usa | G | 2 | | uruguay | D | 2 | | ghana | G | 1 | | england | D | 1 | | italy | D | 1 | +------------+-------+-----------+ [8 rows x 3 columns]
Costa Rica and Germany did the best of these two groups in the group stage. If this is surprising, don't forget that we counted tie games twice. | https://turi.com/learn/userguide/sgraph/exercises.html | CC-MAIN-2017-47 | refinedweb | 847 | 62.48 |
React Native Tutorial: Building iOS Apps with JavaScript
In this React Native tutorial you’ll learn how to build native iOS and Android apps based on the hugely popular React JavaScript library.
Version
- Other, iOS 11, Xcode 9
) with React Native your code may be written in JavaScript but the app’s UI is fully native. It doesn’t have the drawbacks typically associated with a hybrid HTML5 app.
- Additionally (unlike Titanium), React introduces a novel, radical and highly functional approach to constructing user interfaces. Your UI is simply a function of the current app state.
React Native brings the React paradigm to mobile app development. It’s goal isn’t to write the code once and run it on any platform. The goal is to learn-once (the React way) and write-anywhere. An important distinction to make.:
Don’t worry if you’ve never written any JavaScript or used the CSS-like properties you’ll see. This tutorial will guide you through every step and provide resources where you can learn more.
Ready to get going? Read on!
Getting Started
React Native uses Node.js, a JavaScript runtime, to build your JavaScript code. If you don’t already have Node.js installed, it’s time to get it!
First install Homebrew using the instructions on the Homebrew website. Then install Node.js by executing the following in a Terminal window:
brew install node
Next, use
homebrew to;
- ios is a folder containing an Xcode project and the code required to bootstrap
your application
- android is a folder containing Android-related code, Metro Bundler, the React Native JavaScript bundler running under Node.js. export default class App extends Component<{}> { ... } // linking and importing libraries in Swift. It also uses what’s called a destructuring assignment to bring in the
Component object. Destructuring lets you extract multiple object properties and assign them to variables using a single statement.
ES6 is a much nicer way to write JavaScript, supporting features like default parameters, classes, arrow functions, and destructuring assignments. Apple has supported ES6 since iOS 10, but older browsers may not be compatible with it. React Native uses a tool called Babel to automatically translate modern JavaScript into compatible legacy JavaScript where necessary.
Back to App.js, check out the class definition:
export default class App extends Component<{}> {
This defines a class which extends a React
Component. The
export default class modifier makes the class “public”, allowing it to be used in other files.
Open index.js and take a look at the entry point file:
import { AppRegistry } from 'react-native'; import App from './App'; AppRegistry.registerComponent('PropertyFinder', () => UIKit classes; instead they are a lightweight equivalent. The framework takes care of transforming the tree of React components into the required native UI.
Next, replace the
const styles statement with the following:
const styles = StyleSheet.create({ description: { fontSize: 18, textAlign: 'center', color: '#656565', marginTop: 65, }, });
This defines a single style that you’ve applied to the description text. If you’ve done any web development before, you’ll probably recognize those property names. The React Native StyleSheet class used to style the application UI is similar to the Cascading Style Sheets (CSS) used on the Web.
Then, get rid of the
instructions assignment code block as you no longer need it.
Save your changes to App.js and return to the simulator. Press Cmd+R, and you’ll see your fledgling property search app starting to take shape:
That’s a JavaScript application running in the simulator, rendering a native UI, without a browser in sight!
Still don’t trust me? :] Verify it for yourself: within Xcode, select Debug\View Debugging\Capture View Hierarchy and take a look at the native view hierarchy. You will see no
UIWebView
App component, then constructs the native UIKit view.
Using JSX
Your current application uses
React.createElement to construct the simple UI for your application, which React turns into the native equivalent. While your JavaScript code is perfectly readable in its present form, a more complex UI with nested elements would rapidly become quite a mess.
Make sure the app is still running, then return to your text editor to edit App.js. Modify the body of
render to be the following:
return <Text style={styles.description}>Search for houses to buy! (Again)</Text>;
This is JSX, or JavaScript syntax extension, which mixes HTML-like syntax directly in your JavaScript code; if you’re already a web developer, this should feel rather familiar. You’ll use JSX throughout this article.
Save your changes to App.js and return to the simulator. Press Cmd+R, and you’ll see your application refresh to display the updated message: App App.js, find the import statements near the top and add a comma following the
View destructuring assignment. Then add the following below it:
NavigatorIOS,
This brings in
NavigatorIOS that you’ll use for navigation.
Next, replace the
App class definition with the following:
class SearchPage extends Component<{}> {
Add the following class below the
SearchPage component:
export default class App App.js. Add the following code to this file:
'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, TextInput, View, Button, ActivityIndicator, Image, } from 'react-native';
This imports the modules you’ll need to build the UI.
Add the following
Component subclass after the import statements:
export default class SearchPage extends Component<{}> { render() { return ( <View style={styles.container}> <Text style={styles.description}> Search for houses to buy! </Text> <Text style={styles.description}> Search by place-name or postcode. </Text> </View> ); } }
render is a great demonstration of JSX and the structure it provides. Along with the style, you can very easily visualize the UI constructed by this component: a container with two text labels.
Now, add the following style code at the bottom of the file:
const styles = StyleSheet.create({ description: { marginBottom: 20, fontSize: 18, textAlign: 'center', color: '#656565' }, container: { padding: 30, marginTop: 65, alignItems: 'center' }, });
Again, these are standard CSS properties. Setting up styles like this is less visual than using Interface Builder, but it’s better than setting view properties one by one in your
viewDidLoad():
Platform,
Text and
View.
Save your changes and return to the simulator to check out the new UI:
Styling with Flexbox
So far, you’ve seen basic CSS properties that deal with margins, paddings and color. However, you might not be familiar with Flexbox, a more recent addition to the CSS specification that’s useful for handling complex layout across different screen sizes.
React Native uses the Yoga library under the hood to drive layout. Yoga is a C implementation of Flexbox and it includes bindings for Swift, Objective-C, Java (for Android), and C# (for .NET).
Generally you use a combination of
flexDirection,
alignItems, and
justifyContent Yoga properties to manage your layout.
So far, your layout has a container with two children arranged vertically:
This is due to the default
flexDirection value of
column being active.
flexDirection helps define the main axis and cross axis. Your container’s main axis is vertical. Its cross axis is, therefore, horizontal.
alignItems determines the placement of children in the cross axis. Your app has set this value to
center. This means the children are center-aligned.
You’re going to see some other layout options at play.
Open SearchPage.js and insert the following just after the closing tag of the second
Text element:
<View style={styles.flowRight}> <TextInput style={styles.searchInput} <Button onPress={() => {}} </View>
You’ve added a view that holds a text input and a button.
In your styles definition, add the following new styles below the
container style:
flowRight: { flexDirection: 'row', alignItems: 'center', alignSelf: 'stretch', }, searchInput: { height: 36, padding: 4, marginRight: 5, flexGrow: 1, fontSize: 18, borderWidth: 1, borderColor: '#48BBEC', borderRadius: 8, color: '#48BBEC', },
These set the placement of the text input and button.
Save your changes and check the simulator to see your updates:
The text field and Go button are on the same row, so you’ve wrapped them in a container view using the
flowRight style which uses
flexDirection: 'row' to horizontally place the items in a row.
You’ve also added a
flexGrow: 1 style to the text input. Yoga first lays out the text input and button according to their sizes. It then distributes the remaining space according to the
flexGrow values. The text input therefore takes over the remaining space. assets alongside your components helps to keep your components self contained, doesn’t require the app to be relaunched if you add new images. It also provides a single place for adding images if you are building for both iOS and Android.
Back in SearchPage.js, add the following beneath the closing tag of the
View component that wraps the text input and button:
<Image source={require('./Resources/house.png')} style={styles.image}/>
Now, add the image’s corresponding style to the end of the style list:
image: { width: 217, height: 138, },
Save your changes and check out your new UI:
react-native startcommand you have in the terminal).
Your current app looks good, but it’s somewhat lacking in functionality. Your task now is to add some state to your app and perform some actions.
Adding Component State
A React component can manage its internal state through an object called, you guessed it,
state. Whenever a component’s state changes,
render() is called.
Within SearchPage.js, add the following code just before
render():
constructor(props) { super(props); this.state = { searchString: 'london' }; }
Your component now has a
state variable, with
searchString set to an initial value of
london.
Within
render(), change
TextInput to the following:
<TextInput style={styles.searchInput} value={this.state.searchString}
This sets the
TextInput value property — that is, the text displayed to the user — to the current value of the
searchString state variable. This takes care of setting the initial state, but what happens when the user edits this text?
The first step is to create a method that acts as an event handler. Within the
SearchPage class add the following method below the
constructor:
_onSearchTextChanged = (event) => { console.log('_onSearchTextChanged'); this.setState({ searchString: event.nativeEvent.text }); console.log('Current: '+this.state.searchString+', Next: '+event.nativeEvent.text); };
This defines a function using the
=> syntax. This is an arrow function, another recent addition to the JavaScript language that provides a succinct syntax for creating anonymous functions.
The function takes the value from the native browser event’s
text property and uses it to update the component’s state. It also adds some logging code that will make sense shortly.
Note: JavaScript classes do not have access modifiers, so they have no concept of
private. As a result you often see developers prefixing methods with an underscore to indicate that they should be considered private.
To wire up this method so it gets called when the text changes, return to the
TextInput field within the
render method and add an
onChange property so the tag looks like the following:
<TextInput style={styles.searchInput} value={this.state.searchString} onChange={this._onSearchTextChanged}
Whenever the user changes the text, you invoke the function supplied to
onChange; in this case, it’s
_onSearchTextChanged.
There’s one final step before you refresh your app again: add the following logging statement to the top of
render(), just before
return:
console.log('SearchPage.render');
Save your changes and return to your simulator.
You should see the text input’s initial value set to london. You should also see Xcode console logs when editing the text:
2017-11-26 23:00:31.847 [info][tid:com.facebook.react.JavaScript] SearchPage.render 2017-11-26 23:00:38.134 [info][tid:com.facebook.react.JavaScript] _onSearchTextChanged 2017-11-26 23:00:38.134 [info][tid:com.facebook.react.JavaScript] Current: london, Next: londona 2017-11-26 23:00:38.135 [info][tid:com.facebook.react.JavaScript] SearchPage.render
Looking at the console logs, the order of the logging statement seems a little odd:
- This is the initial call to
render()to set up the view.
- You invoke
_onSearchTextChanged()when the text changes.
- You call
this.setState()to schedule an update to the component state to reflect the new input text. This triggers another render.
- You log the current and the next search text values.
Note: You may see frequent log messages related to
nw_connection_get_connected_socket or
finished with error - code : -1001..
A React component state change triggers a UI update. This de-couples the rendering logic from state changes affecting the UI. Most other UI frameworks put the onus on you to update the UI based on state changes. Alternatively, the updates are done through an implicit link between the state and UI. For an example of the latter, see this article on implementing the MVVM pattern with ReactiveCocoa.
At this point you’ve probably spotted a fundamental flaw in this concept. Yes, that’s right — performance!
Surely you can’t just throw away your entire UI and re-build it every time something changes? This is where React gets really smart.
Each time the UI renders itself, it takes the view tree returned by your render methods, and reconciles — or diffs — it with the current UIKit view. The output of this reconciliation process is a simple list of updates that React needs to apply to the current view. That means only the things that have actually changed will re-render!
You can wrap your head around all that later; you still have some work to do in the app.
Initiating a Search
First, remove the logging code you just added above, since it’s no longer necessary.
In order to implement the search functionality you need to handle the Go button press, create a suitable API request, and provide a visual indication that a query is in progress.
Within SearchPage.js, update the initial state within the constructor:
this.state = { searchString: 'london', isLoading: false, };
The new
isLoading property will keep track of whether a query is in progress.
Add the following logic to the start of
render:
const spinner = this.state.isLoading ? <ActivityIndicator size='large'/> : null;
This is a ternary
if statement that optionally adds an activity indicator, depending on the component’s
isLoading state. Because the entire component is rendered each time, you are free to mix JSX and JavaScript logic.
Within the JSX that defines the search UI in
return, add the following line below the
Image to place the spinner:
{spinner}
Next, add the following methods to the
SearchPage class:
_executeQuery = (query) => { console.log(query); this.setState({ isLoading: true }); }; _onSearchPressed = () => { const query = urlForQueryAndPage('place_name', this.state.searchString, 1); this._executeQuery(query); };
_executeQuery() will eventually run the query, but for now it simply logs a message to the console and sets
isLoading appropriately so the UI can show the new state.
_onSearchPressed() configures and initiates the search query. This should kick off when the Go button is pressed.
To accomplish that, go back to the
render method and replace the
onPress prop for the Go
Button as follows:
onPress={this._onSearchPressed}
Finally, add the following utility function just above the
SearchPage class declaration:
function urlForQueryAndPage(key, value, pageNumber) { const data = { country: 'uk', pretty: '1', encoding: 'json', listing_type: 'buy', action: 'search_listings', page: pageNumber, }; data[key] = value; const querystring = Object.keys(data) .map(key => key + '=' + encodeURIComponent(data[key])) .join('&'); return '?' + querystring; }
urlForQueryAndPage doesn’t depend on
SearchPage, so it’s implemented as a free function rather than a method. It first creates the query string based on the parameters in
data. Then it transforms the data into
name=value pairs separated by ampersands. Finally, it calls the Nestoria API to return the property listings.
Save your changes, head back to the simulator and press Go. You’ll see the activity indicator spin:
Your Xcode console should show something like this:
2017-11-26 23:19:21.950 [info][tid:com.facebook.react.JavaScript]
Copy and paste that URL into your browser to see the result. You’ll see a massive JSON object. Don’t worry — you don’t need to understand that! You’ll add code to parse that now.
Performing an API Request
Still within SearchPage.js, update the initial state in the class constructor to add a
message variable to the end of the list:
message: '',
Within
render, add the following to the bottom of your UI, right after the spinner:
<Text style={styles.description}>{this.state.message}</Text>
You’ll use this to display a range of messages to the user.
Add the following code to the end of
_executeQuery:
fetch(query) .then(response => response.json()) .then(json => this._handleResponse(json.response)) .catch(error => this.setState({ isLoading: false, message: 'Something bad happened ' + error }));
This makes use of the
fetch function, which is part of the Fetch API. The asynchronous response is returned as a Promise. The success path calls
_handleResponse which you’ll define next, to parse the JSON response.
Add the following function to
SearchPage:
_handleResponse = (response) => { this.setState({ isLoading: false , message: '' }); if (response.application_response_code.substr(0, 1) === '1') { console.log('Properties found: ' + response.listings.length); } else { this.setState({ message: 'Location not recognized; please try again.'}); } };
This clears
isLoading and logs the number of properties found if the query was successful.
Note: Nestoria has a number of non-1** response codes that are potentially useful. For example, 202 and 200 return a list of best-guess locations.
Save your changes, head back to the simulator and press Go. You should see an Xcode console log message saying that 20 properties (the default result size) were found:
2017-11-26 23:22:18.478 [info][tid:com.facebook.react.JavaScript] Properties found: 20
Also note that when this message is logged, the spinner goes away.
It’s time to see what those 20 properties actually look like!
Displaying the Results
Create a new file SearchResults.js, and add the following:
'use strict'; import React, { Component } from 'react' import { StyleSheet, Image, View, TouchableHighlight, FlatList, Text, } from 'react-native';
This imports the relevant modules you’ll use.
Next, add the component:. Here’s a look at the
FlatList properties:
dataprovides the data to display
keyExtractorprovides a unique key that React uses for efficient list item management
renderItemspecifies how the UI is rendered for each row
Save your new file. and press Go. You’ll be greeted by a list of properties:
It’s great to see the property listings, but that list is a little drab. Time to liven things up a bit.
A Touch of Style
Add the following style definition at the end of SearchResults.js:
const styles = StyleSheet.create({ thumb: { width: 80, height: 80, marginRight: 10 }, textContainer: { flex: 1 }, separator: { height: 1, backgroundColor: '#dddddd' }, price: { fontSize: 25, fontWeight: 'bold', color: '#48BBEC' }, title: { fontSize: 20, color: '#656565' }, rowContainer: { flexDirection: 'row', padding: 10 }, });
This defines all the styles that you are going to use to render each row.
Add a new component representing a row by adding the following just under the import statements:
class ListItem extends React.PureComponent { _onPress = () => { this.props.onPressItem(this.props.index); } render() { const item = this.props.item; const price = item.price_formatted.split(' ')[0]; return ( <TouchableHighlight onPress={this._onPress} <View> <View style={styles.rowContainer}> <Image style={styles.thumb} source={{ uri: item.img_url }} /> <View style={styles.textContainer}> <Text style={styles.price}>{price}</Text> <Text style={styles.title} numberOfLines={1}>{item.title}</Text> </View> </View> <View style={styles.separator}/> </View> </TouchableHighlight> ); } }
This manipulates the returned price, which is in the format 300,000 GBP, to remove the GBP suffix. Then it renders the row UI using techniques that you are by now quite familiar with. Of note, an
Image is added to the row and is loaded from a returned URL (
item.img_url) which React Native decodes off the main thread.
React.PureComponent. React re-renders a
Componentif its props or state changes. React only re-renders a
PureComponentif a shallow compare of the state and props shows changes. Used under the right conditions, this can give your app a performance boost.
Now replace
_renderItem with the following:
_renderItem = ({item, index}) => ( <ListItem item={item} index={index} onPressItem={this._onPressItem} /> ); _onPressItem = (index) => { console.log("Pressed row: "+index); };
_onPressItem is passed into
ListItem to handle a row selection. This design pattern is equivalent to a callback. In this callback, the index for the selected row is logged.
Save your work, head back to the simulator, press Go, and check out your results:
That looks a lot better — although it’s a wonder anyone can afford to live in London!
Tap the first row and check that the Xcode console reflects the selection:
2017-11-26 23:29:19.943 [info][tid:com.facebook.react.JavaScript] Pressed row: 0
Try tapping other listings or searching other locations in the UK.
Where To Go From Here?
Congratulations on completing this React Native tutorial! You can find the complete project here if you want to compare notes. :]
As a challenge, try showing a property’s details when the user selects one from the search list. You can check out the challenge solution if you get stuck.
npm installvia the Terminal in the root folder of the project.
Check out the React Native’s source code if you’re curious. I suggest taking a look at this ES6 resource to continue brushing up on modern JavaScript.
If you’re a web developer, you’ve seen how to use JavaScript to easily create a native app. If you’re a native app developer, you’ve gained some appreciation for React Native’s fast iteration cycle. Whether you decide to use React Native in a future app or simply stick with Swift, I hope you’ve learned some interesting principles to apply to your next project.
If you have any questions or comments on this React Native tutorial, feel free to join the discussion in the forums below! | https://www.raywenderlich.com/485-react-native-tutorial-building-ios-apps-with-javascript | CC-MAIN-2021-17 | refinedweb | 3,631 | 57.37 |
The First Annual Underhanded C Contest 341
Posted by CowboyNeal
from the delightfully-malicious dept.
from the delightfully-malicious dept.
Xcott Craver writes "We have just announced a new annual contest, the Underhanded C Contest, to write clear, readable, innocent-looking C code that implements malicious behavior. The object is to hide evil functionality that survives visual inspection of the source. The prize is beer."
The prize is beer... (Score:5, Funny)
"Sending bestiality porn to my mom and boss with my face cut and pasted from my iPhoto library, ho ho! didn't see that one coming... FIRST PRIZE!"
how's this? (Score:5, Funny)
Re:how's this? (Score:3, Informative)
What you really want is something more subtle. For example, here's an easy one using rounding errors in the core of a smoothing algorithm. Assumes a picture of width x height of type "RGB" (assumed to be a typedef'ed struct containing bytes r, g, and b) in a two-dimensional array called
This will work (Score:4, Funny)
Re:This will work (Score:5, Funny)
Seems a bit like those hacking contests (Score:2)
Re:Seems a bit like those hacking contests (Score:5, Informative)
I mean I could do something like this:
# When do you want it done?
$today="sudo";
$yesterday="su -c";
# Define our globals
$superman="ls";
$wonderwoman="rm"
$bat
$aquaman="mv";
#define some important flags
$blows="-r";
$maims="-p";
$chunks="-f";
#define some targets
$your_mom="/";
$your_dad="/usr";
$your
$your_teacher="/bin";
$hell="/dev/n
$heaven="/dev/random";
$skyhigh="nfs://mys
#....later, back at Superfriends Headquarters
`$batman $blows $your_sister $skyhigh`;
`$wonderwoman $blows $chunks $on $your_sister`;
`$today $batman $and $your_mom $think $heaven $is $a $great $place $for $your_sister`;
#Would you like to see the rest of the story?
#print "Would you like to hear more? Please type your password to continue!";
The superfriends save the day again.
Re:Seems a bit like those hacking contests (Score:2)
It tried to remove the home directory itself!
Couldn't do it and it gave up without damaging any files.
Only severely misconfigured UNIX systems allow deleting one's own home directory, because the directory above your home, which is what you need permission on, you don't have write (you don't have
Nice as a proof of concept, but won't work anymore.
Re:Seems a bit like those hacking contests (Score:2)
in other words... (Score:4, Funny)
Re:in other words... (Score:4, Insightful)
Yes, I know that must come as a shock, and most people here probably won't believe me...yet it's true.
(And just to head off the inevitable nutcase looking for a Score:5, Funny: no, replacing the prize with free pr0n isn't going to cut it.
Re:in other words... (Score:3, Funny)
There you programmers go again... (Score:2)
Seriously, though, this is (obviously) a lot like the obfuscated c contest, but it's a cool idea, in that there's an important lesson to learn about evaluating code.
Re:There you programmers go again... (Score:3, Insightful)
Beer (Score:2)
Re:Beer (Score:3, Interesting)
It really just depends on what kind of plane you're talking about. I'm sure there's areas on even modern large-body jets where there's an uninsulated section large enough for a keg.
Beer? Phui! (Score:2, Funny)
The prize is world domination!
It's a bad idea (Score:3, Interesting)
C is a superb language. Why besmirch its reputation with a contest to make it seem as untrustworthy as possible?
Re:It's a bad idea (Score:5, Insightful)
Java gives you a polished floor on which you can slip and break your neck.
C++ gives you a thermo-nuclear device.
Re:It's a bad idea (Score:4, Funny)
Source [york.ac.uk]
Why assume C-specific tricks? (Score:2)
C is an awful language (Score:2, Informative)
You're just not used to it. (Score:5, Insightful)
A picky compiler is a blessing, not a curse. It's much easier to identify and fix compile errors than run-time errors.
difficult to convert to better languages (thank you preprocessor)
Meaningless troll.
encourages obfuscation
Unless the compiler is literally holding a gun to your head, this is meaningless. In C you have nearly limitless control to write your code the way you feel is clearest. If it came out obfuscated then you have nobody to blame but yourself.
some constructs are clearly tacked on and/or poorly implemented (switch), arbitrary nonorthogonality (struct, parens and brace usage, pointer/array declaration), shitty strings.
Tacked on? If you don't like the way constructs are set up then fine, that's your opinion. But if you read The C Programming Language you can tell that every single construct was scrutinized over for the proper balance of efficiency (why it makes sense to pass array parameters as pointers and structs as copies) and consistency (why data types are declared the way they are. Declaration and use of data is made to match.) Do you honestly believe the creators/first users of C, some of the greatest programmers who ever lived, really said, "Ahhh, fuck it. Let's just throw something together," when designing their own programming tools?
Most people who don't like C are really just saying they don't like low-level programming because that's what it was designed for, and that's what it's perfect for. Too many newbie programmers get used to some modern, flash-in-the-pan, all-things-to-all-people languages and when they are faced with the challenges of low-level languages rashly conclude that it's the language's fault they're having problems.
C is the perfect language for the job it was designed for. The same cannot be said for most more modern languages.
Re:You're just not used to it. (Score:3, Insightful)
I'm not sure about strings. With the really low level stuff like OS development, I can see th
Re:You're just not used to it. (Score:3, Insightful)
Clarity. All the data types in C are intended to be clear. It's only a single step up from assembly, really. C handles strings the same way assembly does: it eats bytes sequentially from an array, and it's up to the programmer to tell the program when it's had enough. Data handling in C is a virtually transparent veneer of abstraction from pointer arithmetic. A string
Re:You're just not used to it. (Score:3, Insightful)
I think you're confusing C with a high-level language. It doesn't give you lists, associative arrays, or strings because those are high-level data types and C is a low-level language. Your complaints are like saying the biggest problem with a car is you can't drive it on water -- they display a fundamental misunderstanding of the subject.
Re:You're just not used to it. (Score:4, Insightful)
Are you really going to want to wait 100s of milliseconds for a garbage collector to run at arbitrary intervals in your carefully word aligned DMA transaction code that needs to run within a matter of microseconds? And how exactly is Python, LISP, or any other interpreted/dynamic runtime compiled language going to be used to write a task scheduler or memory managment system worthy of being used in an OS kernel or embedded MCUs with barely 16KiB RAM?
I think you're quite bitter about having to use C for writing applications, which I can perfectly understand. As for what C is actually MEANT for, it does the job quite well. And yes, the preprocessor issues suck, and it would be nice to have Pascal strings, but there really is no alternative to C that I have seen for low-level programming. It makes computer science purists who think everyone should program in Haskell or LISP feel dirty, but it does the job very well. It sure beats writing directly in ASM.
Re:C is an awful language (Score:4, Insightful)
C is good for what it was first used for: writing Unix. At least initially, it was mimimalistic; orthogonality took a back seat to ease of implementation. (See Gabriel's classic essay [jwz.org] for details.)
(It's certainly not flawless. Any language that needs a utility like cdecl to make declarations understandable has problems, and there should've been a Boolean type from the beginning. It would be nice if char (which should be whatever represents a glyph on the target system) weren't conflated with short short int. Basically, if C were in your back yard, it would be declared an "attractive nuisance.")
I think the authors of The Art of Unix Programming wisely recognize that C, like any other tool, should be used only where appropriate. (Sorry if that's tautological, but I can't think of a better way to put it.)
Re:Indeed. This could be a field day for Java and (Score:3, Informative)
Re:Indeed. This could be a field day for Java and (Score:2, Insightful)
Re:Indeed. This could be a field day for Java and (Score:3, Insightful)
Actually, that's not really the case... not for the kind of "malicious code" that they're talking about here. They're not talking about "getting out of the sandbox", they're talking about "hiding information in the output". It's actually a lot easier to hide this kind of "malicious code" in an object-oriented language because you can play games with the namespace.
Re:Indeed. This could be a field day for Java and (Score:4, Informative)
Please check out the contest page: the "evil" behavior is not something java would prevent you from doing. We're not talking about crashing a computer or gaining root access, but performing a data processing task incorrectly. It's entirely problem state.
That being said, I chose C because it does permit more tricks along the lines of stack smashing and type mismatches. The winners of the obfuscated V contest used techniques like this to conceal their evil behavior, so I feel this would give people more freedom to get creative.
Finally, this is not meant to slam C, or open source, or any such like. I can't imagine how anyone can look at this contest and see it as an argument for less openness.
Xcott
Re:Indeed. This could be a field day for Java and (Score:2)
There are tons of C programs that look valid, but given some prompting can behave in arbitrarily evil ways.
If you want it to automatically behave in an evil way without a "little extra encouragement" then I suppose it would be a bit harder.
Story is just plain bad (Score:3, Insightful)
Yeah, I just flip the "+good +bad -malicious" flags on javac when I want to trust code. Come on
Re:Story is just plain bad (Score:3, Informative)
Have you seen Technocrat.net [technocrat.net]? Looks to be just starting, but I'm already impressed: slashdot ran an article on a nanotech textiles protest - technocrat ran one on a group of scientists demonstrating a refined iteration of a carbon nanotube CPU. Comments are on-topic too, touch wood.
(Or there's always ars [arstechnica.com] for CS stuff, but they're hardly a
So are you very, very good or very, very bad? (Score:2)
If you sincerely believe this is not a hard task, then you're either very, very good at programming, or really not very good at all.
Most developers aren't very good at writing clear, concise code that actually does what it's supposed to. Writing code of that quality that looks like it does what it's supposed to do, while actually doing something subtly different, sounds like a very difficul
C-style vs Java-style language features (Score:2)
I assume you're joking, since Java is as vulnerable to typical attacks like SQL injection just as much as many other languages, with just the same sort of careless slip in a couple of lines by a tired programmer...
If crashing is "malicious behavior" (Score:2)
Re:If crashing is "malicious behavior" (Score:2)
Re:If crashing is "malicious behavior" (Score:2)
Hmmm
There are more lines of non-crashing, non-malicious, well-designed, and well-tested lines of C out there than most other programming languages.
Re:If crashing is "malicious behavior" (Score:3, Funny)
Nope. Only the code that includes
#include <windows.h>
*ducks*
How will the judges be able to trust this code? (Score:2)
Re:How will the judges be able to trust this code? (Score:2)
The judges will expect that (Score:2)
If they didn't do this, you can bet that someone would try to write a program which would detect competitors' programs running and disable them.
I think I might win (Score:4, Funny)
main()
{
printf("Hello World");
}
Seemingly harmless, right? Wrong. It's still in devlopment, but think about it. You should have to greet the world before you destroy it.
I think this is more appropriate (Score:3, Funny)
main() { printf("Goodbye World!\n"); }
Re:I think I might win (Score:2)
This year's challenge (Score:2)
Re: This year's challenge (Score:5, Informative)
Why, yes! [sourceforge.net]
Re: This year's challenge (Score:2)
Re: This year's challenge (Score:2)
Re: This year's challenge (Score:2)
Well, if you're Yoda, then you can just use the Force to do it.
my submission (Score:2)
Strange (Score:2)
like this? (Score:5, Funny)
void main()
{
screensaver(); * function */
anyone that thinks there is * / needs */
}
585
Re:like this? (Score:5, Funny)
Re:I'll take the bait (Score:3, Informative)
You are correct. This is from ISO/IEC 9899:1999(E):
Attack the Compiler (Score:5, Interesting)
You need only attack the compiler, or the linker, or the interpreter.
Re:Attack the Compiler (Score:2)
Re:Attack the Compiler (Score:2, Informative)
Re:Attack the Compiler (Score:3, Insightful)
I guess the thing is: What we're really concerned about here, (if I may project a little,) is voting software.
In those cases, they're probably not going to say, "download the compiler from a random site on the net." In fact, it's probably going to be very hard to control the people who compile the software, and even harder to control the people who compile the compiler. At some point, somebody's going to get the compiler, and they're going to get it from some specified place.
If it's a se
Here you go (Score:5, Funny)
Just tuck it away in a commonly used header file, use touch to restore the last date/time of modification, and you're all set.
#define void int
Hours & hours of irritation & confusion!
T&K.
Diebold (Score:2, Insightful)
Now if only we can get them to enter their code in the contest...
Re:Diebold (Score:3, Funny)
It's supposed to survive inspection, remember. giveElectionToTheRepublican() is underhanded, but it probably won't survive inspection.
Why? (Score:4, Insightful)
Who is behind this and what is their motivations? What will they do with the ideas submitted in this contest? In a day of professional computer hackers, this is not a contest to have.
Re:Why? (Score:5, Insightful)
It is sort of like the computer version of a bomb squad.
Re:Why? (Score:3, Informative)
Something like:
if (blah || blah || uid=0) {
blah;
}
Re:Why? (Score:2)
OR
Having contests like these creates a sample base of dangerous code and clever tricks that evil doers can use to craft subtley malicous code in open source projects.
Re:Why? (Score:2)
Who is behind this and what is their motivations? What will they do with the ideas submitted in this contest? In a day of professional computer hackers, this is not a contest to have.
Dicionary.com describes simulacrum [reference.com] as,
1. An image; a representation.
2. An insubstantial, superficial, or vague likeness or semblance.
So, Mr Simulacrum25 (if that is indeed your real name!), care to tell us why you're so scared of other people looking in to ways of secretly concealing informatio
Re:Why? (Score:4, Informative)
Is Google down? Okay, I updated the faq to tell you who we are.
Also, we never said anything about hackers. Nowhere have we associated hacking with malicious behavior. And I sincerly hope this will be a learning experience for all involved. I, in particular, will probably learn a thing or two about running next year's contest.
Xcott
Here's my entry: (Score:3, Funny)
root (hd0,0)
chainloader +1
Now where's my beer?
Diebold Hiring the winner! (Score:4, Funny)
Diebold needs new programmers. If you have what it takes to hide "winning" code in our election machines. Apply to Diebold Careers [diebold.com]
Cheating? (Score:3, Funny)
Would the Windows source code count? (Score:2, Funny)
Subtlety (Score:5, Funny)
Re:Subtlety (Score:2)
Re:Subtlety (Score:2)
Obligatory simpsons paraphrase (Score:5, Funny)
Judge: 'That's bad.'
Programmer: 'But it's optimized for PowerPC!'
Judge: 'That's good!'
Programmer: 'PowerPC is also cursed.'
Judge: 'That's bad.'
Programmer: 'But you get your choice of operating systems!'
Judge: 'That's good!'
Programmer: 'The operating systems run on Intel.' *pause* 'That's bad.'
Judge: 'Can I go now?'
Re:Subtlety (Score:3, Informative)
I've tried their Rare Vos, Hennepin, and self-named Ommegang beer: my favorite is the Rare Vos but I like them all.
Obscurifacation (Score:2)
Especially useful on large programs it pretty much made the source totally unreadable, and a complete headache to try to unravel even if you countered with a similar program - because all meaning in the origin
An example from years ago (Score:5, Interesting)
Re:An example from years ago (Score:4, Informative)
Some dude from Microsoft is gonna win... (Score:5, Funny)
He'll submit the source code to IE.
When will we see this pop up in the real world? (Score:2, Interesting).
Oh dear, now we're rewarding people for writing actual malicious code that is designed to pass visual inspection from other programmers.
When these s
The prize is beer (Score:2)
Well, nothing could go wrong here, since we all know that all C programmers are over 21. And if by any chance the winner wasn't over 21 they would make that clear and refuse their prize.
The next day the headlines read" " C Programmers Give Minors Beer, Drunken Night of Celebration Kills 6 in Traffic Acciident ". Reactionary congressmen urged on by a powerful lobby from Washington State quickly pass laws to outlaw all C programming outside of Microsoft.
here's my entry (Score:4, Funny)
easy (Score:2, Interesting)
Service Pack fixes it, but it's documented (Score:5, Informative)
Linux Kernel Backdoor Attempt (Score:5, Informative)
The attempt was trying to insert
if ((options == (__WCLONE|__WALL)) && (current->uid = 0))
inside a function. Note that (current->uid = 0) is not testing but rather sets the UID to zero (and the surrounding brackets avoid the GCC warning).
So The Hard Part Is To (Score:5, Funny)
Wow, nobody's going to win this one.
Vectors (Score:3, Informative)
A way to automatically find this would be to use an execution tracer that would alert you when the programs point of execution "left" it's source code or allowed system api's.
Volunteer to help out! (Score:3, Interesting)
This would make the test more like the real world too.
Re:What are the legal ramifications of this? (Score:3, Funny)
Re:What are the legal ramifications of this? (Score:3, Informative)
RTFA, please.
The challenge for the first UCC is to write a simple program that performs some basic image-processing operation, for example smoothing or resampling, but manages to conceal a unique imperceptible fingerprint in each image it opens.
The fingerprint should be different for every execution of the program. It doesn't have to have any particular meaning, but useful tracking information is worth extra points (tho getting caught is worth fewer points.) The print should be extractable from the o
Re:What are the legal ramifications of this? (Score:2)
Are you serious? Entrapment is an undercover cop asking you if you want to buy drugs, then when you say no, he tries to persuade you and suceeds, possibly becuase you just want him to go away.
It's really not that easy for something to qualify as entrapment, also consider that writing malicious code isnt illegal, it's free speech and no different then writing a book that urges people to do something malicious, not at all illegal.
But no please, keep thinking everything is illegal and dont bother doing
Re:What are the legal ramifications of this? (Score:4, Insightful)
The authorities start a contest such as this, an unsuspecting programmer submits a malicious program, and he or she is arrested and charged with a variety of computer crimes.
What computer crimes would be broken?
Frankly, I won't participate in this contest considering the current legal state of America.
No, you won't participate because of yor current state of paranoia over the legal state of America.
Re:What are the legal ramifications of this? (Score:5, Funny)
Re:SxE anyone??? (Score:3, Funny)
What if someone in the straight edge crowed wins?
They can give the beer to me.
Re:SxE anyone??? (Score:2)
Re:Possibly obfuscated intentions (Score:2)
It also means that an army of coders have considered and may recognize numerous different approaches to hiding this kind of watermarking. | http://tech.slashdot.org/story/05/06/11/1341244/the-first-annual-underhanded-c-contest | CC-MAIN-2014-10 | refinedweb | 3,641 | 63.7 |
How can we convert from String to Hex in java
This code is part of AES encryption algorithm, I have this method that return the encrypted value as: String I need it to return the result as Hex instead .
public static String encrypt(String Data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGO); c.init(Cipher.ENCRYPT_MODE, key); byte[] encVal = c.doFinal(Data.getBytes()); String encryptedValue = new String( Base64.getEncoder().encode(encVal) ) ; return encryptedValue;}
I am trying to convert a string like "testing123" into hexadecimal form in java. I am currently using BlueJ.
And to convert it back, is it the same thing except backward?
While importing data from a flat file, I noticed some embedded hex-values in the string (
<0x00>,
<0x01>).
I want to replace them with specific characters, but am unable to do so. Removing them won't work either.What it looks like in the exported flat file: example:
This is what I've tried: (and mind,
<0x01> represents a none-editable entity. It's not recognized here.)
import iowith io.open('1.txt', 'r+', encoding="utf-8") as p: s=p.read()# included in case it bears any significance
import reimport binasciis = "Some string with hex: <0x01>"s = s.encode('latin1').decode('utf-8')# throws e.g.: >>> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 114: invalid start bytes = re.sub(r'<0x01>', r'.', s)s = re.sub(r'\\0x01', r'.', s)s = re.sub(r'\\\\0x01', r'.', s)s = s.replace('\0x01', '.')s = s.replace('<0x01>', '.')s = s.replace('0x01', '.')
or something along these lines in hopes to get a grasp of it while iterating through the whole string:
for x in s: try: base64.encodebytes(x) base64.decodebytes(x) s.strip(binascii.unhexlify(x)) s.decode('utf-8') s.encode('latin1').decode('utf-8') except: pass
Nothing seems to get the job done.
I'd expect the characters to be replacable with the methods I've dug up, but they are not. What am I missing?NB: I have to preserve umlauts (äöüÄÖÜ)
-- edit:
Could I introduce the hex-values in the first place when exporting? If so, is there a way to avoid that?
with io.open('out.txt', 'w', encoding="utf-8") as temp: temp.write(s)
This question already has an answer here:
I have this String
c9e9a0f30c56fc4881f09b65070ecf6ad65f2a51bc910fd5 composed of hexadecimal characters only. Correct me if I'm wrong but a character on a String takes a byte for its representation right? But since a hexadecimal character fits in 4 bits I could fit two characters in a byte. Is there a simple way to do this in Java?
Thank you in advance! You guys rock!
Declaration of a method are following:
//some.hvoid TDES_Decryption(BYTE *Data, BYTE *Key, BYTE *InitalVector, int Length);
I am calling this method from the following code:
//some.cextern "C" __declspec(dllexport) bool _cdecl OnDecryption(LPCTSTR stringKSN, LPCTSTR BDK){ TDES_Decryption(m_Track1Buffer, m_cryptoKey, init_vector, len); return m_Track1Buffer;}
Where as data type of
m_Track1Buffer is
BYTE m_Track1Buffer[1000];Now i want to make some changes in above method i.e. want to return the
String in hex instead of
Byte. How should i convert this
m_Track1buffer to
Hex string. | https://www.convertstring.com/it/EncodeDecode/HexDecode | CC-MAIN-2019-18 | refinedweb | 541 | 58.38 |
Agenda
See also: IRC log
<Roland> trackbot, start telcon
<trackbot> Date - 23 April 2009
<Steven> can anyone hear me speaking?
no, steven
<scribe> Scribe: Gregory_Rosmaita
<scribe> ScribeNick: oedipus
RM: each item will have 30 minutes devoted to it
SP: Yves will be joining us on ITS integration at 1400h UTC
<Steven>
RM: what do we need to cover with Yves
SP: 3 options: inline similar to inline styling; put in head as meta info, or use XLink
MG: should as to use LINK element
not XLink
... XLink one of many ways, so not a hard and fast requirement; do we want to do everything? has its own ruby module, translation stuff
... elements in legacy documents without changing them through external XSLT; use XPath to indicate were should be applied; referencing implementations - required to prove works
SP: is ITS out of CR?
SM: yes, been a rec for quite some time
SP: if referring to existing technologies, is ok
RM: what is minimum we can do?
SP: LINK element to ITS rules
RM: still doesn't limit exposure
- still have to understand everything in ITS
... should we be incorporating required ITS features
... what is appropriate to us
MG: ok to just pick a sub-set
RM: yes
MG: ITS namespace has own ruby
module - no link or dependency on Ruby spec itself
... should we consider switching to ITS 1.0?
SP: asked about this - also have own SPAN element
MG: correct
SP: requires a SPAN-like and
Ruby-like element -- provided in cases where don't have them,
but if available can use
... should check that interpretation with Yves
SM: their Ruby brought into line with Ruby Rec at some point
MG: couldn't find any differences - inline ruby element names and behaviors seem same as in Ruby spec
SM: fundamental question: to what
extent can we sub-set this given our current
functionality
... are we going to incorporate ITS as part of their namespace or ours?
... my vote is: do it in their namespace
SP: agree
GJR: agree
SP: if just point to set of rules
rather than inline, only case that arises is its:translate
attribute
... propose bringing its:translate into XHTML2
SM: as an attribute in their namespace
SP: yes
... what we are missing is "translate"
SM: inline ITS is a sticking point -
SM: not bring in all elements, but bring in things like "translation" referenced to their namespace
SP: questions: 1) does spec allow
us to use our native SPAN and RUBY and dir; 2) are you ok with
only external ITS; can we use "ref" with LINK to accomplish
this?? what would be the rel value
... how do they do that in XLink
<ShaneM> <link rel="itsRules" ... ?
<ShaneM> oooh. use CURIEs <link rel="its:rules"
SP: could suggest its:rules "rel" value
SM: would have to declare its
prefix vocab mapping
... also ITS namespace has to be the same
SP: already an ITS namespace with
value rules in it
... its:rules element
SM: correct
<Steven>
SM: could show them how to annotate as RDF
<ShaneM> There's no there-there right now
SP: no, this is more a namespace question, although there is a GRDDL version i thought i came across
SM: like idea of using CURIEs - use their vocabularies and have it just work
<Steven> <link>
<Steven> <link rel=�ts:rules" href="...."/>
SP: what is missing is version info
RM: LINK in HEAD and nowhere
else
... allow its:translate on one of our elements
SM: vocabulary concatonated to name
MG: can take Qname, right?
SP: syntaxically similar to Qname
<Steven> a qname is a subset of curie
MG: MarkB - advised use of Qnames along with role values - is that right?
SM: interesting question
... can put anything want in quotation marks, but conforming RDFa parser not going to allow triples
... Qname doesn't map to IRI like CURIE
SP: ah
... P3P has reserved value for "rel" to do roughly the same thing
<Steven> rel="p3pv1"
<Steven> (note version info)
SM: from implementation report
and conformance language, we conform by virtue of having a
native SPAN attribute
... one must be available: SPAN, RUBY; if Ruby used, declare inline, if SPAN used, use as inline element
... did provide us with module as per our request
... also support ITS in M12n?
<markus> Birbeck discussing QNames in @role:
<Roland> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<Roland> <html xmlns=""
<Roland> xmlns:its=""
<Roland> xml:
<Roland> <head>
<Roland> <title>its</title>
<Roland> <link href="../its.." rel="its:rules" type="??" />
<Roland> </head>
<Roland> <body>
<Roland> <p its:Grrrr</p>
<Roland> </body>
<Roland> </html>
proposed questions now at
GJR: apply to XHTML2 only or to 1.2?
RM: first agree on framework, then retrofit
shane, Yves will join at
RM: other i18n issues to discuss?
[none logged]
RM: order of agenda items: Access first?
<Steven>
SM: clear to move Access to second LC - put out new draft this morning and updated disposition of comments
<Steven>
SM: happy to let draft go to LC
RM: just needs a bit of editorial tidying, but ready to go, so should start process
SM: yes
... chicken and egg problem: Access refers to CURIEs CR draft; changed CURIEs so doesn't have prefixing mechanism, putting onus on host language; Access isn't a host language, so we should be ok
RM: assuming HCG has no problem with this tomorrow, can immediately ask for XHTML Access to go back to Last Call
SM: should be more specific about whom we need to comment on Access
RM: have to address concerns brought up by PF and i18n
SP: some SVG stuff as well?
SM: no last call comment from SVG in disposition/issue tracker
GJR: PF has a long standing
clarification request about abiility to mix targetid and
targetrole in the @order attribute
... PF wants to know if is permissible
PFWG ACTION-211 - query XHTML2 and SVG on wheter mixing roles and ids with targetrole and targetid for @order is ok or problemmatic
<ShaneM> we got your voice mail
SM: in ACCESS element description must have targetrole OR targetid specified - if not present, mapping ignored
<Steven> sorry, problems with phoen here. Trying another
SM: not permitted in Access element - can have one or the other, can't have both
GJR: will communicate that to PF
<Steven> oh no
RM: user agent must only use targetid attribute values
<Roland> "If a targetid and a targetrole are both specified for an element, a user agent MUST only use the values from the the targetid attribute."
RM: have resolution from 2009-04-22 telecon to cycle Access Module back through Last Call
<Steven> Gregory: When I go to banking services, the forms are half declarative, and half procedural
<Steven> ... I need a role value to express this
<Steven> ... some people are worried this would hold up ARIA
<Steven> Shane: Add it to the role module!
SM: nothing to do with ARIA - just define "form" in Role Module and be done with it
GJR: fine with me
RM: return to ARIA later;
SM: updated CURIE spec - removed xmlns stuff and produced new editor's draft
SM: changes CURIE into a datatype
with a defines mapping with value space
... does it poorly, but does the job - can't find a better way anyway
... may get push-back from people who feel this change is too large
... already have 1 comment to that effect
MG: wasn't there an email that said up to host language to perform binding, so how can one have generic CURIE processor
SM: can't
... always permitted alternate prefix mapping mechanisms
SP: introduced to open hole to allow it to be inserted into HTML5?
SM: what?
SP: leaving it to host language
<Roland>
SM: no, another objection; didn't want to use xmlns as prefix mechanism
MG: concerned about Role Module
forcing HTML vocab to be default one
... ability to redefine vocab is separate but legitimate issue
SM: objection from a reviewer that didn't want to be forced to use xmlns - we thought that reasonable
SP: strong argument against having to go to LC again
<markus>
<Roland>
SP: if reviewer still objects - can state can have 1 or the other, but not both - going back to LC won't solve that problem
SM: generic processor never practical
<Roland> Includes: " I don't see how you can get out of CR to PR, looking at your implementation report. At this stage, I'm now asking Sean, my AC rep, to oppose such a transition."
SM: should finish collecting
tests into a "test suite"
... do we need a "test suite"?
... for CURIEs? think we have one anyway -- just point to RDFa and be done with it
... could identify sub-set of relevant tests
RM: wasn't there a concern about a feature that RDFa doesn't use
SM: datatype, which isn't a
feature; a lot of CURIE features not used by RDFa -- allow
alternate prefix mapping mechanisms, etc.
... no default prefix
... if CURIE starts with a colon, don't define meaning for that in RDFa
... or a CURIE without a colon - in car, can't check
... MarkB had deemed those "reserved values"
MG: so what if CURIE does start with colon?
SP: prefix without colon -
section 7 in RDFa "Module" defines how work with CURIEs with
rules
... can leave out prefix according to CURIE document
SM: should say "for each of those, host languages may define a rule or mechanism to establish default prefix"
SP: "when prefix omitted from
CURIE" doesn't cover the colon question
... if just put colon in front, use default prefix
SM: right
SP: got it
SM: agree that there are aspects
of CURIE that RDFa does not use; isn't requirement that test
suites be comprhensive, but all features of spec have to be
used in 2 independent implementations
... we need to decide if satisfied criteria
... but that doesn't necessarily require a test suite
SP: have usage in RDFa, OWL
RM: aren't talking about implementations of those languages are we?
SP: can point to implementations of RDFa as implementation of CURIEs
SM: agree
SP: have a dozen of those
RM: markup languages include: OWL
SM: OWL WG said won't use CURIEs
RM: including OWL is a bit of a stretch then
SM: yes
... rolled their own rather than reuse CURIEs
<Roland>
RM: Last Call WD - 20 April 2009 - should send feedback
SM: part of SemWeb activity, which is origins of CURIEs so makes sense for us to eat our own dog food
RM: strange that didn't request
feedback specifically from us since working on similar
mechanism
... can we get comment from RDFa task force?
<scribe> ACTION: Shane - get RDFa task force to contribute to, sign onto or issue CURIE comment on Last Call draft of OWL2 [recorded in]
<trackbot> Created ACTION-76 - - get RDFa task force to contribute to, sign onto or issue CURIE comment on Last Call draft of OWL2 [on Shane McCarron - due 2009-04-30].
RM: doesn't seem like a coordinated approach within SemWeb
SM: CURIEs useful in SPRQL
... way to view CURIEs is as datatype with some requirements on host language
SP: just like a URI
OWL1:
RM: comment date is 12 May 2009 - need to be expeditious
<Roland>
<Roland>
<Roland> Comment By 12 May 2009
SP: if don't use CURIEs what do they use?
RM: their own solution
SM: which is VERY similar to
CURIE, but with further restrictions
... called "abreviated IRIs"
from W3 front page blurb: "OWL 2 (a compatible extension of OWL 1) consists of 13 documents (7 technical, 4 instructional, and 2 group Notes)"
OWL comment action item:
SM: is DAISY using CURIEs?
MG: yes
GJR: on list for ARIA 2.0 - support for CURIEs to point to external resources
RM: can mention RIF - RIF core
and RIF collection/dialect
... other implementations?
GJR: ARIA use pending status of CURIE document
SM: Markus, have a pointer?
MG: not public info yet
SM: need something to point to - could be email from you to public-xhtml2@w3.org
RM: easiest to send email to public-xhtml2 with pointers to code in that mail
ACTION - Markus: send email to public-xhtml2 about DAISY's use of CURIEs to public-xhtml2
<trackbot> Sorry, couldn't find user - -
<scribe> ACTION: Markus - send email to public-xhtml2 about DAISY's use of CURIEs to public-xhtml2 [recorded in]
<trackbot> Created ACTION-77 - - send email to public-xhtml2 about DAISY's use of CURIEs to public-xhtml2 [on Markus Gylling - due 2009-04-30].
RESOLUTION: request CURIE to be transitioned from CR to PR
trackbot, pointer
<trackbot> Sorry, oedipus, I don't understand 'trackbot, pointer'. Please refer to for help
[ADJOURN UNTIL 1345h UTC]
ARIA 2.0 CURIE Support Issue Tracker entry:
<ShaneM> it occured to me that xhtml 1.2, xhtml 2, and xhtml modularization 2 also all use CURIEs
<ShaneM> oh - and XHTML Role and XHTML Access and RDFa of course...
SM: does aria's roles allow CURIEs?
"The applicable ARIA role is the concrete ARIA role whose name is matched by the first token in the sequence of tokens in the role attribute value which matches, on case-sensitive comparison, the name of any concrete ARIA role."
"A concrete ARIA role is any of the role types described above except abstract roles (roles for which isAbstract is true) and the roles imported from the Role Module, that is those that are introduced in sections 4.4.6 and 4.4.7"
<alessio>
An implementing host language will provide an attribute with the following characteristics:
* The attribute name MUST be role;
* The attribute value MUST allow a space-separated sequence of whitespace-free substrings;
* The appearance of the name literal of any concrete ARIA role (see section 7.3.2) as one of these substrings MUST NOT in and of itself make the attribute value illegal in the host-language syntax; and
* If the name literal of a concrete ARIA role appears as one of the substrings in the space-separated list in the role attribute, the role MUST be processed in accordance with this specification.
SM: essentially CURIE-type mechanism by another name
ARIA 1.0 ") acces
RM: request transition for CURIE, make LC comments to OWL2 to try and get consistency in SemWeb area
<Steven> Yves, we are ready when you are
<Steven> YvesS
<YvesS> ok, I'm getting there.
shane,
SM: should announce in rdfa.info that DAISY uses RDFa
MG: will go public with first
draft before summer - nothing to look at at this point
... except for source code repository
yves,
background: the WG has identified at least 3 questions for Yves:
*
o does ITS allow XHTML to use its native SPAN element and Ruby module?
o is external ITS support alone sufficient?
o can we use LINK with "rel" in HEAD?
1. does ITS allow XHTML to use its native SPAN element and Ruby module?
2. is external ITS support alone sufficient?
3. can we use LINK with "rel" in HEAD?
Subtopic: Reuse of XHTML's Native SPAN element or ruby module?
SP: want to integrate ITS into
XHTML2 - wanted to get info straight from source's mouth
... can we use native XHTML span to satisfy ITS?
Yves: correct
SM: what about Ruby module
Yves: if aligned with ITS
SP: ITS copied ours, so should be ok
Subtopic: LINK versus XLink
SP: can we use LINK with "rel" to link to ITS rules document
Yves: good question; as long as documented properly, shouldn't be an issue; don't see any conflict; processor just needs to know what to do with LINK
SM: have other groups identified
value that want to use for "rel" attribute
... want to have "rel" attribute that states HREF pointing at is an ITS rule
Yves: XHTML2 WG should come up with value for "rel" attribute - we will follow your lead
SP: preference is to use a CURIE
<ShaneM> XHTML2 WG Gets to blaze the trail again!
SP: since rulename is its:rules
therefore rel="its:rules"
... any objection to using CURIE?
Yves: don't forsee problem
SM: is HTML5 group going to accomodate ITS?
Yves: yes
SP: how?
Yves: explicit links
<ShaneM> HTML5 would not like use to use a colon
SP: if have to interoperate with their value, shouldn't be a CURIE, but keyword value
<ShaneM> rel="itsrules"
SM: if that is part of target audience, i agree -- if try to use CURIE, have vocabulary prefix issue to deal with, so prefer rel="its:rules"
<ShaneM> rel="itsRules" maybe
SM: without colon - then HTML5
can't complain about colon
... want maximum number of people to take advantage of and use ITS
... need consistent behavior model
Subtopic: ITS Rule Versioning
SP: do rules documents state version?
Yves: yes - describe way external tool can handle ITS document
SP: not worried that LINK wouldn't say which version pointing to?
Yves: no - customized tools is end goal
SP: don't want to have to change
documents because of new version of ITS rules
... if allow LINK rel="itsRules" is that sufficient?
Yves: yes, provided can do the lookup
Subtopic: its:translate
SP: want to use its:translate, but already have own "dir" - can just use "translate" attribute
Yves: that is fine; map existing data categories/atttributes using ITS rules
SP: in its rules, can say attribute "dir" is same as its "dir"
<ShaneM> how about <span translate="whatever" dir="ltr">lala</span> ? instead of its:translate?
Yves: yes
SP: no problem importing its:translate - do you have preference if reuse yours or include a native XHTML translate attribute
Yves: use ITS
SP: not allergic to foreign namespaces
Yves: can map it
SP: thank you VERY much Yves for your attendance
Yves: HTML5 comment on question
of value - suggest use "itsRules"
... will keep XHTML2 WG updated on negotiations with HTML WG
SM: create ITS module for XHTML2 spec that indicates bringing in itsRules attribute add to Common or Text module?
MG: inheritable, so that is reason to put in common
RM: text module
MG: 2 questions: ITS module and
should it be in Common or Text Attribute collection
... where to put it is the ultimate question
SM: if add to existing module, i'd add to i18n module
[general agreement on wisdom of this]
SM: adds internationalization collection to the common collection
<Steven>
SP: translate attribute marked as an issue in that very section
SM: for XHTML2, use i18n
module
... architectual question: should i18n module always include ITS in M12n 2.0
... bring in rel="itsrules" and itsTranslate?
... i think the answer is yes
RM: don't see reason to say "no" at the moment
<Steven> itsrules
s/rel="itsRule"/rel="itsrules"/G
SP: why not put i18n and bi-directional text together in same module?
RM: and ruby??
SP: no, ruby has own attribute collection - referenced by indirection
SM: not a bad suggestion to collapse into i18n module, but don't want to consume f2f time on that editorial issue
RM: ITS use in LINK element with
appropriate "rel" value
... investigate collation of ITS, ruby and bi-directionality into an expanded i18n module;user=guest;statetype=-1;upostype=-1;changetype=-1;restype=-1
SM: issued at when stopped last time - hypertext attribute selection
Subtopic: hypertext attribute module
SM: Anne asks why are needed at all
SP: hreflang doesn't solve
problem - if multiple language versions of link and send dutch
link to you who use russian, should get russian version
... hreflang not a new facilllity; always in HTML4
... problem - doesn't do anything - no better than comment
... if claim it is dutch than it better be "nl" - if don't want to do, then don't
GJR: hreflang is useful for
accessibility because it prepares the Assitive techonology to
make the appropriate natural language switch
... hreflang identifies natural language for natural language processing
SP: 2 problems: 1. not garunteed
to be interoperable (will break if move URLs if web server
doesn't use same method of specifying URLs
... 2. no way to garuntee that is possible - know at least 1 server where one can have several resources linked via URL but not to sub-resources
RM: content creator's choice
whether or not to do that
... could make them available as choice or through content-negotiation
SP: hreflang doesn't break
content negotiation
... hreflang offers extra functionality - if don't want to use, don't have to, but is useful functionality for some use cases
... example: if have on homepage links to different versions of homepage, this allows me to check if they are really there -- allows one to check links to ensure that what is supposed to be the dutch version is the dutch version
GJR: also good trigger to switch natural langauge for TTS, charsets for screen magnification, especially in absence of natural language declaration in document being referred to
RM: document benefits and extra functionality
<Steven>
"."
RM: doesn't address why would use in concert with content negotiation
SP: current text isn't sufficient?
RM: don't think we cover value statement very well as currently written
example from document:
<p href=""
hreflang="fr">
The press release in French
</p>
RM: no complimentary documents
that goes with XHTML2 that addresses how to use these things
together
... will lose this if don't put into document
GJR: i have an action item to create a wiki page for Role BP; i could do the same for hreflang and content negotiation
RM: need "motivating examples"
SP: could put same example with <a hreflang="nl">Press Release in Dutch</a>
GJR: wouldn't you want <a hreflang="nl" xml:Dutch for "this page in dutch</a>
RM: content negotiation methods - match against what UAs do today
SP: if want to say this is version in french, so available to someone who wants french
RM: if all want to do is get what matches browser, don't have to worry; if want to give user option to choose language, then use hreflang
<scribe> ACTION: Gregory - create wiki page for hreflang and content-negotiation best practices and examples [recorded in]
<trackbot> Created ACTION-78 - - create wiki page for hreflang and content-negotiation best practices and examples [on Gregory Rosmaita - due 2009-04-30].
GJR: make sure to address xml:lang in conjunction with hreflang and content negotiation
RM: done on hreflang for now?
SP: brief comment at end - target is CSS issue with pointer to old spec
SM: answer is "no it is not"
SP: right
SM: bi-directional text verbiage has typo i need to correct
Subtopic: Edit
SM: Quote element doesn't have default presentation, whereas "edit" has one
RM: comment from DocBook about not having default presentation in quote
SP: reping CSS WG - ascertain if changed mind
RM: want to have consistency for content creators across languages
SP: can undo decision - is in current form due to comment and request
SM: have to revisit the issue anyway
Subtopic: Embedding Attribute Module and @type
SM: question is why need @type at
all
... purpose of @type is so i can indicate to UA what types of resources are available that i want to use for my document
... UA should then determine intersection of what author wants and internal capabilities and serve the "best" one
... author in control of document and resources therein
RM: what about things embedded from elsewhere? don't necesarily have control over embedded content
SP: always been in HTML
RM: don't need old baggage
SM: some old baggage is useful
and we have tightened usage
... @type allows me to serve image in SVG, PNG, JPG, and GIF - as author, want cascade: SVG, PNG, JPG or GIF depending on UA capabilities
SP: if don't want to use it,
don't use it, full stop
... allows for more author control - increases author's power, doesn't decrease it
SM: what should http-accept header report
<alessio> provides a more stable object fallback
RM: don't have image module
<ShaneM>
RM: first example uses NL - ok
SP: why arent' attributes applied directly to a list
SM: why do you need detail is
comment
... if change to UL should solve problem
SP: <ul role="navigation"> right?
SM: sure
... don't call "LABEL" but "CAPTION"
MG: no LABEL element anymore
GJR: suggested use of LEGEND instead of CAPTION
SM: TITLE or CAPTION - different semantics
GJR: use old fieldset, legend. label model, freed from forms - irrelevant due to XForms module, so reuse LEGEND as generic labeller
Subtopic: Why Need OBJECT?
SM: something has to take PARAM
GJR: trying to get HTML5 to consider PARAM for EACH media-specific element
Subtopic: XHTML Scripting Module
SM: complaint that it was being dropped; we have decided to chop XML Events into event, handler and script
Subtopic: XForms
SM: don't understand "useable by everyone" forms instead
SP: send pointer to XForms in HTML tutorial
RM: some of these complaints/comments have been obsoleted by events
SM: most of them;user=guest;statetype=-1;upostype=-1;changetype=-1;restype=-1
Subtopic: Example for hreftype
SM: will check to ensure that hreftype example is correct
Subtopic: Definition of Access
SM: editorial complaint
RM: shouldn't be problem - ripped out Access and made it its own module
SM: right
Subtopic: bidi text
comment: "(bidi text) there are two section definitions that are malformed: 15.1.3.15.1.1. Inheritance of text direction information and 15.1.4. 15.1.2. The effect of style sheets on bidirectionality"
SP: in HTML4 could only say deleted somewhere and inserted somewhere else -
GJR: proposed a for/id relationship for INS and DEL in Editing Module
attributes:
GJR: lingering question: "is <DEL id="blah1">dig</DEL> <INS for="blah1">dog</INS> best practice, or is d<DEL id="blah1">i</DEL><INS for="blah1">o</INS>g permissible, and is it any of our business? "
<inserted> ScribeNick+ Steven
<Steven> Roland: I find it hard to get excited about this
<Steven> Roland: Further down it shows a reply, and mentions the edit="moved"
<Steven> Roland: Are there any more of these issues?
<Steven> Shane: Lots
<Steven> ... such as 82 issues in "incoming"
<scribe> Scribe: Gregory_Rosmaita
SP: meant to be new working group
when renamed XHTML2
... HTML5 WG didn't take over our HTML issues
... we (XHTML2) retained issues from old working group
... done our best to work with them, go to LC, and let them comment on that
RM: should delete or mark
incomplete in issues list
... can close one-by-one, but need to do SOMETHING with them
... new ones since group re-chartered?
SP: would be in incoming bucket
SM: only 1 issue since
rechartered
... about editorial error in CURIE spec which i think i fixed
RM: comments on XML Events get to issue tracker?
old issue tracking system on XML Events:;statetype=-1;upostype=-1;changetype=-1;restype=-1
shane's tracker "XMLEvents has 6 messages"
<Roland>
Errata for XML Events: An Events Syntax for XML
comment:."
SM: don't remember seeing it in
issue tracker, but can put it there
... didn't imagine us doing an update to XML Events 1
RM: should we ever need to, this
is something we should address at same time
... should keep track in relation to XML Events 1 - if do need to PER XML Events 1, then would address all errata on that document
SM: i'll get it into the tracker
Subtopic: How Do We Make the Issue Tracking System Useful?
SM: use issue tracker effectively
for new work (last call comments, etc.)
... in the past, have tracked comments from last call or PR review - works to extent we use it
... do have a lot of old baggage and unprocessed stuff in old tracking system
... can take all of unprocessed stuff and mark obsolete
RM: proposed resolution: All items in issue tracking system dated prior to new charter be closed as no longer relevant
SM: will that fly?
SP: can argue it reasonably; old
group's charter ended and new group chartered (XHTML2) - did
best to process as many comments from previous group as could
and are now staring tracking afresh
... TBL did say this is going to be a new group with a new charter and new chair
SM: going to create a bucket
called "old" -- everything that isn't in a certain state will
be included
... if closed, leave where is - already dealt with and useful for pointers
... if implemented, done it, but haven't reissued public draft since effecting changes
... if marked "suspended" we were holding for later processing
... anything not in "suspended", "implemented" or "closed" will be obsoleted
RM: charter start date?
... end date 31 December 2009
SP: date of charter 2007-02-02
SM: anything before 2007?
SP: yes
RM: yes
GJR: yes
AC: yes
SM: should we inform users that comment tabled, please re-review and re-submit if necessary
RM: let's ascertain how many there are to deal with
SP: [counting]
proposed RESOLVED: All items in issue tracker dated prior to issuance of new XHTML2 Charter (2007-02) will be closed as no longer relevant
SM: more general question: 259
messages that are "open", but 135 are in the "trash" - spam not
yet marked as closed
... rather than doing in "real time" will go through and remove the extraneous "crust"
SP: if only 80, can do quick pass
over them
... can we chop it down even further?
RM: shane, take a pass, post a list, and will revisit if we need resolution
<scribe> ACTION: Shane - post list of outstanding old issue tracking system items to public-xhtml2 in preparation for final disposition [recorded in]
<trackbot> Created ACTION-79 - - post list of outstanding old issue tracking system items to public-xhtml2 in preparation for final disposition [on Shane McCarron - due 2009-04-30].
<ShaneM> brb
SP: elements for structural
portions of document; semantics indicated by attributes (why
added role)
... in case of D, looks like adding semantics
... can't we use a role="dialogue"
GJR: would role="dialogue" be applied to Q
<Tina> If we are not indicating semantics with elements, then why are we indicating semantics with /some/ elements?
GJR: Q inappropriate because when including dialogue, one is not quoting, but speaking in the character's voice
" or u0022 or u0027, and so on) nor can one rely on extremely spotty implementation of the :before and :after pseudo-elements to g
RM: dialogue in my understanding involves multiple parties
GJR: monolog would be subsumed into dialogue
<alessio> ...what about d role="monolog"?
RM: could we make this a property of P or SPAN?
MG: yep
what about this use case:
<d>
<dl>
<dt> Shopkeeper</dt>
<dd> <nd>[obviously lying]</nd> Sorry, we're just closing for lunch</dd>
</dl>
</d>
<Tina> Can't that be solved by pulling in another namespace specifically created for, say, plays etc?
"
SM: not convinced D/dialogue is a semantic structure
RM: INS/DEL kept only in text;
use other attributes (including role) to annotate
... content model on wiki page is horrendous
RM: what is rationale?
". "
RM: represents fact that individual is uttering statement
GJR: provides a means to represent text that is expressed by an individual or group of individuals
RM: perhaps should make distinction --
<d>
<dl>
<dt> Shopkeeper</dt>
<dd> <nd>[obviously lying]</nd> Sorry, we're just closing for lunch</dd>
</dl>
</d>
RM: don't think D would be right
thing there - DL for scene
... what if in argument or debate?
... generic D would be much more about annotating a section
... D doesn't carry semantics for me"
>
DL Should Give Structure to, Not Generically Indicate, Dialogue
RM: investigate what people are actually saying -- all about speech
<h> Kane Found in Love Den with <em class="em-quote">Dancer</em></h>
em-quote would be a :before and :after psuedo-element to indicate quotation nesting
<Roland> <u role="to-be-said">Hi</u> <q role="actually-said">Hello</q>
<markus> Id be in favor of supporting inline D with the rationale to avoid misuse of Q, and wait for (along Tinas suggestion above) a future dedicated module under XHTMLMOD2 for "real" block level markup of plays etc.
<markus> ... Steven: you cant attach rdf/a to unicode quotes
MG: idea with D is can ascribe from whom dialogue originates
RM: Q says "this is what was actually said" - what does D do?
<Steven> The rule was for deciding how to introduce new elements
<Steven> we left old elements mostly untouched
<Steven> for 'mindshare' reasons
GJR: D proposal has role/type proposed for D
SP: understand use case, but feel
that if our current markup extensibility methods are not able
to handle this case, then somehow we failed
... next time someone comes along with a semantic element idea, what do we do? extensibility has to be considered before new elements are added
... how to fix this? semantic mechanism so that anyone can add semantic info to document
... if not sufficient, what is wrong with model?
RM: agree with Steven --
concentrate on problem statement
... if agree on problem statement, can explore what we can do within XHTML2's over-arching philosophy -- if run into problems, then can consider new element
GJR: semantically there IS a difference betwen a quote and dialogue
RM: role="maleProtoganist"
... take GJR's use cases and investigate if can solve them with existing technologies native to XHTML
... content model is scary
GJR: next steps?
RM: rationale is most important bit;
"5. "
RM: concentrate on problems then
propose solutions
... FIVE MINUTE WARNING
... any urgent business
SP: need to ensure roadmap reflects reality
RM: goal is to get new draft out
in May 2009
... can we create draft for publication in may?
MG: how does this correlate with PLH's induced discussions with SamRuby?
SP: have to carry on according to charter whilst addressed in w3c channels - wouldn't be addressed until end of year
RM: editors comfortable with may
2009 for publishable draft?
... what help needed?
SM: ready to publish now
SP: WG task -- assign and read sections
MG: what about XForms?
SP: just reference XForms -
import XForms 1.1 with the following elements
... ok if in working draft as is
... XForms WG discussed attribute names yesterday - going to deprecate old attribute names and introduce new - old content will still work, but XHTML2 can go ahead and just use new attributes
RM: implications?
SP: clashes with XForms attributes -- target, for example
RM: is there a definitive list?
SP: thought solved for XML Events
2, need to check XForms
... will post pointer to XForms minutes
... very accomodating
RM: schedule another vFtF
soon
... will discuss logistics of next virtual face2face at next week's regular XHTML2 WG telecon
<ShaneM> there are now 45 issues that are !Implemented
<scribe> meeting: XHTML2 Virtual Face2Face
meeting+ XHTML2 Virtual Face2Face
meeting- XHTML2 Working Group Teleconference
meeting+ XHTML2 Virtual Face2Face
This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/Date:/Date - / Succeeded: s/SP/SM/ Succeeded: s/can we use LINK/can we use "ref" with LINK to accomplish this?/ Succeeded: s/href/ href/ Succeeded: s/not/note/ Succeeded: s/what would be the Role value/what would be the rel value/ Succeeded: s/CURIE/CURIEs/ Succeeded: s/local/generic/ Succeeded: s/SP: can mention RIF/RM: can mention RIF/ Succeeded: s/RDFa implementation/rdfa.info/ Succeeded: s/SM: want to integrate/SP: want to integrate/ Succeeded: s/SM: can we use native/SP: can we use native/ Succeeded: s/SM: ITS copied ours/SP: ITS copied ours/ Succeeded: s/SM: can we use LINK/SP: can we use LINK/ Succeeded: s/rel="itsRule"/rel="itsrules"/ FAILED: s/rel="itsRule"/rel="itsrules"/G Succeeded: s/SM: and ruby/RM: and ruby?/ Succeeded: s/hypertext attribute selection/hypertext attribute module/ Succeeded: i/Roland: I find/ScribeNick+ Steven Succeeded: s/XML/HTML/ Succeeded: s/attac/attach/ Found Scribe: Gregory_Rosmaita Found ScribeNick: oedipus Found Scribe: Gregory_Rosmaita Default Present: Steven, Roland, Markus, Gregory_Rosmaita, ShaneM, Alessio, Yves_S Present: Steven Roland Markus Gregory_Rosmaita ShaneM Alessio Yves_S Regrets: Rich_S Agenda: Got date from IRC log name: 23 Apr 2009 Guessing minutes URL: People with action items: - email force get gregory markus rdfa send shane task WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output] | http://www.w3.org/2009/04/23-xhtml-minutes.html | CC-MAIN-2014-35 | refinedweb | 6,062 | 55.17 |
date and time in Ruby
By: Tadayoshi Funaba Emailed: 1641 times Printed: 2110 times
The date.rb file provides two classes for working with dates and times.
The first class, Date, represents dates. It works with years, months, weeks, and days. See the Date class documentation for more details.
The second, DateTime, extends Date to include hours, minutes, seconds, and fractions of a second. It provides basic support for time zones. See the DateTime class documentation for more details.
Ways of calculating the date.
In common usage, the date is reckoned in years since or before the Common Era (CE/BCE, also known as AD/BC), then as a month and day-of-the-month within the current year. This is known as the Civil Date, and abbreviated as civil in the Date class.
Instead of year, month-of-the-year, and day-of-the-month, the date can also be reckoned in terms of year and day-of-the-year. This is known as the Ordinal Date, and is abbreviated as ordinal in the Date class. (Note that referring to this as the Julian date is incorrect.)
The date can also be reckoned in terms of year, week-of-the-year, and day-of-the-week. This is known as the Commercial Date, and is abbreviated as commercial in the Date class. The commercial week runs Monday (day-of-the-week 1) to Sunday (day-of-the-week 7), in contrast to the civil week which runs Sunday (day-of-the-week 0) to Saturday (day-of-the-week 6). The first week of the commercial year starts on the Monday on or before January 1, and the commercial year itself starts on this Monday, not January 1.
For scientific purposes, it is convenient to refer to a date simply as a day count, counting from an arbitrary initial day. The date first chosen for this was January 1, 4713 BCE. A count of days from this date is the Julian Day Number or Julian Date, which is abbreviated as jd in the Date class. This is in local time, and counts from midnight on the initial day. The stricter usage is in UTC, and counts from midday on the initial day. This is referred to in the Date class as the Astronomical Julian Day Number, and abbreviated as ajd. In the Date class, the Astronomical Julian Day Number includes fractional days.
Another absolute day count is the Modified Julian Day Number, which takes November 17, 1858 as its initial day. This is abbreviated as mjd in the Date class. There is also an Astronomical Modified Julian Day Number, which is in UTC and includes fractional days. This is abbreviated as amjd in the Date class. Like the Modified Julian Day Number (and unlike the Astronomical Julian Day Number), it counts from midnight.
Alternative calendars such as the Chinese Lunar Calendar, the Islamic Calendar, or the French Revolutionary Calendar are not supported by the Date class; nor are calendars that are based on an Era different from the Common Era, such as the Japanese Imperial Calendar or the Republic of China Calendar.
Calendar Reform
The standard civil year is 365 days long. However, the solar year is fractionally longer than this. To account for this, a leap year is occasionally inserted. This is a year with 366 days, the extra day falling on February 29. In the early days of the civil calendar, every fourth year without exception was a leap year. This way of reckoning leap years is the Julian Calendar.
However, the solar year is marginally shorter than 365 1/4 days, and so the Julian Calendar gradually ran slow over the centuries. To correct this, every 100th year (but not every 400th year) was excluded as a leap year. This way of reckoning leap years, which we use today, is the Gregorian Calendar.
The Gregorian Calendar was introduced at different times in different regions. The day on which it was introduced for a particular region is the Day of Calendar Reform for that region. This is abbreviated as sg (for Start of Gregorian calendar) in the Date class.
Two such days are of particular significance. The first is October 15, 1582, which was the Day of Calendar Reform for Italy and most Catholic countries. The second is September 14, 1752, which was the Day of Calendar Reform for England and its colonies (including what is now the United States). These two dates are available as the constants Date::ITALY and Date::ENGLAND, respectively. (By comparison, Germany and Holland, less Catholic than Italy but less stubborn than England, changed over in 1698; Sweden in 1753; Russia not till 1918, after the Revolution; and Greece in 1923. Many Orthodox churches still use the Julian Calendar. A complete list of Days of Calendar Reform can be found at.)
Switching from the Julian to the Gregorian calendar involved skipping a number of days to make up for the accumulated lag, and the later the switch was (or is) done, the more days need to be skipped. So in 1582 in Italy, 4th October was followed by 15th October, skipping 10 days; in 1752 in England, 2nd September was followed by 14th September, skipping 11 days; and if I decided to switch from Julian to Gregorian Calendar this midnight, I would go from 27th July 2003 (Julian) today to 10th August 2003 (Gregorian) tomorrow, skipping 13 days. The Date class is aware of this gap, and a supposed date that would fall in the middle of it is regarded as invalid.
The Day of Calendar Reform is relevant to all date representations involving years. It is not relevant to the Julian Day Numbers, except for converting between them and year-based representations.
In the Date and DateTime classes, the Day of Calendar Reform or sg can be specified a number of ways. First, it can be as the Julian Day Number of the Day of Calendar Reform. Second, it can be using the constants Date::ITALY or Date::ENGLAND; these are in fact the Julian Day Numbers of the Day of Calendar Reform of the respective regions. Third, it can be as the constant Date::JULIAN, which means to always use the Julian Calendar. Finally, it can be as the constant Date::GREGORIAN, which means to always use the Gregorian Calendar.
Note: in the Julian Calendar, New Years Day was March 25. The Date class does not follow this convention.
Time Zones
DateTime objects support a simple representation of time zones. Time zones are represented as an offset from UTC, as a fraction of a day. This offset is the how much local time is later (or earlier) than UTC. UTC offset 0 is centred on England (also known as GMT). As you travel east, the offset increases until you reach the dateline in the middle of the Pacific Ocean; as you travel west, the offset decreases. This offset is abbreviated as of in the Date class.
This simple representation of time zones does not take into account the common practice of Daylight Savings Time or Summer Time.
Most DateTime methods return the date and the time in local time. The two exceptions are ajd() and amjd(), which return the date and time in UTC time, including fractional days.
The Date class does not support time zone offsets, in that there is no way to create a Date object with a time zone. However, methods of the Date class when used by a DateTime instance will use the time zone offset of this instance.
Examples of use
Print out the date of every Sunday between two dates.
def print_sundays(d1, d2) d1 +=1 while (d1.wday != 0) d1.step(d2, 7) do |date| puts "#{Date::MONTHNAMES[date.mon]} #{date.day}" end end print_sundays(Date::civil(2003, 4, 8), Date::civil(2003, 5, 23))
Calculate how many seconds to go till midnight on New Year’s Day.()
Be the first one to add a comment | http://www.java-samples.com/showtutorial.php?tutorialid=1109 | CC-MAIN-2017-13 | refinedweb | 1,333 | 63.29 |
Best practices
Map and Scene view options
ArcGIS Runtime API for Qt offers the three patterns listed below for creating and displaying a map in a map view, or scene in a scene view. For convenience, templates are included with the SDK to aid in creating new projects. In Qt Creator, choose the ArcGIS template based on your resources, platform, experience, and need for speed.
Qt Quick
ArcGIS Runtime supports writing Qt Quick apps in a combination of C++ and QML code, or in pure QML. This is accomplished by using ArcGIS Runtime's C++ API or its QML API, respectively.
Create a Qt Quick Cpp app
The
Map class is part of the C++ API.
Map is an implementation of
Map accessible from QML, and harnesses the speed of the C++ API in the business logic. With this approach, you leverage QML's extensive set of UI functionality, flexibility, and visual appeal while providing ArcGIS Runtime capabilities through the C++ API. Often recommended by Qt experts, this app pattern works on the platforms listed above. Note that with this template/pattern, you cannot use components of the C++ and QML APIs together in the same app.
To use this pattern, when creating your new project in Qt Creator, select Qt Quick C++ app (for the ArcGIS Runtime version installed) and then finish creating the project. The selected ArcGIS Runtime template registers
Map type as
Map in
main.cpp.
// Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Display_map_quick_Cpp", 1, 0, "MapView");
In the C++ header file, the template creates a read/write
Q_ for the
Map.
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged)
The template creates the
Map component in the
<appname\> file.
Item { // Create MapView (MapQuickView) here. Then create its Map (type) etc., in C++ code. MapView { id: view anchors.fill: parent // set focus to enable keyboard navigation focus: true } // Declare the C++ instance which creates the map etc., and supply the view Display_a_map { id: model mapView: view } }
In the your app's C++ code (<appname>.cpp), the template creates the following code. The constructor initializes
QObject, and
m_ using the
Basemap you selected when creating the project.
Display_a_map::Display_a_map(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISStreets, this)) { }
Below, the template creates the
set function. This function is what is executed when the MapView is created and set in QML code.
// Set the view (created in QML) void Display_a_map::setMapView(MapQuickView* mapView) { if (!mapView || mapView == m_mapView) { return; } m_mapView = mapView; m_mapView->setMap(m_map); emit mapViewChanged(); }
Create a Qt Quick QML app
If you API and want to develop native apps. QML has been part of the API since version 10.2.5 and works on all supported platforms.
To use this pattern, when creating your new project in Qt Creator, select Qt Quick QML app (for the ArcGIS Runtime version installed) and then finish creating the project. The template creates the following code in
main.qml. The template creates an
Application containing a
Map. Within the
Map, the code declares a
Map.
Basemap is set from your selection when creating the project.
ApplicationWindow { id: appWindow width: 800 height: 600 title: "Display_a_map" // add a mapView component MapView { anchors.fill: parent // set focus to enable keyboard navigation focus: true // add a map to the mapview Map { // Add the ArcGISTopographic BasemapStyle to the map initBasemapStyle: Enums.BasemapStyleArcGISTopographic } } }
Create a Qt Widgets Cpp app
C++ is all about performance. With the C++ API, you can build an app with a powerful computing back-end, and develop your UI in C++ using the Qt Widgets module. Qt Widgets has a rich suite of tools and components used for building powerful desktop applications. C++ is supported for applications running on Linux, macOS, and Windows. For pure C++ apps like these, the map view is implemented as a
Map.
To use this pattern, when creating your new project in Qt Creator, select Qt Widgets app (for the ArcGIS Runtime version installed) and then finish creating the project. The template creates the following code in the <appname>.cpp file.
Basemap is set from your selection when creating the project.
Display_a_map::Display_a_map(QWidget* parent /*=nullptr*/): QMainWindow(parent) { // Create a map using the ArcGISStreets BasemapStyle m_map = new Map(BasemapStyle::ArcGISStreets, this); // Create the Widget view m_mapView = new MapGraphicsView(this); // Set map to map view m_mapView->setMap(m_map); // set the mapView as the central widget setCentralWidget(m_mapView); }
Integrate the SDK into an existing app
The ArcGIS Runtime SDK for Qt can be integrated into an existing Qt app with a couple of steps. The steps vary slightly depending on if the application was created using Qt Quick or Qt Widgets.
Qt Quick C++ API integration
To use the C++ API, include the
arcg)
Qt Quick QML API integration
To use the QML API, include the
arcgis_)
After want to add the import paths to the ArcGIS Extras plugin or the Toolkit. Adding QML plugins to the QML Import Path can be accomplished by using the
QQml method in C++ code. For example, you can add the ArcGIS Runtime QML plugin to the plugin path with the following syntax:
view.engine()->addImportPath("pathToSDK/sdk/macOS/x64/qml");
As an alternative, you could instead add an environment variable called
QML2_ with the paths to the various plugins you wish to use.
After the
pri file is included and the import paths are added, import the QML plugin in a QML file by using the
import syntax. For example, version 100.13 of ArcGIS Runtime could be imported with the following:
import Esri.ArcGISRuntime 100.13
Qt Widgets C++ API integration
Include the
esri_ project include file (
pri) into your project file. You can get this
pri file from the SDK installation, under the
sdk/ideintegration folder. For example, the following syntax includes ArcGIS Runtime into your Qt Widgets application:
include(/pathToSDK/sdk/ideintegration/esri_runtime_qt.pri)
Additional information
The following Qt resources provide additional information about API. This code can be set at runtime, and can either be in your main.cpp, or in some other C++ class. Beyond using a proxy for debugging,
QNetwork supported only ANGLE. Starting with ArcGIS Runtime 100.3.0, your apps can fully support both OpenGL and ANGLE so that you can utilize either rendering engine and Qt's fallback mechanism when OpenGL cannot be used on a given system. For more information, see Qt's documentation.
To override the default behavior to set ANGLE rendering, add the following code before the Qt application object is constructed.
# Q_OS_WIN32 // Force usage of OpenGL ES through ANGLE on Windows QCoreApplication::setAttribute(Qt::AA_UseOpenGLES); #
Please note that support for ANGLE is deprecated and will be removed with a future version of the software. | https://developers.arcgis.com/qt/programming-patterns/best-practices/ | CC-MAIN-2022-40 | refinedweb | 1,120 | 55.03 |
C++ constructor example programs: Constructor are functions having name as that of class. They do not have return type and are used to initialize objects.
C++ constructor program example
#include <iostream> using namespace std; class Game { private: int goals; public: // constructor used to initialize Game() { goals = 0; } // return score int getGoals() { return goals; } // increment goal by one void incrementGoal() { goals++; } }; int main() { Game football; cout << "Number of goals when game is started = " << football.getGoals() << endl; football.incrementGoal(); football.incrementGoal(); cout << "Number of goals a little later = " << football.getGoals() << endl; return 0; }
Game class contains a member goals which stores the number of goals. Game() constructor is used to initialize number of goals which are zero initially. Game class object football is created and number of goals are printed just after object is created and goals are incremented using incrementGoal function. | http://www.programmingsimplified.com/cpp/source-code/constructor-program-example | CC-MAIN-2017-09 | refinedweb | 140 | 54.22 |
Exercise:
Error Message:Oops, try again. Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP".
So I originally had the below code. It seems to do everything except print without the whitespaces. After looking at a couple of existing questions, this code prints instead of returns so I get why it doesn't work. Quick question though, how do I return this without white space?
def reverse(text):
length = len(text)
for word in text:
length -= 1
print text[length],
print reverse("Python!")
I then went and rewrote it to the below code, and got the same error message:
def reverse(text):
length = len(text)
reverse_list = []
for word in text:
length -= 1
reverse_list.append(text[length])
return str(reverse_list)
print reverse("Python!")
first method...In last line when you print it,even though you're using comma after print ,It will create a space there!hint**Concatenate each character in new string(define an empty string) then return it
Second method..Your second code works fine ,except last line..reason..
x =[1,2,3]
str(x) # this is '[1,2,3]' now not "123"
hint**You can usejoin() method on your final list to convert it back to string..not str()method.
join()
str()
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. | https://discuss.codecademy.com/t/7-reverse/83807 | CC-MAIN-2017-22 | refinedweb | 226 | 75.91 |
Bryn Paul Arnold Jones wrote:> Why not just make it simple, and have a config option that appends a> '-D<lang>' to the cflags, and then have the printk's like this:> > printk(KERN_DEBUG,> #ifdef LANG1> "Message that %s said %d in lang 1\n"> #else /* not in LANG1 */> #ifdef LANG2> "Message that %s said %d in lang 2\n"> else /* not in LANG2 */> "Message that %s said %d in english\n"> #endif /* LANG2 */> #endif /* LANG1 */> , device->name, status);> > That way if the printk hasn't been translated to the perticular> language yet, the english is used, it dosn't use memory for each> additional language, and you also don't have all that messing> with loading, and searching through, lists of translations.I haven't been following this thread, but just my two cents. The abovesounds crazy to me. Like, if your supporting 20+ languages (not thatunlikely either at some point) then the kernel source is going to getmassive and unreadable because anytime there's a printk you'll have towade through a ton of crap to get past it.Somehow, I don't think Linus would go for this solution either, and hewould have the final say of course. Cheers,Chris | https://lkml.org/lkml/1997/1/18/68 | CC-MAIN-2014-15 | refinedweb | 203 | 59.1 |
I feel my question has been asked, but I haven't gotten an answer out of previous posts in the forums. So here's my code:
def is_prime(x): if x == 2: return True elif x > 1: for n in range(2, x-1): if x % n == 0: return False else: return True else: return False
After testing some numbers, and printing the results, I've found this code works perfect for any numbers not 3 or 9. I'm not sure why this isn't working for me, as when I run the number through the code in my head it should work. Here's my process of thought.
1) The code checks if x == 2, if it does then returns True.
2) If x != 2, then it runs through my loop. The loop checks if x is divisible by any number "n" between 2, and x-1. Meaning if this was the number 3, it would go through the range 2, 2. Or if x = 9, then it would run through the range 2, 8.
3) If x % n == 0 it is not a prime number because there is no remainder. On the other side of things, if x % n does have a remainder for n in range(2, x-1), then it is prime.
4) Else, the number is 1 or 0, which is not a prime, so it would return False.
So why then does 3 and 9 not work in this loop? The "n" range for 3 would be 2,2. 3/2 leaves a remainder, yet returns "none". 9 would have a range (2, 8) where 3 is in that range. 9/3 would leave no remainder, yet it still returns True. It has nothing to do with multiples of 3 in total as 12 returns False. Please help! | https://discuss.codecademy.com/t/is-prime-problem-with-3-and-9-returning-true/53471 | CC-MAIN-2018-26 | refinedweb | 305 | 89.79 |
From: Joseph Gauterin (joseph.gauterin_at_[hidden])
Date: 2008-07-31 05:49:44
Yes, we've got MSVC 8 & 9 and GCC 4+ passing everything now. I expect
the tests for most of the other toolsets will pass next time they're
run. Then it's just a matter of seeing if there's anything that can be
done about the remaining compilers that don't implement ADL properly.
>> Either the rule against adding to std:: would need to be relaxed or
>> user code would break when the library becomes part of std::.
Am I correct in thinking that it's permissible to provide a template
specialization of a function in namespace std but not an overload?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2008/07/140526.php | CC-MAIN-2019-43 | refinedweb | 139 | 76.11 |
387 [details]
repro solution
### Overview
Given a solution where:
1. TestApp.iOS references TestApp PCL and ClassLibrary1_iOS
2. TestApp (PCL) references ClassLibrary1 PCL
3. ClassLibrary1 (PCL) and ClassLibrary1_iOS have the same assembly name, default namespace, and methods
when the iOS project is built, the ClassLibrary1_iOS project dll gets copied to app's bin/ directory, but with the wrong mdb file. Instead the mdb file for the ClassLibrary1 PCL project is present resulting in not being able to debug the iOS library project and this error in the debug output:
> 2016-06-17 15:48:17.581 TestAppiOS[41586:3406222] warning: Symbol file .mdb doesn't match image
Note, the Android project does not have this issue even with the same project structure as above. Also, this seems to only be an issue with Visual Studio as testing on XS resulted in the correct mdb being copied for the iOS project.
However, given that both library projects have the same assembly name and methods, I'm not 100% sure what the expected behavior is in this case.
### Steps to Reproduce
1. Run the "TestApp.iOS" project in the attached repro solution
### Expected Results
The breakpoint set in "Class1.cs" inside ClassLibrary_iOS will be hit as this is the method that is called during runtime.
### Actual Results
The breakpoint is not hit
### Environment Info
Microsoft Visual Studio Professional 2015
Version 14.0.25123.00 Update 2
Microsoft .NET Framework
Version 4.6.01584 5.2.603.
Created attachment 16388 [details]
build output
Thank you for a very thorough investigation of the issue and a beautifully clean repro!
We'll take a look. It seems like this wouldn't be an uncommon scenario for developers creating bait&switch PCLs, so I think it's worth investigating and documenting an expected behavior.
Updating Target Milestone to C8SR1.
This bug will be addressed on Cycle10 when we switch to using PPDB instead of MDB for Visual Studio 2015+.
Fixed in 4.6.0.168 | https://bugzilla.xamarin.com/41/41966/bug.html | CC-MAIN-2021-25 | refinedweb | 329 | 66.03 |
How to extract the map matrix after subscribing to /map of map_server?
I need to run Dijkstra's algorithm on this map.
So till now, I've used map_server and got the /map and /map_metadata topics. I'm not quite sure how to proceed further.
This is what I've done so far.
#include < ros/ros.h>
void dijkstra() {
}
int main(int argc, char **argv) {
ros::init(argc, argv, "shortestpath");
ros::Nodehandle n("~");
ros::Subscriber sub = n.subscribe("/map", 1000, dijkstra);
}
/map gives a 1D array so I need to use it and convert it in a 2D matrix.
Why don't you use amcl, and move_base? What is that you want to do exactly? | https://answers.ros.org/question/337009/how-to-extract-the-map-matrix-after-subscribing-to-map-of-map_server/?sort=votes | CC-MAIN-2022-21 | refinedweb | 115 | 85.49 |
The ssh vs. OpenSSH Trademark Battle, Next Round 252
My favorite tidbit from the article is this: "[OpenBSD and OpenSSH Developer Theo] de Raadt cites U.S. trademark law that requires owners of trademarks to notify violators immediately ... de Raadt argues that Ylönen would have to be living under a rock not to be aware of OpenSSH before now. OpenSSH, released in December 1999 and in use before that, was used by more than 17% of all SSH users earlier this month, according to a study published on the University of Alberta Web site." Besides that, the story does a great job of listing other people whose products including "SSH" in their names have been left blissfully alone, making it seem that OpenSSH is getting what can only be called special treatment.
Of interest: here is a link to a page at openssh.com showing the legal papers received and scanned by members of the OpenSSH project, including the trademark application in question, showing an entirely lowercased "ssh" as the applied-for mark.
You think this is funny? (Score:2)
How about unfair corporate use? (Score:1)
I'm not sure if such hijacking is legally possible, or worthwhile, but it would really be unfair and damaging to SSHCS, or any company, which is why we have the trademark laws. This may be one reason why they may have to enforce it.
The reaction of SSH Communications Services may thus be quite understandable and acceptable. But that doesn't of course negate the fact that Tatu and SSHCS made a legally fatal mistake in giving the protocol, the free version of the product, the commercial version, and the company the same name.
bad company (Score:1)
Just to show how much more understanding and reasonable all the other big corporations are, I'm going to introduce the products:
OpenKleenex
OpenJello
OpenSPAM
Re:A name... (Score:1)
0p3N55h3Z 4-3v3R!
Re:What about trademarking other things like this? (Score:2)
I think its too late for that... the trademark has already been sufficiently diluted - I started using OpenSSH about 4 months ago, and I had never even heard of the company until this article.
Re:I like Theo, but that was the wrong thing to do (Score:2)
If you're not compatible, you can't use the name.
That doesn't mean you can use the registered mark. When that was done, there was no registered mark. The Mark is owned by a corporation (founded by this gentlemen, not that it's terribly relevant), and can't be appropriated without authorization.
For example, if I write some code, call my program Microsoft, and say in my license that you may use the name Microsoft in referring to my code, you aren't authorized to use it.
That is hardly a license to a Trademark issued two years after that was written.
The author of the original software asked you not to use the name ssh or Secure Shell if they are incompatible. That is a contractual agreement as part of a license.
The company is using the Trademark SSH to refer to their company and software. When you used that license, you contracted to not name is SSH if it is not compatible. That has NO bearing on the trademark.
Re:Et Tu Slashdot (Score:3)
If his permission to use "ssh" is revocable, arguably so are any other parts of his license -- including the permission to use the code in derivative works. Rolling over on the name could be used in court as evidence that the OpenSSH crew agreed that the license is revocable -- in which case he can next eliminate the whole OpenSSH project, whatever its name. Ooops...
Re:Compromise (Score:2)
Well, at least, it shouldn't work that way. Fraunhofer is doing the exact same thing with mp3. The problem is that there needs to be a distinct line drawn between specifications and products. You shouldn't be able to trademark a specification (such as the SSH protocol).
Question (Score:3)
FluX
After 16 years, MTV has finally completed its deevolution into the shiny things network
What if it were Linux (Score:3)
Encrypted shell (esh)
trusted Shell (tsh)
secure telnet (stn) which btw, is more accurate, as it's not really a shell.
Get involved
FTP and FTQ too! (Score:2)
Re:Et Tu Slashdot (Score:2)
But this part of the law was created for exactly this case... when a trademark owner allows others to invest a large amount of time and/or money into an infringing mark without their knowledge of infringement, and then tries to pull the rug out from everyone at exactly the worst time.
--
SeSH? (Score:3)
The concept of trademarking an application name so close to a standard protocl name is, at best, silly. On the other hand, I don't think that it's worth starting a big fight over. There are far better things to put our energy/ time/ money into.
--
Re:Et Tu Slashdot (Score:2)
I sorta disagree. gcc was not named cc. gnutar was not named tar. They don't have to name their program ssh. RMS would say that they should do things as differently as possible, and provide a --traditional for inter-operability (Btw, I would love hearing what Theo would say if RMS tried to tell himn what to do
Sure gnuls would be ridiculous, so my example isn't worth much. Even apache is named httpd, so...
> By your standards F-Secure is diluting the ssh mark
Frankly, I don't know. I was just saying that *I* often confused ssh and openssh, and that *I* would have zero problem using asfkaos (A Shell Formelly Known As OpenSHH) as it would help me to stay away from ssh(tm) products.
OTOH, maybe you are right, and ssh corp should be told to f*ck themselves...
Cheers,
--fred
It's a suite of products, people! (Score:2)
"ssh" is a secure replacement for rsh, "slogin" is a secure replacement for rlogin, and "scp" for rcp.
rsh was for remote shell, ssh is for secure shell.
That's why, so if you think you're cool and are allowed to speak just because you popped a RedHat CD into your Packard Bell, please reformat, reload windows, and don't come back.
Thank you.
-Nev
He's being "nice", but... (Score:5)
O SSH [pdc.kth.se]
TTSSH [zip.com.au]
NiftySSH [lysator.liu.se]
MacSSH [macssh.com]
Java-SSH [cam.ac.uk]
TGssh []
sshCE [movsoftware.com]
An OpenVSM project called just SSH [ohio-state.edu]
SSH-OS2 [nmsu.edu]
...
and, well, you get the point. He's just going after OpenSSH because they're beating him in the market. And not only does he have no legal leg to stand on, but he's being a real slime by only going after the successfull one. Theo would be right to tell hime where to stick his lawyers.
Re:What if it were Linux (Score:2)
he's done that. there was a story on slashdot a while ago about it, but it would be a horrendous pain in the ass about it. basically, linus has no problem with use of the lunix trademark as long as it's done in good faith. but when somebody registered a bunch of linux-related domain names so he could sell them, linus threatened action, and the guy backed down.
note: that's how i remember it. i could be on crack.
Last license I buy from SSH Inc. (Score:2)
opensource project with a very good stance on why it did and should continue to use the name OpenSSH. I was planning on rolling out SSH this summer to over 800 desktops/servers. I guess I will be DEFINATLY going with OpenSSH in light of these developments.
Re:Et Tu Slashdot (Score:2)
A name... (Score:4)
I like Theo, but that was the wrong thing to do... (Score:4)
Good job. We have now taken the position to the outside world of being total assholes.
The guy made an effort NOT to bully an Open Source group. He didn't send threatening lawyer letters. He asked people to be reasonable. Quite frankly, you're going to lose BADLY in a court of law, because not only is there the possibility of confusion, but there is DOCUMENTED confusion.
Now, this is totally absurd.
He didn't bully, DON'T use that against him. The arguement that he didn't bring it up until confusion happened may be legally correct, but now sets the horrible precedent that Open Source groups will be as shady as possible, and if you give them an inch, they'll take a mile.
Notice something, the original license (if anything tells people not to be nice and release their source code, this is the example, that was hardly a license, more of a nice gesture) allowed you to call your application ssh.
That's irrelevant.
OpenSSH could be renamed, OpenSecSH, which would be an open implementation of the SecSH protocol, which is the name of the working group. The FILE could still be called ssh/sshd.
SAMBA couldn't call itself SMB, confusion reasons, but the applications use SMB (like, smbd).
However, you can be polite, compile as osecsh and osecshd and include a symlink (automatically, but prompted) for ssh and sshd, so if you have both implementations, you can decide which one you want.
However, if the Open Source community insists on fighting on the Trademark grounds, we're in the wrong.
You can dispute the merits of Software Patents.
You can dispute the merits of long copyright terms.
You can dispute the merits of copyrights in general.
You can't dispute the merits of Trademarks.
Trademarks are the only thing that prevents confusion in the marketplace. If people are confused and think that OpenSSH is from SSH, then there is a legitamate issue.
Also, I don't think you're going to win on the enforcement. One year or so is reasonable, given that OpenSSH has minimal press coverage, etc. I think that it would be EASY for SSH to show that they found out about it, saw a problem, and then asked them to fix it.
Theo, you're going to lose, and you're being a bastard. He hasn't demanded that you stop making a version of SSH, just that you not use his product name.
Theo, I'm an OpenBSD user. I love OpenBSD. I love OpenSSH. You're in the wrong here... VERY WRONG.
Alex
Et Tu Slashdot (Score:5)
Now it's open sources' turn. The right thing to do is honor the wishes of the guy who created SSH, the guy who made SSH available to you (albeit with a license you didn't like), and the guy who still tries to make a living from his hard work.
Give up the conflicting name. Not because you have to. Because it's the right thing to do.
Prompt nodification (Score:3)
-Moondog
Re:Et Tu Slashdot (Score:5)
He gave the name away, and now he regrets having done so. Well, too bad. OpenSSH used the name with the entirely justifiable understanding that this was allowed. They took nothing that had not been offered. They built a brand of their own, which the original author now wants to destroy since it is becoming competitive.
That's dirty pool.
Claim your namespace.
Compromise (Score:5)
If he doesn't want it to escalate, then he'd best compromise. I think that there's a broad feeling of indignance in the OpenSSH developer and user community that there's a "submarine trademark" (if I may put it that way) on something which we consider to be the name of a protocol. I think there's going to be a great reluctance to go ahead with a name change, because it would let the nose of the camel into the tent. What next -- remove all mention of "SSH" from the documentation?
If Ylönen demands no less than the removal of "SSH" from the project name, and OpenSSH isn't willing to do this, then he has the choice of either backing down or going ahead and making himself really unpopular by suing a free software project. This whole direction does not strike me as being one that can result in a net win for Ylönen. If he wins his trademark rights he'll establish himself as an enemy of the OpenSSH community; if he loses his trademark he looks like a poor businessman.
Instead, he should cut his losses and suddenly realise that he can license the use of the trademark to the OpenSSH project for free, on condition that they clearly distinguish themselves from his product, and perhaps provide linkage to his web site as a clarifying measure. If the real problem is customer confusion, then let's deal with the confusion without all this ugly legal sabre-rattling nonsense.
Does Ylönen realise that he's setting himself up as an enemy of the Free Software Republic? This isn't sensible.
Re:Too Little, Too Late (Score:3)
All this time our policy has been that the trademarks cannot be used by others without a proper acknowledgment, and cannot be used in product names without a special license from us," he said. "We have enforced it against all significant players in the field," he added. "We have not felt it appropriate to go after every random web page or the various non-commercial student projects done at universities."
So which is it? Do we think it's better for a trademark owner to go after every single petty violation? Or does it seem to be more fair when a trademark owner lets some of the little guys slip through the cracks, but then has to take action if they become larger? You can't have both worlds...
(granted, there was that other clincher, but your particular argument conflicts with other common slashdot sentiment)
--
Re:Have a contest for a new name (Score:2)
M$ probably thinks they own the CE suffix. winCE and all.
so would you rather M$ go after you or that SSH guy?
;-)
--
Re:You thnk ths s funny? (Score:2)
At least there's no (TM)s n your username.
Re:Et Tu Slashdot (Score:2)
The Project History and Credits section of the OpenSSH website would seem to refute your assertion:
The original license contained the following text:
While I can't personally vouch for the veracity of the OpenSSH history, it and the original license not only seem to directly contradict your assertion that "you couldn't use it for commercial purposes", but also seems to imply that if a derived version of the original is compatible with the protocol description, then he has no problem with someone referring to it as "ssh" or "Secure Shell".
Also, The SSH transport and user authentication protocols have been submitted to the IETF [w3.org] by Ylönen himself, which I believe qualifies as "submit[ting] as an open standard". As a matter of fact, it's currently the main focus of the Secure Shell (secsh) IETF working group [ietf.org].
All in all, this parallels the "one click" scenario pretty closely, with the difference being that SSH was far more novel and complex an idea than "one click" shopping. If Mr Ylönen had released it as a commercial product, or even just released it under a more restrictive license, there would be no debate. As it stands, though, it reeks of dodgy business practices brought on by stockholder pressure and OpenSSH's success.
Re:I like Theo, but that was the wrong thing to do (Score:3)
That's what I thought until I read the last bit of his letter to the OpenSSH developers:
This is why we have contacted Corenic.net, your domain registration provider, to cancel all service on the "openssh.com" domain.
Until I read that, I sympathised with the SSH company - I thought they were doing the right thing by just requesting instead of sending the attack-dog lawyers. However, they made an agressive pre-emptive strike to destroy openssh.com's domain before they even have had a chance to consider changing their name.
If I were in charge of OpenSSH, I would have gladly changed the name of my code has he not pre-emptively tried to destroy my domain before I had a chance to even consider what to rename my product to!
Re:Et Tu Slashdot (Score:3)
Agreed. The SSH chap sounds like a decent, pleasant fellow. Given that by far the hardest thing he's asked the OpenSSH people to do is choose a new name, and that he's contributed significantly to their own success, it would show a lack of common courtesy should they refuse to comply.
I honestly can't see why
/. is making such a fuss about this, it smacks of mob hysteria and, as you say, double standards.
Re:What about trademarking other things like this? (Score:2)
-m
Let me get this straight... (Score:4)
Puh-leaze!
Enough with the stupid intellectual propery lawsuits already.
I think Tatu's just pissed that OpenSSH is a better product than his commercial SSH, and that OpenSSH is becoming so widely used that it, and not Tatu's commercial ssh, is what people generally mean when they say, SSH. Shit! Now I've just supported his case.
Re:Compromise (Score:3)
The only thing he can do is modify the name of his product, trademark the new name, and launch an advertisement campaign to make it known.
Re:What if it were Linux (Score:2)
Who is on the side of "trademarks are bad"? We're on the side of "selective enforcement of trademarks are bad, and most likely invalid".
No, it isn't, and had Ylönen requested that the OpenSSH project change its name near the beginning, and been requiring that other SSH impementations that he knew of change their names, I at least wouldn't be objecting to this. By singling out OpenSSH for this treatment, springing this upon them (apparently) more than a year after OpenSSH was started (with much controversy over the domain names, if you will recall - this wasn't a stealth project), and assisting with the development of other SSH implementations without requiring that their names be changed, he created this situation.
Re:lets not have a double standard (Score:2)
There is, there should be, and they did based on what was true at the time.
There is an expiration on the time to prosecute, and their very well should be. Statute of limitations exist for many things. Generally the idea is you have to decide _now_ if something pisses you off enough to sue, not wait until 10 years down the road when your company isn't doing so hot and needs some extra loot. If someone has a trademark, they have to defend it. Waiting until someone else has established their own name and then trying to take them down is not only dirty, it flies in the face of the law.
When OpenSSH started, they believed they were ok to use that name. So they only thing they could have "known better" was to know that once their product started to steal market share from ssh, SSH would turn on them.
And lastly, how exactly would this be SSH getting their name back? Have they been unable to use it in the interim? No. Is OpenSSH the same as SSH? No. Can you attack anyone whose name contains part of yours? Maybe if WIPO is presiding, but not in US law. I can name my application "Something Explorer" without being sued by MS.
Yes, OpenSSH used the ssh name, but only in the sense that the name OpenSSH accurately describes what it is and does. I can see the name and say "ah! an open implementation of ssh. much preferable to that closed source garbage." So the gains made by OpenSSH were as much because of conscious decisions as name similarity. It's not like releasing a soft drink in a red can named Coca-Cola, where people think your product is the same. It's more like releasing a product called "Generic Cola" in a red can -- people can quickly figure out that it is supposed to be like Coke, but is cheaper. If Coke really does taste better than Generic Cola, then people will still buy Coke. If not, then that's Coke's problem, not an invitation for their lawyers to try to shut down Generic Inc.
Side note: if SSH really wanted to have a distinct name to build a brand around, they shouldn't have just used the "single-letter abbreviations for what my shell is, followed by sh" naming convention. If I were to decide, that right there would lead me to rule that their trademark was unenforceable.
Re:FTP and FTQ too! (Score:2)
-Don
Re:What about trademarking other things like this? (Score:2)
rsh is not a shell itself, it provides access to a "remote shell". In the same way, a secure shell would be any shell that you got access to securely.
Which leads to my favorite new name for the open source version: what it does is "opens shell" or, OpensSH. There, everybody happy now?
Re:Prompt nodification (Score:2)
Both trademark and patent laws contain provisions requiring that the owner file claims within a limited period of time. In the case of SSH the trademark holder may already be too late.
MOVE 'ZIG'.
Re:Not only is this dumb... (Score:3)
Nah. Trademark law provides for unrelated products to be sold under the same trademark without infringement.
MOVE 'ZIG'.
Re:Skipping to the meat of the letter: (Score:2)
Bzzzt. Wrong. The main point of law is the question of whether the name domain OpenSSH might cause confusion. In this case, given the identical functionality if the products I think they have a good case.
MOVE 'ZIG'.
Well, here's telnet... (Score:2)
Yet.
Re:Not only is this dumb... (Score:2)
No, this is not always true, see the case of Visa condoms [jenkins-ip.com] being denied, even though it's nothing to do with credit cards.
--
Re:There's the solution! (Score:2)
Maybe they should rename OpenSSH (Score:4)
Butt-Head Cryptographer...
Besides, I can type bcp a smidgeon faster than scp.
Re:Microsoft's Lawyers Fixed this for Openssh (Score:2)
Microsoft DO have some deal with them, but both sides refuse to reveal details of it.
* explorer is a registered trademark of the symicron GmbH
Samba Information HQ
Re:Skipping to the meat of the letter: (Score:2)
Re:lets not have a double standard (Score:2)
Apples and Watermelons. (Score:5)
This is nothing more than a company trying to rescind the actions of it's founder to protect a failing business strategy.
Why? Because people are being drawn to the open-source implementation rather than paying out good money for something they can get for free.
Tatu's also probably peeved that OpenSSH will receive wider distribution (through Linux, BSD, and possibly OS-X sales/downloads) than his company's probably capable of. And thus will be more likely to achieve ubiquity than his proprietary, commercial products.
Sorry, but it doesn't work that way Tatu. You can't fish something out there until it hits name-recognition status, then make them change their name so you can supplant them. The community is NOT your advertising tool.
Chas - The one, the only.
THANK GOD!!!
Re:secshell (Score:2)
Imagine that he did back in 1999 when OpenSSH was first released. What would have been the Slashdot reaction then?
Well, (Score:2)
No, wait, don't sue me!
;)
-Omar
(or SwiSH
or SwaSH
or...
)
Re:Skipping to the meat of the letter: (Score:2)
Actually, when I read the letter, I sawAre you just trying to stir up the flames?
Re:secshell (Score:4)
No, your understanding is wrong. The standard is called "SSH". Look at the IETF SSH Protocol Description [ietf.org]:
Abstract.
Re:What about trademarking other things like this? (Score:2)
much like the .arc extension begat .zip (Score:3)
More than a decade ago, we saw this with SEA trying to enforce the
It could happen again.
Re:What about trademarking other things like this? (Score:3)
The major marketing investment done in SSH has been made by Unix system admins who needed a secure and practical (and easily obtainable) way to connect between hosts, and who were later left to fend for themselves as the product went closed and unsupported on a large number of platforms.
And, frankly, having gone through the pains of dealing with the forms of licensing of SSH and having salesmen tell me there is NO version that has ever been free (ok, I know more about the licensing than the salesmen) to the various other stages, it was a true pleasure to dump the commercial branch and go entirely with OpenSSH.
If SSH has any brandname value it is despite SSH Inc, not because of it.
Re:its kinda too bad, but its the rules (Score:2)
Who even knew it was trademarked? Did they ever attempt to let anyone know this before? No.
SSH is the common word for a protocol; everyone knows that. It's already been what trademark law calles, 'diluted'. It's a common name now; once something is common like that, you can't take it back just because it's trademarked. Everyone already has something in their mind when they think of 'ssh', and it's not this guys product in particular, it's merely the protocols involved.
Re:Et Tu Slashdot (Score:5)
'."
This would pretty clearly seem to imply that as long as OpenSSH was creating a protocol-complaint product that they were welcome to use the name ssh. Otherwise it would have said something like "SSH is the trademark of SSHC, INC, and may not be used without our permission, period".
Unless I am missing something here, it would seem as if Ylonen pretty clearly authorized other compatible and derived products to use the name 'SSH'. And once that permission was granted, it can never - at least not if we want to 'do the right thing' - be taken back.
Claim your namespace.
Re:FTP and FTQ too! (Score:2)
-Don
ssh... short shiny hair? silly slimy hubris? ... (Score:2)
Re:Skipping to the meat of the letter: (Score:2)
This part, however, goes too far:
This is why we have contacted Corenic.net, your domain registration provider, to cancel all service on the "openssh.com" domain.
Where is that bit? I can't find it. Thanks
Re:Do they have the right to do this? (Score:2)
-Don
Future Projects (Score:2)
Next time, when we start a Free project aiming to be compatible with someone else's code, why don't we *TALK* to them first?
I'm not saying we should ASK for permission to use name or anything, but just to get an idea how they'd interpret their own agreements.
Say, if the OpenSSH team talked to SSHC and said "Now we have your 1.27 license, and it says we can use the name if it is compatible. Can you verify that?"
If they said "Ok you can use that" then they'd better keep their mouths shut at this time. Too bad it wasn't what happened.
Command Names and Trademarks. (Score:2)
This case is worrying, however, because ssh is also the name of the command. The trademark is not only identifying a brand, it is also the thing you type to perform an action. If DEC (or whoever) had patented "dir" they would have made competing OSes less attractive because new OSes would have to invent arbitrary different names for conceptually identical commands. If SSH enforces the trademark, it is only reasonable that they must fight against alternative implementations using the command "ssh".
This would lead to a repeat of the look-and-feel wars of the GUIs, only this time fought over CLIs using trademark law. LnF was about users moving to different platforms/apps and expecting things to work the same. CLI is no different: users expect telnet to do approximately the same thing on all platforms. If command names are choosen to avoid infrigement, we all will lose.
Re:An idea! (Score:2)
Next you'll say "I'll trademark the trademark symbol! Then anyone who trademarks anything will violate my trademark and I'll sue them for trademark infringement." (that idea is trademarked btw. And so are the three letters btw)
Now lets all have a good laugh while our mod points die.
"Me Ted"
Re:Microsoft's Lawyers Fixed this for Openssh (Score:2)
--
What about trademarking other things like this? (Score:5)
However, on the other side of the table is OpenGL and Mesa3D. Now, MesaGL would more accurately describe what Mesa3D emulates, but GL is a trademark of SGI, and they probably wouldn't like it if it was used without their permission. The best solution would be for the designers of OpenSSH to change their name and avoid any more disputes. This would also give open source developers a more moderate reputation, as opposed to the uncompromising one they seem to have nowadays.
what's next (Score:2)
Lawyer: not open and shut, but close (Score:4)
I'm not certain which jurisdiction's law governs here (and am not going to do the hour or two of research unless someone pays
He said that software could be used and modified, and that *incompatible* programs must not use the ssh name. That doesn't *give* permission to call compatible programs ssh, but it certainly implies it. Similarly, finding someone with a smoking gun in his hand over the shot and still bleeding body doesn't *prove* he killed him, but there's a whole lot of 'splainin' to do . . .
I don't see where he can go with this without producing more info. With implied consent and five years of silence, it's a real hard row to hoe . . .
hawk, esq.
Re:A name... (Score:2)
--
wrong view of the candy (Score:2)
Can't he sell support for OpenSSH? (Score:2)
Since his company apparently has problems and lots of people contant it for support for OpenSSH, couldn't he just start supplying it, for a fee? It seems to me they should be capable of that, and they'd be in a great position to point out the advantages of using their own, commercial ssh...
Re:I like Theo, but that was the wrong thing to do (Score:4)
I agree with you on this point. But on the overall argument I disagree. Yes, Tatu is trying to be nice. And yes, Theo is being an asshole. But that being said, I don't see how Theo's going to lose this. With his current attitude, he's in danger of losing the PR battle, but that seems to be it.
Have you seen the license for ssh 1.2.12 (which is what OpenSSH is based off of)? Here is the most salient part (IMHO):
The only thing he says about the name is that if you're not compatible, then you can't use the name. Which leaves the only possible interpretation to be that if you are compatible, you can use the name.
I think that it would be a nice gesture on OpenSSH's part to give up the name. But I don't think it is, by any means, required. And if OpenSSH wishes to protect their identity, using a publically available name, that's entirely up to them. Theo could be more nice about it, but I don't think he'd be in the wrong to keep the name.
Re:Et Tu Slashdot (Score:2)
I have been confused between openssh and ssh numerous time. Both commmands are named 'ssh', and I think it is an error.
Anyway, the request seems pretty stupid, as OpenSSH is doing a lot of good to ssh corp. If OpenSSH renamed the command to something less related to ssh, like pinss (pins is not secure shell) or yass (yet another secure shell), then ssh corp will loose a lot of mindshare.
Making the issue into "we can legally keep the name" is plain wrong. They want the name ? Give them. The name is just a name. The free alternative is better, so will succeed under any kind of name (and, people will alias ssh to wosin [whatever open ssh is named] anyway, so the pratical impact will be zero).
Cheers,
--fred
Nice Take... (Score:3)
This story [segfault.org] makes a nice point.
There's the solution! (Score:2)
Well, then, there's the solution: just rename OpenSSH to OpenSTN (Secure TelNet).
Sure, name changes are hard, but in Quake, when a rocket is barreling towards you, what do you do? Strafe to the side, right! And this is the legal equivalent of that.
I've gotta admit... (Score:2)
I think SSHCS's claims have no standing, and their decision to ``defend their trademark'' against only a single product sheds a poor light on Tatu Ylonen.
Nonetheless, the letter is much, much friendlier than what I've seen in similar cases -- i.e., cease and desist yesterday.
IMO, it looks like SSHCS is following good and proper form as they do this entirely questionable act
:-/
Uh-oh, you're screwed (Score:3)
It's Pizza and OS/2 from now on.
Sorry, but you better get rid of OS/2, also. I think RMS and the FSF have had a trademark on the term "half an OS" for about the last 5 years of HURD's development.
:)
Cheers,
Re:Too Little, Too Late (Score:2)
Also, unless Tatu is lying outright, he says (in the paragraph that I quoted) that OpenSSH is NOT the first to be "attacked".
--
OpenSSH named after protocol or application? (Score:5)
For countless reasons, I'm sure it's the latter. But that begs the question of why SSH-the-company was so incredibly incompetent that they named SSH-the-protocol after SSH-the-application even though virtually all servers and clients try to incorporate their protocol into the name. TELNET, FTP, FINGER, PING, HTTP(D), etc. Sendmail and bind are two notable exceptions, and of course this can't apply to multiprotocol clients (e.g., Mosaic, Navigator/Commuicator).
OpenSSH, to me, says one thing and one thing only - that it's an "open" implementation of the "SSH" protocol. It has absolutely no connection to SSH-the-program or SSH-the-company other than the historical curiosity that the latter originated the protocol and is pushing it on the standards track. (Something which is undoubtably dead in the water until they (SSH, not ISO) pull their head out of their corporate assh.)
If SSH-the-company wants to keep the identity of SSH-the-program distinct from SSH-the-protocol, they should change the name of SSH-the-program.
Read Yesterday's Article... (Score:3)
Trademark law applies only to commerce (Score:2)
But that's not true. What the owner obtains are exclusive rights (within one field) to use the trademark in commerce. Read the law:
I recently announced my plans to set up freebugtraq [cr.yp.to], a non-commercial competitor to bugtraq. I was promptly threatened with a trademark lawsuit. Where do trademark owners get the idea that they can control non-commercial activities?
Re:I like Theo, but that was the wrong thing to do (Score:2)
Saying "If you do that, you'll look like a total asshole" to Theo de Raadt is pushing him to do it. Ask around you "who is the biggest open-source asshole ?". If you remove the goatse.cx (which may not be opensource), most answers will point to Theo.
He is already the most appreciated asshole of the community.
Cheers,
--fred
secshell (Score:2)
Clearly the problem is that there are multiple tools that are used the same way and called the same thing. ssh makes a secshell connection to address with terminal emulation. One of these tools has a trademark on ssh; I think its actually in a good possition to make a case that the other tool should use a different name, such as the more descriptive secsh.
-Daniel
Re:I like Theo, but that was the wrong thing to do (Score:3)
Read USC title 15 section 1115 for the various reasons that a trademark can be contested. There are at least 4 possible separate paragraphs that can be used in this case, including prior use, abandonment, permission and mark functionality.
All this is is a lesson to other people that legalities like trademark issues, patents and license issues isnt something you play around with and later decide what you really meant (or change your mind about it). SSH has been messy this way from the beginning.
Re:secshell (Score:2)
Re:Maybe next time.. (Score:2)
SSH would be exactly there, had they gone down that route from the beginning.
The author of SSH was kind enough to release his code and make it public (sorta had to since he had GPL parts in there at the time), we were nice enough to decide ssh was a good idea and use it in a lot of places, creating the market for him. We got a turnaround, license changed, proprietary product that didnt work on all platforms any more and an incompatible shiny new protocol.
Re:You think this is funny? (Score:2)
That's good enough for me!
John
Re:OpenSSH named after protocol or application? (Score:2)
Am I being obnoxiously picky? Yeah, I suppose so.
Too Little, Too Late (Score:5)
Theo de Raadt, co-creator of OpenSSH,."
Looks like it is too little too late as far as trade mark enforcement goes. If nothing else, Ylönen may be trying to cash in on the name of OpenSSH.
Although there is a point that he (Ylönen) has to do something, I suppose, and better late than never. But it is likely too late.
Oh yeh, IANAL btw
Is this a troll? (Score:2)
Trademark law is there to protect the consumer. Who can honestly deny that OpenSSH has been hurt SSH's business? The only point in contention is that SSH waited to long to enforce the trademark by being NICE -- by emailing the team over the period of a year, several times, at least from my interpretation of the letter in the last Slashdot piece on SSH.
Being NICE is something Slashdotters always seem to want corporations to do. And now it make have cost SSH its trademark. But we don't care, because we're so wrapped up in our own superiority and rights to entitlement that we bite back whenever it's something we disagree with, even if it's a double-standard. This attitude is no less evil than an "evil" (tongue-firmly-in-cheek) corporation.
Let's remember that there's a trademark on LINUX.
what about the SH? (Score:2)
Re:I like Theo, but that was the wrong thing to do (Score:3)
But is this confusion really caused by OpenSSH having a name that is similar to SSH, or is the confusion caused by the fact that Tatu Ylonen chose to overload "SSH" to mean both a product and a protocol?
If OpenSSH is renamed to "FooShell" but still implements the SSH protocols, confusion is going to remain. The reason there will be confusion is that the word "SSH" (more often than not) will still refer to something that might not be SSH Communication Security's product. Just as when people talk about Cola, they're not always talking about Coke.
---
Re:What about trademarking other things like this? (Score:3)
According to the SSH version 1.2.12 license:
'."
OpenSSH is doing nothing illegal in using the term "ssh", because OpenSSH is a derivative work of ssh 1.2.12 and is compatible with the RFC.
Now, Mr. Ylönen may regret having given that permission. But the only argument he can make is that the OpenSSH name is not sufficient to mark that the software is a distinct derivative work of ssh. If so, he can object to the OpenSSH name itself, but not the use of "ssh" in the name.
BTW, Kleenex® and Xerox® (along with Velcro®) are still trademarked (at least in the U.S.) due to the extensive efforts of their legal departments. Partly because their founders had the sense to not issue a license allowing other people to call their products Kleenex, Xerox, and Velcro, unlike Mr. Ylönen.
Re:Et Tu Slashdot (Score:2)
What I'm having a problem with is that SSH is the acronym for a protocol that has been submitted to standards bodies by the holder of the SSH trademark. By definition anything submitted to the public standards bodies becomes part of the public domain.
Aside from the use of the term in the standards documents, there has been no apparent attempt to stop anyone other than the open source development team from using SSH in the name of their "product." As someone else has pointed out in these threads, trademark defense has to be consistent to be valid.
I'm not sure a trademark on the acronym SSH is valid without being more specific about the design of the trademark. Even IBM's trademarks aren't on the three letters IBM, but on specific color combinations and fonts for their famous corporate logo.
Although I generally don't feel Ylonen is acting in good faith in this matter, I'd rather see us switch to a name like OpenSTN, provided that the documentation submitted to the standards bodies are also updated to use a protocol acronym other than SSH. Whatever acronym is used for the standard is the acronym that should be used by Open???.
I don't agree with comments in this thread that the open source project should have a page crediting and linking the commercial provider's site. If anything, they should be referencing the site and documentation from the standards bodies describing the protocol. Once a standard has been submitted to ISO, ANSI, W3C, or any other such body, it is the standard that becomes important for determining interoperability, not the identity of the originator. Any historical credit for the standard should be referenced by the standards documentation, not by the open source implementation.
Have a contest for a new name (Score:2)
My vote is for Cryptonomicon Enabled
Nobody would object if we put a CE after everythingtelnetCE
ftpCE
fooCE
barCE
loseCE
Re:I like Theo, but that was the wrong thing to do (Score:2)
Open Source should take the High Road (Score:2)
OSS should take the high road and just rename itself. If OpenSSH does it now, then they can say they made their own decision and did it because they wanted to. If they wait too long, then stronger words will be used by both sides, and pretty soon emotions take over and you can kiss common sense and cooperation goodbye.
So, OpenSSH, change your name, not because you have to, but because you can. Be altruistic. I think that's the best outcome that will make everyone feel good about themselves and others.
Skipping to the meat of the letter: (Score:2)
Microsoft's Lawyers Fixed this for Openssh (Score:4) | http://it.slashdot.org/story/01/02/16/0217209/the-ssh-vs-openssh-trademark-battle-next-round | CC-MAIN-2014-52 | refinedweb | 7,324 | 71.75 |
HTTPS Transport Reference
Nicolas Earnshaw
Apr 15, 2014 16:24
Jan 16, 2015 14:55
This menu uses JavaScript. Please enable JavaScript in your browser to use this feature.
As of Mule 3.6 and later, the HTTP endpoint-based connector and transport has been replaced by an operation-based HTTP connector.
The legacy endpoint-based connector will be removed in a future version. See HTTP Connector for more information about the HTTP operation-based connector and how to migrate your projects to it..
This connector provides Secure HTTP connectivity on top of what is already provided with the Mule HTTP Transport. Secure..
Property
Description
tls-client
Configures the client key store with the following attributes:
tls-key-store
Configures the direct key store with the following attributes:
tls-server
Configures the trust store. The attributes are:
tls-protocol-handler
Configures the global Java protocol handler. It has one attribute, property, which specifies the java.protocol.handler.pkgs system property.
java.protocol.handler.pkgs
For example::
PollingHttpConnector
Attribute
pollingFrequency
The time in milliseconds to wait between each request to the remote http server.
checkEtag
Whether the ETag header from the remote server is processed if the header is present.
discardEmptyContent
Whether Mule should discard any messages from the remote server that have a zero content length. For many services, a zero length would mean there was no data to return. If the remote HTTP server does return content to say that the request is empty, users can configure a content filter on the endpoint to filter these messages out.
For example, after defining the HTTP namespace in the header, you could configure the polling connector like this:.
The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL endpoints by manually setting which cipher suites Mule can use and which SSL protocols are allowed:
tls-default.conf
tls-fips140-2.conf
Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols.. | http://www.mulesoft.org/documentation/display/current/HTTPS+Transport+Reference | CC-MAIN-2015-18 | refinedweb | 359 | 54.52 |
Peer to Peer Series Part 7: PeerChannel Basics
Update: To see how to extend this solution for custom per-page transitions, see
my follow-on article.
If you have played around with Silverlight on Windows Phone 7, one thing you may have tried to figure out is how to add nice transitions between different pages of your application. By default, Windows Phone page transitions aren’t really transitions at all. The new PhoneNavigationPage is just popped into the root PhoneNavigationFrame. Effective, yes. Cool? Certainly not. Face it, modern mobile applications need to not only be functional, but also stylish. Simple “snap” transitions just don’t cut it.
The most common solution to this problem is to use brute force and manage the transitions yourself. You commonly see a “pattern” used in WP7 apps where events in your current page launch a Storyboard animation. When that animation is complete, the actual navigation to the new page is invoked and the new page then runs its own Storyboard once it is loaded. It looks something like this…
// CURRENT PAGE private void CurrentPage_Click(object sender, EventArgs e)
{
SomeStoryboard.Completed += new EventHandler(SomeStoryboard_Completed);
SomeStoryboard.Begin();
}
void SomeStoryboard_Completed(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Favorites", UriKind.Relative));
}
// NEWPAGE
protected override void OnNavigatedTo(Microsoft.Phone.Navigation.PhoneNavigationEventArgs e)
{
base.OnNavigatedTo(e);
SomeNewStoryboard.Begin();
}
It’s a straightforward solution, and it works just fine if your app has only a few pages. If you have lots of pages in your application, however, it becomes quite tedious and hard to maintain.
A better solution can be found by turning to the Silverlight Toolkit. The great thing about having Silverlight on WP7 is that you can leverage many existing Silverlight assets. In this case, we leverage the TransitioningContentControl from the Toolkit. The TransitioningContentControl was created for the traditional navigation-based Silverlight application to solve the same problem we are currently facing.
To get started, download the Silverlight Toolkit from CodePlex. Once installed, you will need to add the System.Windows.Controls.Layout.Toolkit assembly to your WP7 project.
If you are not familiar with the TransitioningContentControl, it's a fairly simple control. The TCC is comprised of two ContentPresenters – current and previous. When you update the Content property of the TCC, it will take the content of the CurrentContentPresenter (if present) and move it to the PreviousContentPresenter. The new content is loaded into the CurrentContentPresenter. The TCC, however, manages the visibility of the previous and current ContentPresenters so that the “old” content is visible and the “new” content is hidden. It then uses a Storyboard, which is defined as part of the TCC’s VisualStateManager, to transition from the “old” content to the “new” content. If you are not familiar with Storyboards, the Visual State Manager, or other designer-type topics, have no fear. The TCC comes with a set of standard transitions, which you can use out of the box.
Getting the TCC to work with our WP7 app is a simple process. First, we need to modify the ControlTemplate for our PhoneNavigationFrame to use the TCC. By doing so, we automatically enable transitions between any PhoneNavigationPages we add to our app. To change the PhoneNavigationFrame, open the App.xaml file. Then, add a couple of namespaces to the xaml:
xmlns:layout="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
Now, modify the PhoneNavigationFrame as shown below:
<phoneNavigation:PhoneApplicationFrame x:
<phoneNavigation:PhoneApplicationFrame.Template>
<ControlTemplate>
<layout:TransitioningContentControl
</ControlTemplate>
</phoneNavigation:PhoneApplicationFrame.Template> </phoneNavigation:PhoneApplicationFrame>
The TCC has its Style property set to a StaticResource. This Style provides the default transitions and is also where you would add your own VisualStates and Storyboards if you would like to add custom transitions. This Style can be found in the Silverlight Toolkit in the TCC Sample Application, or you can get it from the sample WP7 application linked to at the end this article. The Style is long, so I won’t show the entire thing here, but the first parts of the Style are included below to give you an idea of what the Style contains and how it is used by the TCC.
<Style x:
<Setter Property="Transition" Value="DefaultTransition" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="layout:TransitioningContentControl">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2">
<vsm:VisualStateManager.VisualStateGroups>
<vsm:VisualStateGroup x:
<vsm:VisualState x:
<:02.300" Value="0" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
<vsm>
</vsm:VisualState>
Though I won’t break the Style down in detail, I’ll point a couple of highlights. First, the Transition property is set to the VisualState that you would like to use as the transition between pages. Every transition will use this VisualState storyboard. The DefaultTransition VisualState is an example of how Storyboards are constructed for use in a transition. As you can see, each Storyboard must target both the CurrentContentPresentationSite and the PreviousContentPresentationSite (these are the ContentPresenters discussed earlier). You can target more than one property, if you like. Below is a custom transition that rotates the projection plane and the opacity of the ContentPresenters.
<vsm:VisualState x:
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="90"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.
<EasingDoubleKeyFrame KeyTime="0" Value="1"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimation Duration="0" To="0" Storyboard.
<DoubleAnimation Duration="0" To="1" Storyboard.
<DoubleAnimationUsingKeyFrames Storyboard.
<EasingDoubleKeyFrame KeyTime="0" Value="90"/> <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="1"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
That’s it. You now have transitions any time you Navigate to a new PhoneNavigationPage.
Actual format may change based on video formats available and browser capability.
Thanks, I like the video. Would love to see a bit more high quality video. I downloaded the HWMV (High) but can't read the blend screens.
Sources please?
I will be getting source up to my site, slickthought.net, in the coming days. I had a bit of a hoster issue that took my site offline so we had to pull the download links from the article. Check the site at the end of the week and I should have a post up pointing to the download.
Great example! That's what I needed.
OOOPS, SOME PROBLEM
For the reasons I don't know, adding a reference to Layout.Toolkit prevents aplication from starting, i.e. I see only black screen instead of first page. This happens even when running your source file.
I have Windows Phone 7 CTP from April refresh and Silverlight Toolkit v3 from November 2009.
What is going on?
Hmmmm... not sure. I just got the April CTP up and running and have not had a chance to try out the FindAZip on it yet. Maybe grab the TransitioningContentControl source code from the Toolkit and add that directly to your project. Might be able to identify the problem that way. I will try and get a look at it when I get some free time.
There is a major bug with the Windows Phone 7 April Refresh that prevents it from loading any code signed assemblies that are not part of the Windows Phone 7 SDK. There is a work around
you have to do this for nearly every control you add outside of the base sdk. Even standard silverlight dlls like System.Windows.Browser.dll
Jeff:
There is another bug with your app in the new refresh. They got rid of the TopLevelNavigationService property alltogether. I haven't been able to find an alternative so your global error handler breaks.
Thanks for the info Jeff!
For the TopLevelNavigationService... (I don't have the code in front of me - on a different laptop), if it is what I am thinking of, you will have to use the Application.Current.RootVisual and cast it to a PageNavigationFrame and grab the Nav service from there. That's my guess...
Hey Jeff
Nice one!
But I can't get it to run in my solution. got rid of the signed assemblies bug but I get a senseless XAML parseexception from this line:
<layout:TransitioningContentControl
When I run it, I get this:
XamlParseException occured
2024 An error has occurred. [Line: 19 Position: 12]
Parser says this:
Error 1 [Parser_SetValue_Exception]
Arguments: System.Windows.FrameworkElement.Style
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See [Line: 144 Position: 39] C:\Users\Hypi\Documents\Visual Studio 2010\Projects\WinPhoneRSS\WinPhoneRSS\App.xaml 774 9 WinPhoneRSS
when I remove this line, it works but without transitions for sure
u have any clue?
I just got the project working under the April CTP. At this point, I brute forced it by putting the TransitioningContentControl source directly into my project. I am working on a blog post / screencast to show how to get things working. I have a couple of other things I want to explore before I finish it up. Keep an eye here or on my blog - for details. Hopefully in the next day or so...
thx jeff, I will keep an eye on it.
You can see a quick fix to getting the TransitioningContentControl working with the April CTP here -
Hi Jeff, would either the "brute force" or TransitioningContentControl method for Page transitions be suitable for animating the transition between different orientations of the same Page? For example, fading out the portait view and fading in the landscape view when the phone is oriented into landscape mode?
Thanks!
I dont think TCC would do the trick. I took just a quick look, but an orientation change does not actually change the page content, so the TCC would not be invovled in at all. It would just behave "as normal". You would need to wire up the OnOrientationChanged event at the page level and control an animation from there I think. I want to say Peter Torr has a MIX10 video that shows him doing this.
Jeff, you were correct, Peter Torr does have a video covering this. For future reference, it is located here () at the 10:45 mark. Thanks again!
Jeff, one more question concerning TCC, now that I have gotten the AprilCTP workaround implemented and functioning properly within my test application (to do normal page to page transitions). I noticed it works perfectly in portrait orientation. However, when I switch the emulator to landscape and navigate to a different page, the current page is very briefly flashed onto the screen in portrait mode and then the correct animation takes place. This behavior is also noticeable in the demo you posted (to reproduce, note that I had to add landscape support to the Favorites.xaml page).
My guess is this is an artifact of how the TCC actually creates the Page transitions. As it was designed for desktop Silverlight implementations, it did not have to worry about portrait vs. landscape. Of course it could just be an emulator screen buffer issue. Do you have any further thoughts on this? I would feel very hesitant shipping an app if the emulator is a true reflection of how an application with TCC would appear on a device. Thanks!
Interesting. I hadnt really noticed it because I was always using the back button to navigate between pages when I was in landscape mode. Problem when you have a demo app that has TWO WHOLE pages.
I'm not sure what is going on. It appears to have
something to do with sliding content into the various content controls that make up the TCC and the phone having to figure out that the new content should be in landscape rather than portait. I would lean toward this being a bug in the phone but I have spent
about 5 minutes looking at it. I will try and dig deeper into it tomorrow.
UPDATE: Ok, this happens on pages with our without the TCC. I have sent an email to the dev team to see if this is by design, emulator issue, or bug.
Confirmed that the flicker is a known issue and entered as a bug.
Hi,
have you had the time to port this all over to the current Beta SDK? There were so many changes that this would help alot
Does it work in the Beta? I followed the video through with the beta, and I can't get it to work at all.
For those interested I spent 10 minutes converting it over - not much to change really. Anyway I've updated the project and you can find it on my bog:
Hope this helps out...
Hi dotNetProfessional, the link you have posted does not work, could you please give the good link for your zip file.
Thanks a lot!
Sorry about that! Seems I forgot to add the http bit so the Url became relative. I've just fixed it so hopefully it will work now
Hey Jeff,
Using the simple model you first describe (for a simple 2-page application) I was able to create a nice trasition from MainPage to Page 2. However, intercepting the back button in order to implement the transition in reverse has an unacceptable side-effect. The PhoneApplicationPage_BackKeyPress is used to intercept the navigation and allow the transition; however, the stack comes into play and we're caught in an endless loop between the MainPage and Page 2.
Is there any way to deactivate the application from code? Intercepting the back button on the MainPage and deactivating thte app, is in effect returning to the normal action that would result from the back button being pressed on the MainPage?
Alternatively, your second method looks appealing but the Silverlight 3 Toolkit is proving difficult to locate now that Silverlight 4 and the new Silverlight for WP7 are released. Can you provide a link to the older Silverlight 5 Toolkit you used in this video?
Thanks,
Greg
Here's how to do this with the latest Silverlight toolkit (November 2010)
Comments have been closed since this content was published more than 30 days ago, but if you'd like to send us feedback you can Contact Us. | https://channel9.msdn.com/Blogs/SlickThought/Simplify-Page-Transitions-in-Windows-Phone-7-Silverlight-Applications?format=html5 | CC-MAIN-2017-26 | refinedweb | 2,369 | 56.76 |
Now that you've installed cdktf, you will use it to deploy an AWS EC2 instance using TypeScript.
»Prerequisites
To follow this tutorial, you need the following installed locally:
- Terraform v0.12+
- cdktf
- Node.js v12.16+
- an AWS account and AWS Access Credentials
Terraform and the
cdktf tool will use credentials set in your environment or through other means as described in the Terraform documentation.
Add your AWS credentials as two environment variables,
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY, replacing
AAAAAA with each respective values.
$ export AWS_ACCESS_KEY_ID=AAAAAA $ export AWS_SECRET_ACCESS_KEY=AAAAA
»Initialize a project
Start by creating a directory for the project. Name it
typescript-aws.
$ mkdir typescript-aws && cd $_
Inside the directory, run
cdktf init with the TypeScript template. Use
--local to store Terraform's state file on your machine instead of remotely in Terraform Cloud.
$ cdktf init --template="typescript" --local
This will initialize a brand new CDK for Terraform project in TypeScript using an interactive command. Accept the defaults when prompted.
»Write TypeScript code
Open the
main.ts file to view your application code. The template creates a scaffold with no functionality.
import { Construct } from 'constructs' import { App, TerraformStack } from 'cdktf' class MyStack extends TerraformStack { constructor(scope: Construct, name: string) { super(scope, name) // define resources here } } const app = new App() new MyStack(app, 'hello-terraform') app.synth()
The scaffold pre-configures the configuration to use AWS. Run the
get command to install the relevant dependencies.
$ cdktf get
Now, write a configuration in TypeScript that uses the AWS provider to create a compute instance in the
us-west-1 region. Although it requires about 30 lines of code, most of the lines map to equivalents in HCL for traditional Terraform.
Copy the following code and paste it into
main.ts, replacing the existing code.', tags: { Name: 'TypeScript-Demo', fruit: 'blueberry', Address: '123 Main St', }, }) new TerraformOutput(this, 'public_ip', { value: instance.publicIp, }) } } const app = new App() new MyStack(app, 'typescript-aws') app.synth()
»Examine the code
Most of the code is similar to concepts you've seen. The core Terraform classes are in the
cdktf library and respond to IntelliSense if you are using Visual Studio Code. Start typing "Terraform" inside the curly braces and you'll see a list of available objects.
import { App, TerraformStack, TerraformOutput } from 'cdktf'
AWS resources must also be explicitly imported. In this case we need the top level
AwsProvider and the
Instance for our compute resource.
import { AwsProvider, Instance } from './.gen/providers/aws'
Speaking of which, the
AwsProvider can be configured by passing keys and values that map to Terraform arguments as listed in the provider API. In the snippet below we use the
region key to set the region to
us-west-1.
The Terraform API documentation uses snake case (lowercase with underscores) but TypeScript uses camel case (mixed lower and uppercase with no underscores). So a key such as
shared_credentials_file is
sharedCredentialsFile in TypeScript.
TIP: One way to discover all the classes and properties for a provider is to examine the
.gen/providers/aws directory. You'll find files such as
aws-provider.ts which list the exact class names and properties for each resource.
new AwsProvider(this, 'aws', { region: 'us-west-1', })
Next we define a compute instance with the
Instance class. For this you'll also use camel case for properties that correspond to the Terraform API.
A significant difference from HCL is the need to store the new instance in a variable, shown as
const instance here. We will use the instance attributes in an output later, so we must create a variable. In HCL, any resource can be accessed from any point in the configuration file, but in TypeScript you must use a variable if you want to access the resource elsewhere.
const instance = new Instance(this, 'compute', { ami: 'ami-01456a894f71116f2', instanceType: 't2.micro', tags: { Name: 'TypeScript-Demo', fruit: 'blueberry', Address: '123 Main St', }, })
The
instance variable is used in a
TerraformOutput. We want to know the
publicIp of the instance when it is created, and we might want to read this output value from another Terraform workspace.
When writing this code, you can use IntelliSense to view all the properties of the
instance variable. In this case,
publicIp the only one that is used.
new TerraformOutput(this, 'public_ip', { value: instance.publicIp, })
»Provision infrastructure
Now that you have initialized the project with the AWS provider and have written code to provision an instance, it's time to
deploy it.
$ cdktf deploy Deploying Stack: typescript-aws Resources ✔ AWS_INSTANCE compute Summary: 1 created, 0 updated, 0 destroyed. Output: typescriptaws_publicip_EEB4927B = 54.219.195.36
You will be prompted to confirm. After the instance is created, you'll see the output which displays the
publicIp we specified earlier (listed here with the full name of the project and the name of the output,
typescriptaws_publicip_EEB4927B).
»Destroy
In a full cycle development workflow, you would modify the code and run
deploy again to update your infrastructure as specified in the code.
For this tutorial, we're done with the compute instance, so you can run the
destroy command to de-provision it.
$ cdktf destroy Destroying Stack: typescript-aws Resources ✔ AWS_INSTANCE compute aws_instance.typescriptaws_compute_D9683B2F Summary: 1 destroyed.
You'll be prompted to confirm and a message will be displayed that shows it.
TypeScript. | https://learn.hashicorp.com/tutorials/terraform/cdktf-build?in=terraform/cdktf | CC-MAIN-2020-45 | refinedweb | 877 | 56.86 |
Message > Mark menu shouldn't be disabled when no messages are selected
RESOLVED FIXED in Thunderbird 5.0b1
Status
--
minor
People
(Reporter: squib, Assigned: squib)
Tracking
Firefox Tracking Flags
(Not tracked)
Details
Attachments
(1 attachment, 1 obsolete attachment)
On trunk, the Message > Mark menu is disabled if no messages are selected. Since some of the submenu items apply to an entire folder (As Read by Date and All Read), it should remain enabled.
Taking this, since I have a patch in the works.
Assignee: nobody → squibblyflabbetydoo
Status: NEW → ASSIGNED
Here's a fix for this. I also fixed an edge case in SelectedMessagesAreRead where it would return true when no messages are selected. This doesn't have any effect in Thunderbird though (but an addon might be affected). I'd write tests, but I'm sure they'd fail on Mac, since we can't actually open the Message menu via Mozmill there, and the context menu won't work, since it will always result in at least one selected message. I'm open to the idea of putting SelectedMessagesAreRead in gFolderDisplay, but maybe that should be part of another, more general bug to get rid of some of the global namespace pollution.
Attachment #529334 - Flags: review?(bugmail)
Comment on attachment 529334 [details] [diff] [review] Fix this Thanks for improving the clarity of the read parameter! The mac menu bar still has XUL widgets that exist; they just are bridged to the native stuff in the background. As such, if you tell a menu it is being displayed (and there are no dynamically created XBL bindings, although cloneNode is fine), you can still look at the XUL stuff and make sure it's okay. I concede I am unclear on what happens if you send synthetic events at our backing XUL widgets, however. In any event, I am not majorly concerned about regressions in this functionality, so I'll give the test a pass. However, please do migrate "isDummy" from being defined in messageWindow.js in the StandaloneMessageDisplayWidget constructor up onto the prototype of the MessageDisplayWidget since this code (and some already existing code) may access it outside of the standalone message window context. (Although the 'undefined' default will save us, from an error-checking perspective, it's nice to not be accessing nonexistent properties.)
Attachment #529334 - Flags: review?(bugmail) → review+
This should be a pretty uncontroversial change, but I just wanted to make sure this was the most appropriate spot to put isDummy before I checked this in. Thanks!
Attachment #529334 - Attachment is obsolete: true
Attachment #529536 - Flags: review?(bugmail)
Oh yeah: I had tried in bug 575732 to test the Message menu, but it was failing on Mac, so either I did something wrong, or Mozmill can't adequately control global menus on Mac. Either way, I have no idea how to fix it, since I don't have a Mac. :)
Checked in:
Status: ASSIGNED → RESOLVED
Closed: 8 years ago
Resolution: --- → FIXED
Target Milestone: --- → Thunderbird 3.3a4 | https://bugzilla.mozilla.org/show_bug.cgi?id=641253 | CC-MAIN-2019-30 | refinedweb | 499 | 59.74 |
clndr是什么
什么是clndr,A jQuery calendar plugin that uses HTML templates.
clndr介绍、clndr使用
<div class="clndr-previous-button">‹</div> <div class="month"><%= month %></div> <div class="clndr-next-button">›</div>
</div> <div class=“clndr-grid”> <div class=“days-of-the-week”> <% _.each(daysOfTheWeek, function (day) { %> <div class=“header-day”><%= day %></div> <% }); %> <div class=“days”> <% _.each(days, function (day) { %> <div class="<%= day.classes %>"><%= day.day %></div> <% }); %> </div> </div> </div>
The `days` array contains most of the stuff we need to make a calendar. Its structure looks like this: ```source-js { day: 5, events: [], classes: "day", date: moment("2015-12-31") }
This makes quick work of generating a grid.
days.classes contains extra classes depending on the circumstance: if a given day is today, ‘today’ will show up, as well as an ‘event’ class when an event lands on that day.
Pass In Your Events
CLNDR accepts events as an array of objects:
events = [ { date: "YYYY-MM-DD or some other ISO Date format", and: "anything else" } ]
CLNDR looks through the objects in your events array for a
date field unless you specify otherwise using the
dateParameter option. In your template the
days array will auto-magically contain these event objects in their entirety. See the examples for a demonstration of how events populate the
days array.
Usage
CLNDR leans on the awesome work done in Underscore and moment. These are requirements unless you are using a different rendering engine, in which case Underscore is not a requirement). Do be sure to include them in your
<head> before clndr.js. It is a jQuery plugin, so naturally you’ll need that as well.
The bare minimum (CLNDR includes a default template):
$('.parent-element').clndr();
With all of the available options:
$('.parent-element').clndr({ // The template: this could be stored in markup as a // <script type="text/template"></script> // or pulled in as a string template: clndrTemplate, // Determines which month to start with using either a date string or a // moment object. startWithMonth: "YYYY-MM-DD" or moment(), // Start the week off on Sunday (0), Monday (1), etc. Sunday is the default. // WARNING: if you are dealing with i18n and multiple languages, you // probably don't want this! See the "Internationalization" section below // for more. weekOffset: 0, // An array of day abbreviation labels. If you have moment.js set to a // different language, it will guess these for you! If for some reason that // doesn't work, use this... // WARNING: if you are dealing with i18n and multiple languages, you // probably don't want this! See the "Internationalization" section below // for more. daysOfTheWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], // The target classnames that CLNDR will look for to bind events. // these are the defaults. targets: { day: 'day', empty: 'empty', nextButton: 'clndr-next-button', todayButton: 'clndr-today-button', previousButton: 'clndr-previous-button', nextYearButton: 'clndr-next-year-button', previousYearButton: 'clndr-previous-year-button', }, // Custom classes to avoid styling issues. pass in only the classnames that // you wish to override. These are the defaults. classes: { past: "past", today: "today", event: "event", selected: "selected", inactive: "inactive", lastMonth: "last-month", nextMonth: "next-month", adjacentMonth: "adjacent-month", }, // Click callbacks! The keyword 'this' is set to the clndr instance in all // callbacks. clickEvents: { // Fired whenever a calendar box is clicked. Returns a 'target' object // containing the DOM element, any events, and the date as a moment.js // object. click: function (target) {...}, // Fired when a user goes to the current month and year. Returns a // moment.js object set to the correct month. today: function (month) {...}, // Fired when a user goes forward a month. Returns a moment.js object // set to the correct month. nextMonth: function (month) {...}, // Fired when a user goes back a month. Returns a moment.js object set // to the correct month. previousMonth: function (month) {...}, // Fires any time the month changes as a result of a click action. // Returns a moment.js object set to the correct month. onMonthChange: function (month) {...}, // Fired when the next year button is clicked. Returns a moment.js // object set to the correct month and year. nextYear: function (month) {...}, // Fired when the previous year button is clicked. Returns a moment.js // object set to the correct month and year. previousYear: function (month) {...}, // Fires any time the year changes as a result of a click action. If // onMonthChange is also set, it is fired BEFORE onYearChange. Returns // a moment.js object set to the correct month and year. onYearChange: function (month) {...}, // Fired when a user goes forward a period. Returns moment.js objects // for the updated start and end date. nextInterval: function (start, end) {...}, // Fired when a user goes back an interval. Returns moment.js objects for // the updated start and end date. previousInterval: function (start, end) {...}, // Fired whenever the time period changes as configured in lengthOfTime. // Returns moment.js objects for the updated start and end date. onIntervalChange: function (start, end) {...} }, // Use the 'touchstart' event instead of 'click' useTouchEvents: false, // This is called only once after clndr has been initialized and rendered. // use this to bind custom event handlers that don't need to be re-attached // every time the month changes (most event handlers fall in this category). // Hint: this.element refers to the parent element that holds the clndr, // and is a great place to attach handlers that don't get tossed out every // time the clndr is re-rendered. ready: function () { }, // A callback when the calendar is done rendering. This is a good place // to bind custom event handlers (also see the 'ready' option above). doneRendering: function () {...}, // An array of event objects events: [], // If you're supplying an events array, dateParameter points to the field // in your event object containing a date string. It's set to 'date' by // default. dateParameter: 'date', // CLNDR can accept events lasting more than one day! just pass in the // multiDayEvents option and specify what the start and end fields are // called within your event objects. See the example file for a working // instance of this. multiDayEvents: { endDate: 'endDate', startDate: 'startDate', // If you also have single day events with a different date field, // use the singleDay property and point it to the date field. singleDay: 'date' }, // Show the dates of days in months adjacent to the current month. Defaults // to true. showAdjacentMonths: true, // When days from adjacent months are clicked, switch the current month. // fires nextMonth/previousMonth/onMonthChange click callbacks. defaults to // false. adjacentDaysChangeMonth: false, // Always make the calendar six rows tall (42 days) so that every month has // a consistent height. defaults to 'false'. forceSixRows: null, // Set this to true, if you want the plugin to track the last clicked day. // If trackSelectedDate is true, "selected" class will always be applied // only to the most recently clicked date; otherwise - selectedDate will // not change. trackSelectedDate: false, // Set this, if you want a date to be "selected" (see classes.selected) // after plugin init. Defualts to null, no initially selected date. selectedDate: null, // Set this to true if you don't want `inactive` dates to be selectable. // This will only matter if you are using the `constraints` option. ignoreInactiveDaysInSelection: null, // CLNDR can render in any time interval! // You can specify if you want to render one or more months, or one ore more // days in the calendar, as well as the paging interval whenever forward or // back is triggered. If both months and days are null, CLNDR will default // to the standard monthly view. lengthOfTime: { // Set to an integer if you want to render one or more months, otherwise // leave this null months: null, // Set to an integer if you want to render one or more days, otherwise // leave this null. Setting this to 14 would render a 2-week calendar. days: null, // This is the amount of months or days that will move forward/back when // paging the calendar. With days=14 and interval=7, you would have a // 2-week calendar that pages forward and backward 1 week at a time. interval: 1 }, // Any other data variables you want access to in your template. This gets // passed into the template function.. The keyword 'this' is set to // the clndr instance in case you need access to any other properties. // More under 'Template Rendering Engine' below. render: function (data) { return '<div class="html data as a string"></div>'; }, // If you want to prevent the user from navigating the calendar outside // of a certain date range (e.g. if you are making a datepicker), specify // either the startDate, endDate, or both in the constraints option. You // can change these while the calendar is on the page... See documentation // below for more on this! constraints: { startDate: '2017-12-22', endDate: '2018-01-09' }, // Optionally, you can pass a Moment instance to use instead of the CLNDR settings. // If you use moment you shouldn't use weekOffset and daysOfTheWeek // See for more information moment: null });
All of the things you have access to in your template:
// An array of day-of-the-week abbreviations, shifted as requested using the // weekOffset parameter. daysOfTheWeek: ['S', 'M', 'T', etc...] // The number of 7-block calendar rows, in the event that you want to do some // looping with it numberOfRows: 5 // The days array, documented in more detail above days: [{ day, classes, id, events, date }] // The month name- don't forget that you can do things like // month.substring(0, 1) and month.toLowerCase() in your template month: "May" // The year that the calendar is currently focused on year: "2013" // All of the events happening this month. This will be empty of the // lengthOfTime config option is set. eventsThisMonth: [] // All of the events happening last month. This is only set if // showAdjacementMonths is true. eventsLastMonth: [] // All of the events happening next month. This is only set if // showAdjacementMonths is true. eventsNextMonth: [] // If you specified a custom lengthOfTime, you will have these instead. intervalEnd: (moment object) intervalStart: (moment object) eventsThisInterval: [] // Anything you passed into the 'extras' property when creating the clndr extras: {}
Multi-day Events
CLNDR accepts events lasting more than one day. You just need to tell it how to access the start and end dates of your events:
var lotsOfEvents = [ { end: '2013-11-08', start: '2013-11-04', title: 'Monday to Friday Event' }, { end: '2013-11-20', start: '2013-11-15', title: 'Another Long Event' } ]; $('#calendar').clndr({ events: lotsOfEvents, multiDayEvents: { endDate: 'end', startDate: 'start' } });
When looping through days in my template, ‘Monday to Friday Event’ will be passed to every single day between the start and end date. See index.html in the example folder for a demo of this feature.
Mixing Multi- and Single-day Events
If you also have single-day events mixed in with different date fields, as of clndr
v1.2.7 you can specify a third property of
multiDayEvents called
singleDay that refers to the date field for a single-day event.
var lotsOfMixedEvents = [ { end: '2015-11-08', start: '2015-11-04', title: 'Monday to Friday Event' }, { end: '2015-11-20', start: '2015-11-15', title: 'Another Long Event' }, { title: 'Birthday', date: '2015-07-16' } ]; $('#calendar').clndr({ events: lotsOfEvents, multiDayEvents: { endDate: 'end', singleDay: 'date', startDate: 'start' } });
Custom Classes
The classes that get added to a
day object automatically can be customized to avoid styling conflicts. The
classes option accepts
today,
event,
past,
lastMonth,
nextMonth,
adjacentMonth, and
inactive. Pass in only the classnames you wish to override and the rest will be set to their defaults.
In this example we create a
my- namespace for all of the classes:
clndr.customClasses = $('#custom-classes').clndr({ classes: { past: "my-past", today: "my-today", event: "my-event", inactive: "my-inactive", lastMonth: "my-last-month", nextMonth: "my-next-month", adjacentMonth: "my-adjacent-month" } });
To configure the
day,
empty, and next/previous/today/etc. button classes, use the
targets option documented in the usage section.
Constraints & Datepickers
If you are making a datepicker or you’d just like to prevent users from
nexting all the way to 2034 in your calendar, you can pass a
constraints option with
startDate,
endDate, or both specified:
$('#calendar').clndr({ constraints: { endDate: '2015-07-16', startDate: '2015-05-06' } });
Now your calendar’s next and previous buttons will only work within this date range. When they become disabled they will have the class ‘inactive’, which you can use to gray them out or add gif flames or whatever.
The days in your grid that are outside of the range will also have the
inactive class. This means that you will want to add a click callback and check for whether or not a day has the class
inactive. It will look like this:
$('#calendar').clndr({ constraints: { endDate: '2015-07-16', startDate: '2015-05-06' }, clickEvents: { click: function (target) { if (!$(target.element).hasClass('inactive')) { console.log('You picked a valid date!'); } else { console.log('That date is outside of the range.'); } } } });
The constraints can be updated at any time via
clndr.options.constraints. If you make a change, call
render() afterwards so that clndr can update your interface with the appropriate classes.
myCalendar.options.constraints.startDate = '1999-12-31'; myCalendar.render();
Make sure the
startDate comes before the
endDate!
Returning the Instance / Public API
It’s possible to save the clndr object in order to call it from JS later. There are functions to increment or set the month or year. You can also provide a new events array.
// Create a CLNDR and save the instance as myCalendar var myCalendar = $('#myCalendar').clndr(); // Go to the next month myCalendar.forward(); // Go to the previous month myCalendar.back(); // Set the month using a number from 0-11 or a month name myCalendar.setMonth(0); myCalendar.setMonth('February'); // Go to the next year myCalendar.nextYear(); // Go to the previous year myCalendar.previousYear(); // Set the year myCalendar.setYear(1997); // Go to today: myCalendar.today(); // Overwrite the extras. Note that this triggers a re-render of the calendar. myCalendar.setExtras(newExtras); // Change the events. Note that this triggers a re-render of the calendar. myCalendar.setEvents(newEventsArray); // Add events. Note that this triggers a re-render of the calendar. myCalendar.addEvents(additionalEventsArray); // Remove events. All events for which the passed in function returns true will // be removed from the calendar. Note that this triggers a re-render of the // calendar. myCalendar.removeEvents(function (event) { return event.id == idToRemove; }); // Destroy the clndr instance. This will empty the DOM node containing the // calendar. myCalendar.destroy();
If you are taking advantage of the
onMonthChange and
onYearChange callbacks, you might want them to fire whenver you call
setMonth,
setYear,
forward,
back, etc. Just pass in an object as an argument with
withCallbacks: true like this:
// Month will be set to February and then onMonthChange will be fired. myCalendar.setMonth("February", { withCallbacks: true }); // Month will increment and onMonthChange, and possibly onYearChange, will be // fired. myCalendar.next({ withCallbacks: true });
Template Requirements
CLNDR is structured so that you don’t really need anything in your template.
<% _.each(days, function (day) { %> <div class='<%= day.classes %>'><%= day.day %></div> <% }); %>
Currently CLNDR sets the class on a day to
'calendar-day-2013-05-30' and uses it to determine the date when a user clicks on it. Thus, click events will only work if
days.classes is included in your day element’s
class attribute as seen above.
Configuration
Template Rendering Engine
You can pass in a
render function as an option, for example:
var precompiledTemplate = myRenderingEngine.template($('#my-template').html()); $('#my-calendar').clndr({ render: function (data) { return precompiledTemplate(data); } });
Where the function must return the HTML result of the rendering operation. In this case you would precompile your template elsewhere in your code, since CLNDR only cares about your template if it’s going to use Underscore.
If you are using your own render method, Underscore is NOT a dependency of this plugin.
CLNDR has been tested successfully with doT.js, Hogan.js, Handlebars.js, Mustache.js, and Knockout.js. Please get in touch if you have success with other languages and they will be documented here.
Here’s an example using doT.js…
The markup:
<script id="dot-template" type="text/template"> <div class="clndr-controls"> <div class="clndr-previous-button">‹</div> <div class="month">{{= it.month }}</div> <div class="clndr-next-button">›</div> </div> <div class="clndr-grid"> <div class="days-of-the-week"> {{~it.daysOfTheWeek :day:index}} <div class="header-day">{{= day }}</div> {{~}} <div class="days"> {{~it.days :day:index}} <div class="{{= day.classes }}">{{= day.day }}</div> {{~}} </div> </div> </div> </script>
The Javascript:
var clndrTemplate = doT.template($('#dot-template').html()); $('#calendar').clndr({ render: function (data) { return clndrTemplate(data); } });
Here’s an example using Mustache.js…
The markup:
<script type="x-tmpl-mustache" id="calendar-tmpl"> <div class="controls"> <span class="clndr-previous-button">prev</span> <span class="month">{{month}}</span> <span class="year">{{year}}</span> <span class="clndr-next-button">next</span> </div> <div class="days-container"> <div class="days"> <div class="headers"> {{#daysOfTheWeek}} <div class="day-header">{{.}}</div> {{/daysOfTheWeek}} </div> {{#days}} <div class="{{classes}}" id="{{id}}">{{day}}</div> {{/days}} </div> </div> </script>
The Javascript:
$('#calendar').clndr({ render: function (data) { return Mustache.render($('#calendar-tmpl').html(), data); }, });
Internationalization
CLNDR has support for internationalization insofar as Moment.js supports it. By configuring your Moment.js instance to a different language, which you can read more about here: i18n in Moment.js, you are configuring CLNDR as well.
If you would prefer to pass in a pre-configured instance of moment, you can do this by passing it in as the
moment config option when initializing CLNDR:
// To change clndr to German use moment.local('de') moment.locale('de'); // Make sure that your locale is Working correctly console.log(moment().calendar()) // Returns "heute um 18:43 Uhr" $('#calendar').clndr({ // Pass the moment instance to use your language settings moment: moment });
If you are using a moment.js language configuration in which weeks begin on a Monday (e.g. French), CLNDR will detect this automatically and there is no need to provide a
weekOffset or a
daysOfTheWeek array. If you want to reverse this behavior, there is a field in each moment.js language config file called
dow which you can set to your liking.
The day of the week abbreviations are created automatically using moment.js’s current language setting, however if this does not suit your needs you should override them using the
daysOfTheWeek option. Make sure the array you provide begins on the same day of the week as your current language setting. Warning: using
daysOfTheWeek and
weekOffset in conjunction with different language settings is not recommended and may cause you headaches.
Underscore Template Delimiters
If you’re not a fan of
<% %> and
<%= %> style delimiters you can provide Underscore.js with alternatives in the form of regular expressions. There are three delimiters…
interpolate, which outputs a string (this is
<%= %> by default)
escape, for escaping HTML (this is
<%- %> by default)
evaluate, for evaluating javascript (this is
<% %> by default)
If you’re more comfortable with Jinja2/Twig/Nunjucks style delimiters, simply call this before you instantiate your clndr:
// Switch to Jinja2/Twig/Nunjucks-style delimiters _.templateSettings = { escape: /\{\{\-(.+?)\}\}/g, evaluate: /\{\%(.+?)\%\}/g, interpolate: /\{\{(.+?)\}\}/g, };
Internet Explorer Issues
If you’re planning on supporting IE8 and below, you’ll have to be careful about version dependencies. You’ll need the jQuery 1.10.x branch for IE support, and if you’re taking advantage of the
constraints feature you’ll need to use a version of moment.js `: | https://www.javascriptcn.com/read-34034.html | CC-MAIN-2019-04 | refinedweb | 3,217 | 58.48 |
C++ meta programming.
I've been using C++ for a long time now. Ok say 10 years. I have to say I am not comfortable with where the community is going with meta programming. My colleagues have really taken an interest in it, but to me a lot of it is really to show mental prowess or something, not to write better code.
The game to me seems to take these obscure language constructs and bend them in a way that their creators never intended to get a completely different effect. Often the syntax is very strange.
My biggest gripe is that I feel things that could be handled in a clean, dynamic mechanism all of a sudden take on the arcane properties. The code becomes unreadable, yet this done in the name of "libraries." Right once, use many times. Well I found that the libraries are harder to implement and use, which really negates their benefit.
Concept checking is my biggest pet peave. Unlike interfaces the compiler doesn't enforce concepts. This is horribly bad and results in compiler errors that seem to have nothing to do with the code you are writing.
Does anyone know of a document that argues from both sides in a knowledgable manner? My side has no support around here.
christopher baus ()
Wednesday, November 12, 2003
I agree with you 100% about many people taking this stuff too far. I've run into far too many programmers with a brand new copy of "Modern C++ Design" on their bookshelf who are just itching to apply meta-programming to SOMETHING so they go and use it all over the place, in instances where a simple straightforward solution would work better in terms of being more easily understood by a wider variety of programmers and less likely to trip up compiler bugs due to using obscure C++ features.
Mister Fancypants
Wednesday, November 12, 2003
I agree with you 100%. Template metaprogramming is an interesting exercise (and IMO has not been proven to be anything more than that), but I don't think it belongs in a business codebase.
Trying to program like that rather than toward the average programmer just shows selfishness. Someone who stumbles upon such code 5 years later is going to be pissed...
Also, it basically sounds like a way to make your build times enormous. You can do anything you can with templates with runtime operations, and to insist on doing everything at compile time is premature optimization. Sure you get extra type-checking, but I think this is outweighed by all the obscure error messages.
Roose
Wednesday, November 12, 2003
I have to add my agreement to this!
In coding for the Symbian platform (a platform written entirely in C++) I've come to appreciate their minimal but effective use of C++. For example, they use templates to add type-safety to container classes. The template classes to not contain any code; they inherit from a base class which provides the storage. You get all the advantages of template type-safety without the code bloat (and strange errors) that come from using them.
I don't have any problem with meta-programming in general -- it can be very handy. But not in C++ w/ templates; it creates more of a mess than it solves.
Almost Anonymous
Wednesday, November 12, 2003
templates are one thing. the crap you see in Modern C++ design is a whole different ballgame.
Wednesday, November 12, 2003
I guess one person's garbage is another person treasure. I don't think Alexandrescu's work is crap. Far from it. But I do think it is Academic, and would be better served by a language that was meant to support meta programming from the start.
What really bothers me is defining "concepts" where interfaces (pure abstract classes in C++) would suffice.
for instance:
template <typename foo>
class bar
{
void reallyCuttingEdgeOperation()
{
_foo. doIt();
}
foo _foo;
}
What I hate about this is that foo can only be of a type that supports the doIt() "concept", but that concept is implicit. It is not documented anywhere in the code other than the fact that a member called reallyCuttingEdgeOperation() calls it.
Now when a client creates a class type to pass to type template argument foo that doesn't implement the doIt() concept, the end up with an error in bar and not in their own code.
This sucks and reduces productivity and doesn't increase it.
christopher baus ()
Wednesday, November 12, 2003
C++ Metaprogramming is an interesting hack, but a horrible practice. In all cases I've seen it applied in real life, it was the wrong tool for the job.
They result in undebuggable code, incomprehensible error messages, punchcard-like compile times, and various other illnesses.
You need metaprogramming? Use a language that does it natively, like Forth or the various Lisps (Use Dylan or Pliant if you dislike the parentheses - but it really _is_ easy to get used to them if you just try).
You need code generation? Use the right tool for your job (Lex; Yacc; Lemon; D'Parser or friends for parsing; Libero for state machines; Swig for wrappers; ....). Or write your own code generator in a language that makes it easy, e.g., Perl or Python.
No, none of these solutions easily replaces Blitz. That does not necessarily mean metaprogramming is the right solution - it probably means that the right tool has not yet been made. In one project, I dropped Blitz in favor of plain-old C, because a rebuild took several hours, and an incremental build often took several minutes. With plain-old C, the compile times are seconds/incremental, and minutes for a complete rebuild.
Ori Berger
Wednesday, November 12, 2003
I have a wierd feeling that the C++ community might be the cause of the language's own demise. In comp.lang.C++.moderated you will practically get booed off the board if you question the powerful group think. Yet in my opinion the what the group is thinking isn't useful to the average programmer.
repeat after me.
STL algorithmns good.
for loops bad.
boost tuple good.
abstract base classes bad.
boost any good.
void* heresy.
and so on.
That's an excellent argument against STL algorithmns, boost tuple, and boost any.
K
Wednesday, November 12, 2003
Chris,
I am SO with you there bro.
Modern C++ programming techniques have totally gone to shit. Code is absolute crap with all this metaprogramming BS. And the people who do it have elevated it to the level of some sort of cult or fringe religion. it's amazing you have to look for an article arguing both sides -- it's self evident that poor programmers use these techniques and the results are DISASTER.
Dennis Atkins
Wednesday, November 12, 2003
propellerheads' reason makes heavy use of template metaprogramming in C++, and their app is tight. so , it might have its place.
wormser
Wednesday, November 12, 2003
I agree 200% with everyone. Every time I look at the discussions on comp.lang.c++.moderated, which I do less and less frequently, they seem to be devoted to finding ever more insanely complicated ways of doing the simplest of things. And if you really want to give yourself apoplexy, take a look at the Boost Lambda library. But what would I know. I still write my loops starting with
for (int i = 0; i < n; i++)
whereas advanced practioners now consider it "better" to write:
for (int i(0); i != n; ++i)
There is only one side to this question. Your colleagues are all mad. Ignore them.
as
Wednesday, November 12, 2003
I'm pretty surprised about this backlash. I'll agree that metaprogramming can be taken way too far (and I've seen that in real-world practice) but, like any other tool, when used properly, it has its place.
In response to Christopher, many times an abstract base class is the right tool for the job, but not always.
Here's an example. We've created a "serializable" concept, which is simply a set of three methods which can be used to flatten objects to a byte stream, or restore an object's state from a byte stream. This parallels Python's "Pickle" concept, and has the obvious useful applications (send any object across the network, write any objet to file, etc.)
One great advantage of a serializable concept over a serializable interface is that we can add the concept to all of our old classes. Because the functions are non-virtual, adding them to old classes does not change the bit pattern, and the classes remain binary compatible. Sometimes we pass these classes in interfaces or store them in cross-process shared memory, so this is unacceptable. Adding support for "ISerializable" would create virtual tables on our old classes, causing all sorts of fun explosions.
Greg Falcon
Wednesday, November 12, 2003
Yeah but Marcus, you're a genius. That's a different issue. If you leave the project, it's all fall apart.
Reason fan
Wednesday, November 12, 2003
The for loop -- the first is more complicated, as it raises two questions.
Firstly, why do you use postfix ++ when you don't use the result? Oh sure, the generated code is the same as prefix ++... but there's a result! Why aren't you using it? Was it a typo?
Secondly, why do you say "<"... I take it you expect the loop to perhaps terminate with i being n+1, say? But the loop won't do this on its own. I'd say changing the index variable in a for loop is bad practice, and you should use a while() instead. (Or are you just looping while i doesn't equal n? :)
Insert half smiley here.
Wednesday, November 12, 2003
I'm going go out on limb here and say STL Algorithmns are a complete failure in practice. With out something like Java's lamda classes, err anonymous inner classes, you lose locality of the code. I don't want to read code like:
std::for_each(begin, end, doit);
where do it is in another part of the file.
Amen to that brother Christopher! Hallelujah! Preach it!
Greg...
Hmm worrying about the binary representation of classes has been pretty low on my list of requirements. If that was a requirement, I'd probably use good old structs without any member functions.
I'd then define serialize functions globally. Or at least global to the namespace. But that namespace lookup thing... How does that go again?
With regard to loops, I prefer the first form because it's transparently correct, and was the idiomatic way to write a loop over a fixed number of elements until a bunch of wankers with way too much time on their hands decided they could improve on it.
Christopher, I'm totally with you on for_each abuse, but wouldn't go all the way in writing off STL algorithms. I use sort and the various flavours of find a good deal.
Locality of the Code.
Locality of the Code.
Locality of the Code.
Yes... Locality of the Code is a good thing.
Locality, pshaw. (I feel strongly about this.) Names names names! You don't need locality if you have a good name.
You don't inline "fopen", do you? :)
Whoops... "fopen" is a crap name. Pretend it's "GetSystemTime", or something.
>...Libero for state machines;
Arrrgh. Libero is truely craptacular.
Clutch Cargo
Wednesday, November 12, 2003
STL algorithms a failure? Just because they're not as elegant (C++ was never an elegant language) as other systems doesn't invalidate their utility.
Just adapt them to your needs. Most uses of for_each I use for calling a member function, so I wrote a quick adapter to make it fit easier.
Admittedly, there are areas where I'd love some extension, but it's so damn adaptable that I can extend it myself pretty easily.
And for Alexandrescu's book, it's a great intro of where the langauge can go. The current syntax is pretty obtuse (never designed for these uses), but the potential for moving some of the work currently done at runtime to compile time is huge. Current uses for it are limited, but still useful.
Like everything else in C++, like templates, operator overloading, and multiple inheritance, it's up to the programmer to find the right uses.
H. Lally Singh
Wednesday, November 12, 2003
Sometimes I wonder what makes good engineers so damn resistent to change. I think it's the very fact that they are so good at what they do: not only they don't have incentive to learn something new but they don't even want to.
I mean, come on: Joel doesn't like exceptions, you guys hate templates, etc.
Hey, I've got an idea: let's all write in C again!
Ten years ago I was running around preaching OOP to engineers writing C in C++.
Today I run around preaching meta programming to people like you who write C++ from 10 years ago in today's products.
Hello, 2003 calling: the world has evolved!
Why templates and metaprogramming? Well, let's count the reasons.
Compare auto_ptr to new: I haven't had a memory leak in years.
Compare WTL to MFC. Nuff said.
With Loki's Select I was able to have a single code base for 10 different high-performance hashed containers.
In the end, it's productivity: I was able to write a complete 55kloc product in just a few months. Modular, documented and blazing fast.
Learning is hard, guys. That's why you're loosing your job to outsourcing to India.
Nick
Thursday, November 13, 2003
As I program more C++ I use more templates and more STL, as I do so my code gets shorter, more readable, more reliable and more elegant.
Yes, C++ has flaws which result in some ugly syntax (ptr_fun, mem_fun and mem_fun_ref, anyone?), and most compilers report template error messages very badly (but a half decent programmer can learn to read the messages pretty quickly). But there is no denying for_each, transform and the like provide a richer and hence more meaningful syntax than just using for loops for anything.
Mr Jack
Thursday, November 13, 2003
I sort of agree with Nick here -- I've just spent a year working with "C++" developers who are still chasing memory leaks. You start talking about reference counted smart pointers and they have no idea. It's all just too complex.
So they carry on chasing memory leaks instead of writing sensible code.
On the other hand, and I'm guilty of this sometimes, the C++ world does have people who wander around trying to find problems that need their esoteric templating stuff. It's a sort of game: like doing crosswords or something. You just shouldn't let it get in the way of working...
It's a matter of perspective. Metaprogramming isn't a bad thing, it's just some people can let ANYTHING get out of control.
Katie Lucas
Thursday, November 13, 2003
Nick,
The world has moved on, but not necessarily for the better.
The fact that something was introduced, and even became popular, is definitely no indication that it is any good, or even that it does no harm.
First, there was spaghetti code. Then came structured programming, and within 10 years, new code was relatively structured.
Then came Object Oriented design. At first, it was great, because everyone who started using it had a good grasp of structured procedural code; And they were early adopters, so they were actually weighing benefits and costs.
And then the masses came. And now we have class spaghetti, with no end in sight. Unfortunately, there is no modern day Dijkstra + Boare combination to make an effect with a "goto considered harmful" statement - it's all about marketing, and not about merit (It always is, when there's enough money running around; But it _wasn't_ that way 20 years ago, and it wasn't that bad 10 years ago).
Actually, Dijkstra did say that "Object Oriented Programming is an exceptionally bad idea that could only have originated in California". But it really made no effect (and, truth be told, Simula is credited with being the first OO programming language, and it was developed in Europe).
C++ gives you a lot more rope to hang yourself with than C (and perhaps every other language) ever did. When used by informed professionals, it's a good thing. Unfortunately, it is used by programmers.
Ori Berger
Thursday, November 13, 2003
Oh, and just to be clear, I don't claim Object Oriented programming is a bad idea. Or a good idea. You have to define Object Oriented programming before you can meaningfully discuss it, and since there are many definitions, some compatible with each other, and some incompatible. Everyone tends to believe that their definition (which they usually fail to make explicit or well defined) is "the one true way".
s/Object Oriented programming/god/g , BTW - it's a religious discussion. Define what OO means to you if you want a constructive discussion - e.g., use [ ] to characterize which of the 512 options is your OO. And even _that_ does not make it really well defined, it's a start.
And, a question - has any of you who like metaprogramming ever tried doing it in Lisp (or Scheme or Dylan or Pliant)? If so, please share your experience. Mine is that, C++ metaprogramming is like using a pen to write each one of 20 copies of the paper. Eventually, you get where you want; You work hard to get there, which tends to leave you sentimentally attached. You may even have a philosophy about why it's the right thing to do.
When I have work to do, however, I prefer a photocopier.
Ori, I agree with you.
I am on the pragmatic side and I don't much care about religious issues.
For me, metaprogramming is simply a code generator. It saves me from typing/cut and pasting the same code in multiple places while preserving the performance and typesafety I would loose by using dynamic oop techniques.
And c++ is the only language today that gives me that, together with a wealth of libs, modern guis, static typing and performance.
But yes, c++ is HARD. Most of the programs pick a subset they know and stick with it, thus the "what's this new templates/exceptions crap" posts. Other languages are easier to use, have better syntax, but they often got that in exchange for libs, size and performance.
However, I have a bit more have faith in programmers. I think they CAN learn. They don't want to, but they can.
And I doubt there is much marketing when it comes to c++. Java and C# are marketing. C++ always struck me as the pragmatic's choice.
"Learning is hard, guys. That's why you're loosing your job to outsourcing to India. "
Oh. We're losing our jobs because Indians learn better than Americans.
And here I thought it was because they are cheaper.
You really are a genius, aren't you?
Thursday, November 13, 2003
Cheaper at doing the exact same things that you do, yes. Learn a new skill, improve yourself as a programmer, and you may be worth the price difference.
I should know, since I currently employ both offshore code monkeys and highly paid programmers. The latter write general abstractions, data structures, high performance protocols. The former do UIs like maniacs.
Work smarter, not harder.
The STL is great in small doses. Templates are powerful. But I believe that the real reason C++ will never be accepted as a functional programming language is because the syntax stinks. It's absolutely abysmal. Really, almost everything that got added to C++ that wasn't in C has embarassingly bad syntax.
Getting back to the for_each discussion... just compare the following:
for (int i=0; i<v.size(); ++i)
v[i]+=42;
std::for_each(v.begin(), v.end(), std::bind1st(std::plus<int>, 42));
...riiiiiight. Which is the guy at the next desk more likely to understand on the first read? Just because template-based programming has its place, doesn't mean that it should be used everywhere. And as bad as this example is... the more complicated your loop code gets, the more unreadable the STL algorithm equivilent is. (And someone else already said this, but pulling out the loop body into a function 200 lines down in the code is NOT a solution.)
I've worked with people who loved STL algorithms so much that they really write loops like this. I dread every time I hit this kind of code. This goes back to Christopher Baus' point at the very start of this thread, and Roose's followup. The primary goal of professional programming is not to have fun, to form little puzzles for yourself. Your goal is to write solid, maintainable code. And maintainability requires readability.
But, conceding this, template programming certainly has its place. The ability to get a std::vector of your Foo objects, or a std::map mapping your Foo objects to your Bar objects, is not some arcane C++ library magic. Instead, it's the tip of the iceberg of the power of generic programming.
Though template syntax is bad, sometimes it's not so much so. For instance, our "serializable" concept I mentioned before. If I see foo.serializeSize(), bar.serializeSize(), or baz.serializeSize(), I know what the code means even if I've never seen foo's, bar's, or baz's type before. If I have a function templatized on its input parameter t of type T, when I see t.serializeSize() in that code, I know immediately what's going on.
I concede you get the same readability if you implement "serializability" with an interface instead of a concept, but you lose some real power. With templates, I can write a functions that serialize and deserialize ANY vector of ANY class that models the serializable concept. You simply couldn't do that with the interface paradigm. Sure, you could write a function that serialized an array of ISerializable*, but do you really want to store your objects like that? (And managing the lifespan of pointers is even harder and more error prone if you don't avail yourself of smart pointer templates. :-)
Generic programming really shines when you can combine two or more concepts like this and get something really powerful out of the other end. "Sequence" is a standard library concept and "serializable" is ours, yet they plug right together, and make a really simple, powerful, readable function.
It's all a game of cost/benefit analysis. Sometimes the benefits outweigh the hassle of dealing with a clumsy syntax and inept C++ compilers and debuggers. I love this quote from the C++ Faq Lite: "Software Development Is Decision Making".
Greg Falcon
Thursday, November 13, 2003
"Hey, I've got an idea: let's all write in C again!"
Yes, I agree.
Dennis Atkins
Thursday, November 13, 2003
Why stop there? In the good old days, they used Cobol. All this newfangled C stuff is unnecessarily complex.
I'll agree to using C again.
We can even use a garbage collector if you're so concerned with memory leaks.
Thursday, November 13, 2003
Complexity is the enemy.
Let me say that again -- complexity is the enemy.
Cobol bad.
C not perfect, but it appears that it was the sweet spot.
C is in many aspects more complex than C++. Memory and pointer management, for example, are significantly more dificult than using auto_ptr and vector's.
Well there are plenty of generic libraries for C to give you vectors and hashes and what all else that work just fine.
True on the auto_ptr, that's 1 point there.
The complexity in C++ is greater than the complexity in C.
C# on the other hand, I'd say is less complex than either.
And Python is mighty fine indeed.
What a bunch of reactionaries!
new == bad
academic == bad
Let's all go back to struct( void* method;}; in C -- better yet, let's all start using Fortran again because programming is getting too complicated!...
If you dont like the moderated C++ newsgroup - don't read it...
If you dont approve of your colleague or architect's use of metaprogramming, find and justify a better way of solving the problem -- and if that doesn't work, find a new job -- carpentry hasn't changed much over the centuries. Perhaps there is a place for you in that profession.
Bottom line is that choosing the right tool/methodology for the job is often the most difficult step in software development. There was the same backlash against object-oriented programming 10 years ago, and I am sure that in 10 years time there will be a new methodology to bash.
Malcolm O'Callaghan
Thursday, November 13, 2003
I agree with Dennis but I do think auto_ptr<> is a great thing.
The problem is not with meta programming or generics but rather the C++ implementation of these concepts. Templates are a huge mess. Debugging compile time errors with templates can be a nightmare -- if I screw up, I often a compile error in some stl.h file rather in my code. And not just one error, I've gotten over a 1000 errors which can be fixed by changing one line of code -- like what the hell! This is not a good thing.
You might think I'm backwards for not trusting templates -- but once bitten twice shy. Use them were appropriate but don't over use them.
Almost Anonymous
Thursday, November 13, 2003
Yeah let me clarify -- I understand this discussion to be about 'template metaprogramming' in C++ and its offshoots, which seem to produce fully and unnecessarily obfuscated code such as the few examples given.
Traditional Metaprogramming, such as the use of code generators like flex and bison, and many other uses, is very often a fantastic and useful approach that *reduces* maintenence nightmares instead of makes them worse.
Absurd use of the C++ template mechanism is no different than absurd use of the C preprocessor to make your C look like LISP or FORTRAN or BASIC -- a bad idea all around.
Complexity is the enemy.
Template metaprogramming is very useful for library authors. Boost is example of such library.
"Normal" C++ programmers should not use it, unless they acquired this arcane knowledge.
Just because it is fancied on c.l.c++.m doesn't mean everone needs to jump it.
Pavel
Thursday, November 13, 2003
I would argue that at some level all senior developers are library writers. If your code is going to be used by others, ie you are publishing an interface to others on your team, you are a library writer.
christopher baus ()
Thursday, November 13, 2003
Do Boost and STL really use metaprogramming? I don't think they really do in the sense that you will see in "Modern C++ Design." -- e.g. creating lists of types like
< T1, < T2, < T3, <T4, < terminator> > > >
or whatever it is.
Some of you arguing for template metaprogramming may be arguing against the wrong thing. I like abstraction. I like templates. I like Lisp style meta programming. I don't like C++ meta programming.
Roose
Thursday, November 13, 2003
I don't think STL does any metaprogramming in the Lisp sense of the word, but Blitz certainly does: e.g., it turns a vector expression of the form "a = b + 0.5*c + d/2" into something equivalent to
for (i = 0; i < n; ++i)
. a[i] = b[i] + 0.5*c[i] + d[i]/2;
possibly unrolling the loop entirely if n is known at compile time. It does this by generating a class like
Op<assign,vector,Op<add,Op<add,Op<multiply,0.5,vector>, ..........> that mirrors the parse tree.
boost does use a lot of meta programming concepts. Such as tuple for instance which is really Alexandrescu's typelist.
christopher baus ()
Friday, November 14, 2003
Or the lambda library... You can barely tell what language you are using when you program for it.
cccccccccc
cccccccccccccc
Sunday, April 25, 2004
"Software Development Is Decision Making", I could not said it better. some years ago some guy implanted a very strange thing called OOP in C and then was born C++. It was akward, people said it was not a good thing, some loved, some hated, the language evolved and here we are everyone of us use C++ features, not available in plain C, to some extend.
There are lots of programming languages around that aims that every program in that language will be a good program (java, c#, ...).
C++ it´s not like this. C++ it´s about doing things that cannot be done anywhere else, it´s about trying new things, experimenting with new tecniques, and still being able to write good, solid, comercial quality programs, but that, in C++, is a programmers choice.
That´s why C++ it´s called multi-paradigm language, it is not suposed to be the least commom denominator, but to allow everything and let programmers decide what is good, bad or ugly.
Consider this, how many of you use goto´s? No more than a dozen I supose, and it is there if anyone needs it. Multiple inheritance? it´s there, don´t like it, don´t use it, but if you need it, it´s there.
That´s all about template metaprogramming, it´s new, it´s not possible in other languages, and it can be usefull in some places, it´s not the right tool for every job, but is THE right tool for some jobs. So it´s there, use it, don´t use it, give it a try, love it, hate it, but understand that ten years from now we will all be using the best pratices in template metaprogramming; the syntax, the estructure, and everything else will be evolved, and it will be comfortably for most of us; java, C# and any other "good code only" language will suport it, and cutting edge C++ programmers will be using "Quantum Telephatic Oriented Meta-metaProgramming" trying to find better solutions for old and new problems.
It´s not about avoiding complexity, it will sooner or later catch you, it´s about managing it.
Sérgio Vale e Pace
Wednesday, May 26, 2004
If You don't like metaprogramming: don't do it!
If You don't understand it: don't argue (flame) against it !
Maybe You should try java instead of c++ ;-)
Martin P.
Friday, June 18, 2004
Recent Topics
Fog Creek Home | http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=85900 | CC-MAIN-2017-17 | refinedweb | 5,148 | 73.88 |
On Sun, 2012-04-15 at 18:09 +0100, sebb wrote:
> On 15 April 2012 17:55, Oleg Kalnichevski <olegk@apache.org> wrote:
> > On Sun, 2012-04-15 at 16:38 +0100, sebb wrote:
> >> On 15 April 2012 13:29, Oleg Kalnichevski <olegk@apache.org> wrote:
> >> > Folks
> >> >
> >> > It is not a big secret that Google decided to continue shipping the
> >> > extremely outdated pre-BETA version of HttpClient instead of upgrading
> >> > to a newer version and to steer Android users toward HttpUrlConnection
> >> > API. I understand they must have their good reasons. At the same, those
> >> > people who may not share Google's enthusiasm about having to migrate to
> >> > HttpUrlConnection are left with no viable upgrade options as stock
> >> > versions of HttpClient cannot be used in Android. A very common
> >> > work-around to this problem is to move HttpClient code to a different
> >> > namespace in order to avoid classloader conflicts with Android code.
> >> > This can be done either using Maven Shade plugin or a script such as one
> >> > developed by Dirk Boye [1]. The downside of this work-around is that the
> >> > shaded HttpClient cannot be used with 3rd party libraries such as Spring
> >> > compiled against the standard API.
> >> >
> >> > A better approach might be to 'shade' only implementation classes only
> >> > and compile them against the API interfaces and classes shipped with
> >> > Android. This could produce a reasonably up to date version of
> >> > HttpClient which at the same time can be used as a drop-in replacement
> >> > for the outdated Android version.
> >>
> >> I'm not clear what exactly you are proposing to release.
> >>
> >
> > HttpClient 4.1.3 code sans API interfaces and classes moved to
> > 'org.apache.hc.android' namespace or similar.
>
> So the jar would only contain classes in its own package namespace?
> That would certainly avoid classpath issues and Maven coords.
>
> But I don't see how applications would pick up the different implementation.
>
It will not happen automatically but at least one can still create an
instance of DefaultHttpClient from the
'org.apache.hc.android.impl.client' package instead of
'org.apache.http.impl.client' and pass it as a dependency to any
external library that expects an instance of
'org.apache.http.client.HttpClient'.
This may sound like a small thing but this is actually impossible when
HttpClient code is 'shaded' to a new namespace wholesale along with all
API interfaces.
Oleg
> >
> >> > What I would like to do is to take HttpClient 4.1.3 release tag and
> >> > create an Android compatible re-spin with a distinct Maven artifact from
> >> > that tag.
> >>
> >> Maven relies on the artifactId (and groupId, i.e. the coordinates) to
> >> know how to build the dependency path.
> >> So it's important to know what packages the proposed jars will contain.
> >> And it's important not to mislead Maven by supplying incorrect coordinates.
> >>
> >> Otherwise, Maven could combine incompatible jars on the same classpath
> >> - with all the problems that can bring.
> >>
> >
> > I am thinking about creating a copy of HttpClient 4.1.3 in SVN rather
> > than trying to repackage existing binary artifacts in some clever way.
> > This would enable us to selectively apply changes made by Google to
> > their version of HttpClient for better compatibility.
> >
> >> > If you think this is not a good idea please raise your concerns now. If
> >> > I hear no objections, I'll proceed with the development of HttpClient
> >> > version for Android and will call a release vote when ready.
> >>
> >> Luckily it should be quite easy to test the behaviour on Android.
> >> I've been playing with Eclipse and the ADT recently, so can provide
> >> some feedback on that aspect.
> >>
> >
> > That'd be awesome.
> >
> > | http://mail-archives.apache.org/mod_mbox/hc-dev/201204.mbox/%3C1334510761.10753.33.camel@ubuntu%3E | CC-MAIN-2017-34 | refinedweb | 601 | 63.9 |
When learning Android development, it’s imperative that you learn how to implement the basic UI controls. One of the most common practices in any mobile platform is to take a collection of data and display it in a list. In the Android ecosystem, we can get this done with a component called a ListView.
Step One – Create Empty Activity
Open Android Studio and then create an Empty Activity.
New Android Project
At its basic level, an activity controls what’s going on in the current screen and what content is placed on that screen.
Step Two – Create the XML Layout
The presentation portion of you listview is created using an XML layout. These are stored in the layout directory under res
android layout folder
When you open the file activity_main.xml file, you’ll see either the default XML or the Designer.
xml layout android
Android Designer View
Erase the TextView XML and replace it with a ListView
<TextView android:
<ListView android: </ListView>
Inside of the ListView, you’ll see that we have a property called
android:id. This property will allow for us to select this control later on from our Java activity file.
Step Three -Part 2
Next we want to create the XML for each individual element. These are the cells that will show up for each item in our ListView.
Create an XML layout file with a
TextView. I named mine
activity_listview.xml
<TextView xmlns: </TextView>
Step Three – Adding and Array Adapter
As we move over to out MainActivty file, you’ll see that we have an
OnCreate method. This method is called once the Activity is created. In order to display out ListView, first, we are going to need some data. Right above the
OnCreate method, create an array of
String. This can contain anything that you want.
languageArray = {"Spanish","Italian","French","German","Russian","English","Portuguese","Japanese"};
Now, inside of the
OnCreate method, we are going to create what is called an
ArrayAdapter. This takes the context of the activity, the layout that we want to display for each item and the array of items.
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, languageArray);
We then get this
ListView by the id that we gave it in our layout file.
ListView listView = (ListView) findViewById(R.id.mobile_list);
After that, we call the method on our
setAdapter. This passes our adapter into the ListView and allows for it to be displayed to the user.
listView.setAdapter(adapter);
The finished Activity file should look like this.
public class MainActivity extends AppCompatActivity { // Array of strings... String[] languageArray = {"Spanish","Italian","French","German","Russian","English","Portuguese","Japanese"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, languageArray); ListView listView = (ListView) findViewById(R.id.mobile_list); listView.setAdapter(adapter); } }
We can now build the application and our array of items should be displayed.
Android Emulator ListView | https://codebrains.io/5-minute-snippets-how-to-build-an-android-listview/ | CC-MAIN-2019-51 | refinedweb | 489 | 57.87 |
Opened 6 years ago
Closed 5 years ago
#16572 closed Bug (fixed)
select_related doesn't work (silent/masked TypeError) over multiple one-to-one relationships
Description
Given this models.py:
from django.db import models class A(models.Model): pass class B(A): pass class C(B): pass
The following select_related call returns an apparently empty queryset:
>>> A.objects.select_related('b__c') []
Digging a little deeper:
>>> A.objects.select_related('b__c').__iter__().next() ... Traceback (most recent call last): File "<console>", line 1, in <module> File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/query.py", line 107, in _result_iter self._fill_cache() File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/query.py", line 772, in _fill_cache self._result_cache.append(self._iter.next()) File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/query.py", line 273, in iterator for row in compiler.results_iter(): File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 680, in results_iter for rows in self.execute_sql(MULTI): File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 725, in execute_sql sql, params = self.as_sql() File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 58, in as_sql self.pre_sql_setup() File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 29, in pre_sql_setup self.fill_related_selections() File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 661, in fill_related_selections used, next, restricted, new_nullable) File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 617, in fill_related_selections chain = opts.get_base_chain(f.rel.to) File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/options.py", line 452, in get_base_chain % model._meta.module_name,) TypeError: 'b' is not an ancestor of this model >>>
This was a little too deep in Django's internals for me to be able to debug, but as far as I can tell it's a legit bug.
Attachments (1)
Change History (15)
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
comment:3 Changed 6 years ago by
Changed 6 years ago by
Proposed patch
comment:4 Changed 6 years ago by
I've attached a patch that fixes it for me. Here's a summary of the problem:
When asked to
.select_related() a grand child
django.db.models.compiler.SQLCompiler.fill_related_selections() will cascade into both the child and the grand child of the model. When it hits the child it will inevitably find a field pointing to itself. At that point a call to
django.db.models.options.Options.get_base_chain() will raise an exception because (1) it has a non-empty list of parents and (2) it's being asked about its very own model that of course is not in the list.
Not sure if that's the correct solution but I've just added a check to ensure
.get_base_chain() is not talking to itself and in such a case return nothing (as there are no additional intermediate classes to add to the query).
comment:5 Changed 6 years ago by
I'm wondering if this shouldn't be fixed elsewhere.
Not super familiar with these internals either, but would you want to exclude self from the list of parents in the first place here:
comment:6 Changed 6 years ago by
I don't think it's a case of
self.__class__ being in parents. Rather it's a case where one-to-one on a subject of
.select_related() points back to the parent object (as is the case with natural inheritance). As
self is in the scope of the query, Django tries to find intermediate classes to add to the query. To do so it asks
self's manager for the list of classes but the manager gets confused and raises an exception.
comment:7 Changed 6 years ago by
More context:
The code reads as follows (
django/db/models/sql/compiler.py):
603 for f, model in related_fields: 604 if not select_related_descend(f, restricted, requested, reverse=True): 605 continue 606 # The "avoid" set is aliases we want to avoid just for this 607 # particular branch of the recursion. They aren't permanently 608 # forbidden from reuse in the related selection tables (which is 609 # what "used" specifies). 610 avoid = avoid_set.copy() 611 dupe_set = orig_dupe_set.copy() 612 table = model._meta.db_table 613 614 int_opts = opts 615 alias = root_alias 616 alias_chain = [] 617 chain = opts.get_base_chain(f.rel.to)
In this case
used is:
set(['products_childmodel'])
requested is:
{'grandchildmodel': {}}
opts is:
<Options for ChildModel>
f and
model are:
(<django.db.models.fields.related.OneToOneField object at …>, <class 'products.models.GrandChildModel'>)
and
f.rel.to points back to the child model:
<class 'products.models.ChildModel'>
So in the end it asks the
Options instance to
.get_base_chain() for its very own model. One solution is to apply my patch and have the
Options instance deal with that. Another would be to add a check between lined 603 and 604 and just
continue if the relation points to something that is already in
used or at least when it points to the object managed by
opts.
comment:8 Changed 6 years ago by
comment:9 Changed 5 years ago by
This patch certainly solved the problems I was having with this.
comment:10 Changed 5 years ago by
comment:11 Changed 5 years ago by
comment:12 Changed 5 years ago by
comment:13 Changed 5 years ago by
I submitted a pull request to add unit tests that reproduce this bug:
comment:14 Changed 5 years ago by
This seems to be fixed in the commits of #13781. The test in comment:13 passed on sqlite for me, and charettes reports fixed for him too. On a quick look the tests of #13781 seems to cover this ticket's issue, so I will not commit the tests.
Confirmed. | https://code.djangoproject.com/ticket/16572 | CC-MAIN-2017-47 | refinedweb | 1,002 | 50.02 |
libslack(daemon) - daemon module
#include <slack/std.h> #include <slack/daemon.h> typedef void daemon_config_parser_t(void *obj, const char *path, char *line, size_t lineno); int daemon_started_by_init(void); int daemon_started_by_inetd(void); int daemon_prevent_core(void); int daemon_revoke_privileges(void); int daemon_become_user(uid_t uid, gid_t gid, char *user); char *daemon_absolute_path(const char *path); int daemon_path_is_safe(const char *path, char *explanation, size_t explanation_size); void *daemon_parse_config(const char *path, void *obj, daemon_config_parser_t *parser); int daemon_pidfile(const char *name); int daemon_init(const char *name); int daemon_close(void); pid_t daemon_getpid(const char *name); int daemon_is_running(const char *name); int daemon_stop(const char *name);
This module provides functions for writing daemons. There are many tasks that need to be performed to correctly set up a daemon process. This can be tedious. These functions perform these tasks for you.
int daemon_started_by_init(void)
If this process was started by init(8), returns 1. If not, returns
0.
If it was, we might be getting respawned so fork(2) and exit(2) would
be a big mistake (and unnecessary anyway since there is no controlling
terminal). On error, returns
-1 with
errno set appropriately.
int daemon_started_by_inetd(void)
If this process was started by inetd(8), returns
1. If not, returns
0. On error, returns
-1 with
errno set appropriately. If it was,
stdin,
stdout and
stderr would be opened to a socket. Closing them
would be a big mistake. We also would not need to fork(2) and exit(2)
because there is no controlling terminal.
int daemon_prevent_core(void)
Prevents core files from being generated. This is used to prevent leaking
sensitive information in daemons run by root. On success, returns
0. On
error, returns
-1 with
errno set appropriately.
int daemon_revoke_privileges(void)
Revokes setuid and setgid privileges. Useful when your program does not
require any special privileges and may become unsafe if incorrectly
installed with special privileges. Also useful when your program only
requires special privileges upon startup (e.g. binding to a privileged
socket). Performs the following: Sets the effective gid to the real gid if
they differ. Checks that they no longer differ. Sets the effective uid to
the real uid if they differ. Checks that they no longer differ. Also closes
/etc/passwd and /etc/group in case they were opened by root and give access
to user and group passwords. On success, returns
0. On error, returns
-1 with
errno set appropriately.
int daemon_become_user(uid_t uid, gid_t gid, char *user)
Changes the owner and group of the process to
uid and
gid
respectively. If
user is not null, the supplementary group list will be
initialised with initgroups(3). Otherwise, the supplementary group list
will be cleared of all groups. On success, returns 0. On error, returns -1.
Only root can use this function.
char *daemon_absolute_path(const char *path)
Returns
path converted into an absolute path. Cleans up any
. and
.. and
// and trailing
/ found in the returned path. Note that the
returned path looks canonical but isn't because symbolic links are not
followed and expanded. It is the caller's responsibility to deallocate the
path returned with mem_release(3) or free(3). On success, returns the
absolute path. On error, returns
null with
errno set appropriately.
int daemon_path_is_safe(const char *path, char *explanation, size_t explanation_size)
Checks that the file referred to by
path is not group or world writable.
Also checks that the containing directories are not group or world writable,
following symbolic links. Useful when you need to know whether or not you
can trust a user supplied configuration/command file before reading and
acting upon its contents. On success, returns 1 if
path is safe or 0 if
it is not. When the path is not safe, an explanation is written to the
explanation buffer (if it is not
null). No more than
explanation_size bytes including the terminating
nul byte will be
written to the
explanation buffer. On error, returns
-1 with
errno
set appropriately.
void *daemon_parse_config(const char *path, void *obj, daemon_config_parser_t *parser)
Parses the text configuration file named
path. Blank lines are ignored.
'#' to end of line) are ignored. Lines that end with
'\' are
joined with the following line. There may be whitespace and even a comment
after the
'\' character but nothing else. The
parser function is
called with the client supplied
obj, the file name, the line and the line
number as arguments. On success, returns
obj. On error, returns
null
(i.e. if the configuration file could not be read). Note: Don't parse config
files unless they are "safe" as determined by daemon_path_is_safe(3).
int daemon_pidfile(const char *name)
Creates a pid file for a daemon and locks it. The file has one line
containing the process id of the daemon. The well-known locations for the
file is defined in
ROOT_PID_DIR for root (
"/var/run"
by default) and
USER_PID_DIR for all other users
(
"/tmp" by default). The name of the file is the name of the daemon
(given by the name argument) followed by
".pid" (If name is an
absolute file path, it is used as is). The presence of this file will
prevent two daemons with the same name from running at the same time. On
success, returns
0. On error, returns
-1 with
errno set
appropriately. Note: This is called by daemon_init(3) so there is
usually no need to call this function directly.
int daemon_init(const char *name)
Initialises a daemon by performing the following tasks:
If the process was not invoked by init(8) or inetd(8):
Background the process to lose process group leadership.
Start a new process session.
Under SVR4, background the process again to lose process session
leadership. This prevents the process from ever gaining a controlling
terminal. This only happens when
SVR4 is defined and
NO_EXTRA_SVR4_FORK is not defined when libslack was compiled). This means
that the client can't make any assumptions about the
SIGHUP handler when
daemon_init(3) returns.
Change directory to the root directory so as not to hamper umounts.
Clear the umask to enable explicit file creation modes.
Close all open file descriptors. If the process was invoked by inetd(8),
stdin,
stdout and
stderr are left open since they are open to a
socket.
Open
stdin,
stdout and
stderr to
/dev/null in case something
requires them to be open. Of course, this is not done if the process was
invoked by inetd(8).
If
name is non-null, create and lock a file containing the process id of
the process. The presence of this locked file prevents two instances of a
daemon with the same name from running at the same time. The default
location of the pidfile is
/var/run for
root or
/tmp for ordinary users.
On success, returns
0. On error, returns
-1 with
errno set
appropriately.
int daemon_close(void)
Unlinks the locked pid file, if any. Returns 0.
pid_t daemon_getpid(const char *name)
Return the process id of the daemon with the given
name. If the daemon in
question is owned by root, then this function must be invoked by root.
Similarly, if the daemon in question is owned by an ordinary user, then this
function must be invoked by an ordinary user. If
name is the absolute
path to the pidfile (rather than just the daemon name), then any user may
call this function. On success, returns the process id of the daemon. On
error, returns
-1 with
errno set appropriately.
int daemon_is_running(const char *name)
Checks whether or not a daemon with the given
name is running. If the
daemon in question is owned by root, then this function must be invoked
by root. Similarly, if the daemon in question is owned by an ordinary
user, then this function must be invoked by an ordinary user. However, if
name is the absolute path to the pidfile (rather than just the daemon
name), then any user may call this function. On success, returns
1 if the
daemon is running or
0 if it is not. On error, returns
-1 with
errno set appropriately.
int daemon_stop(const char *name)
Stop a daemon process with the given
name by sending it a
SIGTERM
signal. If the daemon in question is owned by root, then this function
must be invoked by root. Similarly, if the daemon in question is owned by
an ordinary user, then this function must be invoked by that user. Note that
root can't use this function to stop a daemon started by another user
just by passing the name of the daemon (because the pidfiles for root
daemons and user daemons are stored in different directories). In order for
root to stop an ordinary user's daemon process,
name has to be the
absolute path to the daemon's pidfile. On success, returns
0. On error,
returns
-1 with
errno set appropriately.
Additional errors may be generated and returned from the underlying system calls. See their manual pages.
EINVAL
An argument was invalid (e.g.
null).
ENAMETOOLONG
The
name passed to daemon_init(3) or daemon_path_is_safe(3)
resulted in a path name that is too long for the intended filesystem.
ELOOP
daemon_path_is_safe(3) recursed too deeply (16 levels).
ESRCH
daemon_stop(3) found that there was no daemon running with the given name.
MT-Safe
This example reads and prints
/etc/fstab with daemon_parse_config(3),
becomes a daemon and then sends a syslog(3) message and then terminates.
#include <slack/lib.h> const char * const config_fname = "/etc/fstab"; List *config = NULL; void fstab_parser(void *obj, const char *path, char *line, size_t lineno) { char device[64], mount[64], fstype[64], opts[64]; int freq, passno; if (sscanf(line, "%s %s %s %s %d %d", device, mount, fstype, opts, &freq, &passno) != 6) fprintf(stderr, "Syntax Error in %s (line %d): %s\n", path, lineno, line); else { char *copy; printf("%s %s %s %s %d %d\n", device, mount, fstype, opts, freq, passno); if (!(copy = mem_strdup(line))) fprintf(stderr, "out of memory\n"); else if (!list_append(config, copy)) fprintf(stderr, "failed to add line %d to config\n", lineno); } } void hup(int signo) { list_remove_range(config, 0, -1); daemon_parse_config(config_fname, config, fstab_parser); } void term(int signo) { daemon_close(); exit(EXIT_SUCCESS); } void do_stuff() { // do stuff... syslog(LOG_DAEMON | LOG_DEBUG, "Here we are"); kill(getpid(), SIGTERM); signal_handle_all(); } int main(int ac, char **av) { if (daemon_revoke_privileges() == -1 || daemon_prevent_core() == -1 || daemon_path_is_safe(config_fname, NULL, 0) != 1 || (config = list_create(free)) == NULL || daemon_parse_config(config_fname, config, fstab_parser) == NULL || daemon_init(prog_basename(*av)) == -1 || signal_set_handler(SIGHUP, 0, hup) == -1 || signal_set_handler(SIGTERM, 0, term) == -1) return EXIT_FAILURE; do_stuff(); return EXIT_SUCCESS; // unreached }
It is possible to obtain a controlling terminal under BSD (and even under
SVR4 if SVR4 was not defined or
NO_EXTRA_SVR4_FORK was defined when
libslack is compiled). If anything calls open(2) on a terminal device
without the
O_NOCTTY flag, the process doing so will obtain a controlling
terminal.
Because root's pidfiles are created in a different directory (
/var/run)
to those of ordinary users (
/tmp), it is
possible for root and another user to use the same name for a daemon
client. This shouldn't be a problem. It's probably desirable. But if it is a problem, recompile
libslack and
relink daemon so that all pidfiles are created in
/tmp by defining
ROOT_PID_DIR and
USER_PID_DIR to both be
/tmp.
The exclusive creation and locking of the pidfile doesn't work correctly over NFS on Linux so pidfiles must reside locally.
daemon_path_is_safe(3) ignores ACLs (so does sendmail(8)). It should probably treat a path as unsafe if there are any ACLs (allowing extra access) along the path.
The functions daemon_prevent_core(3), daemon_revoke_privileges(3), daemon_become_user(3), daemon_absolute_path(3), daemon_path_is_safe(3) and daemon_parse_config(3) should probably all have the daemon_ prefix removed from their names. Their use is more general than just in daemons.
libslack(3), daemon(1), init(8), inetd(8), fork(2), umask(2), setsid(2), chdir(2), setrlimit(2), setgid(2), setuid(2), setgroups(2), initgroups(3), endpwent(3), endgrent(3), kill(2))
20100612 raf <raf@raf.org> | http://libslack.org/manpages/daemon.3.html | CC-MAIN-2015-40 | refinedweb | 1,986 | 65.62 |
Hi all,
I hope that is not a stupid question and you'll forgive me if it is
and excuse me for my englishand excuse me for my english
I want to exec an ant build from java code. The response of the ant should be put in the future in a JScrollPane and if script has inputs this should be capture somehow and resend them to the script, like it is working in console.
I managed to do it, but I have a problem if ant script needs inputs. When I run the code, I must to input somehow back to the Process the value expected but I don't know how
Below is my code any hints or advices are welcome
Thank you!
* TestAnt.class where call is made
* test.xml - the ant script
* the output of the script when is called from java
public class TestAnt { public static void main(String[] args) { try { InputStream stdout = null; String jarLocation=new File(TestAnt.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getAbsolutePath(); String antFileLocation = "c:/ant_1.8/bin/ant.bat"; String cmd = antFileLocation+" -f "+jarLocation+"/test.xml"; Process process = Runtime.getRuntime().exec(cmd); stdout = process.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader(stdout)); String line; while ((line = input.readLine()) != null) { if (line.indexOf("[input]") == -1) { System.out.println(line); } else { System.out.println(line); //in this place an input should be sent back to the process //the code will freeze //my intention is to put all this code in JScrollPane to avoid opening a console } } process.waitFor(); input.close(); } catch (InterruptedException ex) { Logger.getLogger(TestAnt.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(TestAnt.class.getName()).log(Level.SEVERE, null, ex); } } }
<?xml version="1.0"?> <project name="set_package" basedir="." default="test"> <target name="test"> <echo message="Do you want to continue?"/> <input message="obs. responde with y/n" validargs="y,n" addproperty="skip"/> <echo message="${skip}"/> </target> </project>
Buildfile: V:\...\SetPackageSwing\dist\test.xml test: [echo] Do you want to continue? [input] obs. responde with y/n (y, n) | http://www.javaprogrammingforums.com/file-i-o-other-i-o-streams/5681-reading-ant-output-when-exec-command.html | CC-MAIN-2018-22 | refinedweb | 342 | 50.94 |
This blog continues my React/TypeScript miniseries and the previous blogs are:
1. Let’s start coding with TypeScript and React.js
2. React.js: A functional component and its state
3. Using the React.js state hook in the weather app
In this blog, I’ll add the useEffect() hook to fetch the weather info in the app that we started in the previous blog, where you learned how to store the city in the state of the App component. But our ultimate goal is finding the weather in the given city by fetching the data from an external server. Using the terminology from functional programming, we need to write a function with side effects. As opposed to pure functions, the functions with side effects use the external data and every invocation may produce different results even if the function arguments remain the same.
In React’s functional components, we’ll be using the useEffect() hook for implementing the functionality with side effects. By default, React automatically invokes the callback function passed to useEffect() after every DOM rendering. Let’s add the following function to the App component from the previous blog:
useEffect(() => console.log("useEffect() was invoked"));
If you run the app with the browser console open, you’ll see the message “useEffect() was invoked” each time when you enter a character in the input field and the UI is refreshed. Every React component goes through a set of lifecycle events, and if you need you code to be executed after the component was added to the DOM or each time it was was re-rendered, the useEffect() is the right place for such a code. But if you want the code in useEffect() to be executed only once after initial rendering, specify an empty array as the second argument:
useEffect(() => console.log("useEffect() was invoked"), []);
The code in this hook will be executed only once, which makes it a good place for performing the initial data fetch right after the component has been rendered.
Let’s assume you live in London and would like to see the weather in London as soon as this app is launched. Start by initializing the city state with “London”:
const [city, setCity] = useState('London');
Now you’d need to write a function that would fetch the data for the specified city. The URL will include the following static parts (replace 12345 with your APPID).
const baseUrl = ''; const suffix = "&units=imperial&appid=12345";
In between, you need to place the name of the city, so complete URL may look like this:
baseUrl + 'London' + suffix
For making Ajax requests, we’ll use the browser’s Fetch API (see). The function fetch() returns a Promise, and we’ll use the async/await keywords in our method getWeather() that can look like this:
const getWeather = async (city: string) => { const response = await fetch(baseUrl + city + suffix); const jsonWeather = await response.json(); console.log(jsonWeather); }
NOTE: I prefer using the async/await keywords for asynchronous code, but using promises with chained .then() invocations would also work here.
When you use a standard browser’s fetch() method, getting the data is a two-step process: You get the response first, and then you need to call the json() function on the response object to get to the actual data.
TIP: JavaScript developers often use third-party libraries for handling HTTP requests. One of the most popular ones is a promise-based library called Axios (see).
Now you can use this function for the initial data fetch in the useEffect():
useEffect( () => getWeather(city), []);
If you want the code in useEffect() to be executed selectively only if a specific state variable changed, you can attach the hook to such a state variable. For example, you can specify that the useEffect() has to run only if the city gets updated as follows:
useEffect(() => console.log("useEffect() was invoked"), ['city']);
The current version of the App component is shown below.
import React, { useState, useEffect, ChangeEvent } from 'react'; const baseUrl = ''; constGet Weather</button> <h2>City: {city}</h2> </form> </div> ); } export default App;
The second argument of the useEffect() is an empty array, so getWeather() will be invoked only once when the App component is initially rendered.
Note: If you run this app, the browser’s console will show the following warning: React Hook useEffect has a missing dependency: ‘city’. Either include it or remove the dependency array react-hooks/exhaustive-deps. The reason is that inside this hook we use the state variable city, which is a dependency and should be listed in the array. This is not an error and for simplicity I’ll keep this code as is, but you should keep this in mind while designing your hooks.
Tip: For the in-depth coverage of the useEffect() hook, read the article by Dan Abramov “A complete guide to useEffect“.
Run this app with the browser console open, and it’ll print the retrieved JSON with the London weather:
The initial data fetch is complete for the default city, and it looks like a good idea to store the retrieved weather data in the component’s state. Let’s define a new type Weather as shown in listing below for storing the content of the properties name and main marked in the above screenshot.
export interface Weather { city: string; humidity: number; pressure: number; temp: number; temp_max: number; temp_min: number; }
In the App component, we’ll add a new state variable weather and the function to update it as follows:
const [weather, setWeather] = useState(null);
Note that the hook useState() allows you to use a generic parameter for better type safety. Now we need update the function getWeather() so it saves the retrieved weather and city name in the component’s state as shown below:
async function getWeather(location: string) { const response = await fetch(baseUrl + location + suffix); if (response.status === 200){ const jsonWeather = await response.json(); const cityTemp: Weather = jsonWeather.main; cityTemp.city=jsonWeather.name; setWeather(cityTemp); } else { setWeather(null); } }
This code takes the object jsonWeather.main and the city name from jsonWeather.name, and saves them in the state variable weather.
So far, our function getWeather() was invoked for the initial retrieval of the London weather by the hook useEffect(). The next step is to add the code to invoke getWeather() when the user enters any other city and clicks on the button Get Weather. This button is a part of the form (its type is submit), so we’ll add the event handler to the tag. The function handleSubmit() and the first version of the JSX:
const handleSubmit = (event: FormEvent) => { event.preventDefault(); getWeather(city); } return ( <div> <form onSubmit = {handleSubmit}> <input type="text" placeholder="Enter city" onInput = {handleChange} /> <button type="submit">Get Weather</button> <h2>City: {city}</h2> {weather && <h2>Temperature: {weather.temp}F</h2>} </form> </div> );
In React, event handlers get instances of SyntheticEvent, which is an enhanced version of browser’s native events (see for details). SyntheticEvent has the same interface as the browser native events (e.g. preventDefault()) but events work identically across all browsers.
To pass the argument to getWeather(city), we didn’t have to find the reference to the field on the UI. The component’s state city was updated as the user typed the name of the city, so the variable city already has the value displayed in the field. The next screenshot was taken after the user entered Miami and clicked on the button Get Weather.
What if the user enters the city that doesn’t exist or not supported by openweathermap.org? The server returns 404 and we should add the appropriate error handling. So far we have the following line to prevent displaying the temperature if the weather state is falsy:
{ weather && <h2>Temperature: {weather.temp}F</h2> }
In the next version of this app, we’ll create a type guard to check if the weather for the provided city was received or not. For now, let’s take a breather and recap what we did in this and the previous blogs in the weather app:
1. Applied for the APPID at openweathermap.org
2. Generated a new app and replaced the JSX with a simple
3. Declared the state city using the hook useState()
4. Added the function handleChange() that updated city on each change in the input field
5. Added the hook useEffect() that would be invoked only once on the app startup
6. Ensured that useEffect() invokes the function getWeather() that uses the fetch() API to retrieve the weather in London
7. Declared the state weather to store the retrieved temperature and humidity
8. Added the event handler handleSubmit() to invoke getWeather() after the user entered the city name and clicked on the button Get Weather
9. Modified the function getWeather() to save the retrieved weather in the state weather
10. Displayed the retrieved temperature on the web page under the form
This is all good, but you shouldn’t to program all the app logic in one App component, and in the next blog, we’ll create a separate component to be responsible for displaying the weather data.
The source code of the completed app is here. If you want to learn TypeScript quickly, get our book TypeScript Quickly. | https://yakovfain.com/author/budam/ | CC-MAIN-2020-10 | refinedweb | 1,542 | 59.23 |
dialogs.text_dialog() size
Is there any way to control the size of the text_dialog?
I have set a fixed width font for the dialog (Courier 12). On my iPad Pro the dialog width is 68 characters. However, on my iPhone 7, it is only 50.
Is there a way to get the character size of the dialog that will be displayed?
@tbrown313 text_dialog presents the view as a sheet of width=500 which can contain 68 characters with font Courier 12.
But sheet does not exist on iPhone, doc says
we call the View.present() method to get the main view on screen. Views can be presented with different styles. On the iPhone, all views are presented in full-screen, but on the iPad, you can choose between 'sheet', 'popover' and 'fullscreen'.
So...for an iPhone, width will be
ui.get_screen_size()[0]
We can use alert dialog to pause the user interaction with the current screen and show some intermediate action to the user like show error, take user email to process next step kind of stuff.
@tbrown313 you could try on your both devices:
import dialogs from objc_util import * import ui def main(): device = ObjCClass('UIDevice').currentDevice() if 'ipad' in str(device.model()).lower(): w = 500 else: w = ui.get_screen_size()[0] font = ('Courier',12) lc = ui.measure_string('A', font=font)[0] tvo = ObjCInstance(ui.TextView()) p = tvo.positionFromPosition_offset_(tvo.beginningOfDocument(), 0) rge = tvo.textRangeFromPosition_toPosition_(p,p) x = tvo.firstRectForRange_(rge).origin.x #x = 5 nc = int((w-2*x)/lc) f = dialogs.text_dialog(text='A'*nc, font=font) # Protect against import if __name__ == '__main__': main()
Thanks a lot for the code example, @cvp. This helps a lot. It makes it simple to figure out the best combination of font size and characters per line.
This is probably sufficient for my purposes on the iPad since the default size is big enough. I would be interested to know how to select 'sheet', 'popover', or 'fullscreen' however. The documentation on dialogs.text_dialog() doesn't show how to do this.
Also, if I don't have an external keyboard connected (which I never have connected on my iPhone), is there any method to get rid of the onscreen keyboard when the dialog first shows? In this particular case, I don't want the dialog text to be editable. I thought I had seen something about setting editable to false, but can't find the reference.
@tbrown313 don't use dialog if you want to
- use sheet, popover, ....
- decide the size of the view
- make the text non editable
from objc_util import * import ui def main(): device = ObjCClass('UIDevice').currentDevice() if 'ipad' in str(device.model()).lower(): w = 500 h = 500 else: w,h = ui.get_screen_size() font = ('Courier',12) lc = ui.measure_string('A', font=font)[0] tv = ui.TextView() tv.frame = (0,0,w,h) tv.font = font tv.editable = False tvo = ObjCInstance(tv) p = tvo.positionFromPosition_offset_(tvo.beginningOfDocument(), 0) rge = tvo.textRangeFromPosition_toPosition_(p,p) x = tvo.firstRectForRange_(rge).origin.x #x = 5 nc = int((w-2*x)/lc) tv.text = 'A'*nc tv.present('sheet') # Protect against import if __name__ == '__main__': main()
Again, @cvp, thanks a lot for the code. Using the GUI is problematic since much of what I do involves grabbing data from a server, doing something with it, then calling another app using web browser.open(url). When that is done within a Pythonista GUI script, it leaves the GUI window running in Pythonista. My flow is like this:
- Run a shortcut from the Shortcuts app.
- Shortcut calls a Pythonista script.
- Pythonista script makes a remote server call to get data, perhaps display it, perhaps copy to clipboard.
- Pythonista script calls another app using web browser.open(url)
- Other app opens and I do some stuff.
I consider this operation done, but Pythonista still has the GUI on screen if you enter the Pythonista App. So, when I do this same operation again, and the shortcut calls Pythonista, I now have two GUI windows stacked in Pythonista. This does work, but it seems clumsy and fraught with unknown problems.
So, when I have a process like this, I have been making do with the dialogs module in Pythonista, which doesn't have this problem--but has other limitations.
@tbrown313 A last solution is to copy the standard dialogs source code and modify as you want in your own version. | https://forum.omz-software.com/topic/6584/dialogs-text_dialog-size | CC-MAIN-2020-40 | refinedweb | 730 | 68.57 |
Difference between revisions of "Release notes/0.44/fr"
Revision as of 20:39, 20 June 2006 anything.
- fill.
Indicateur de style des outils.
Barre des contrôles de l'outil texte
-.
Palette de couleurs insérable
-
-.
Raccourcis clavier configurables..
Barre d'état
-
-.
- The statusbar text is now no longer just cut off if there is insufficient room, but an ellipsis (...) is inserted at the end to show there's more (only with Gtk 2.6 and newer).
Thème
- Inkscape: [].
Afficher ou non les poignées.
Nouveau comportement de suppression
-.
Préserver les positions des noeuds et poignées
-.
Divers
-.
Plume calligraphique
Tremblement
-.
Largeur de plume
-.).
Outil stylo (courbes de Bézier)
-.
Masques et chemins de décou.
Transformations
Boîte de dialogue transformer.
Centres de rotation persistants
-.
Coller les dimensions).
Connecteurs et disposition automatique
- Align and Distribute dialog.
Vectorisation sélective avec.
Adhérence
-.
Marqueurs
-.
Effets d'extension
-.
Raccourcis divers
-).
Améliorations diverses
-.
Corrections diverses de bogues
- plantera s'il est lié à la première version du paquet Debian de la librairie ramasse-miettes
- Certaines pré-versions d'Inkscape-0.44 subissaient des plantages si l'option "Composite" était activée dans la configuration de X.org. Ce problème est résolu dans la version finale.
Les espaces de nom (namespaces) peuvent nécessiter d'être réparés
- Les précédentes versions d'Inkscape sauvaient parfois les documents avec de mauvaises URIs d'espaces de nom sans prévenir. Ce problème a été résolu, mais des fichiers ainsi corrompus ne peuvent plus être ouverts. Ces documents peuvent nécessiter une correction manuelle des déclarations d'espaces de nom. Les URLs correctes sont listées ci-dessous, avec les préfixes d'espaces de noms corrects entre parenthèses :
- Sodipodi (sodipodi):
- Inkscape (inkscape):
- XLink (xlink):
- SVG (svg or none):
- RDF (rdf):
- Creative Commons (cc):
- Dublin Core Metadata (dc):
Attention aux thèmes défectueux sous. However, but it would be nice if you as affected user would inform the gtk-engines maintainers of any further.
Versions précédentes
- () | http://wiki.inkscape.org/wiki/index.php?title=Release_notes/0.44/fr&diff=prev&oldid=7057 | CC-MAIN-2019-26 | refinedweb | 314 | 61.33 |
raw materials for making shoes
US $1.2-5 / Sheet
1000 Sheets (Min. Order)
Concrete floor diamond grinding shoes
US $0-20 / Piece
2 Sets (Min. Order)
electrical donkey engine high pressure pump woods shoes
US $2000-3333 / Unit
3 Sets (Min. Order)
second hand shoes wholesale from usa to africa bulk used spor...
US $34.0-38.0 / Bags
350 Bags (Min. Order)
used soccer shoes wholesale from usa
US $10200.0-10200.0 / Twenty-Foot Container
1 Twenty-Foot Container (Min. Order)
Used mens shoes wholesale from usa
US $1-1.4 / Kilogram
10 Tons (Min. Order)
Used shoes wholesale from USA for sale used sneakers branded
US $25-35 / Kilogram
7000 Kilograms (Min. Order)
High Quality Used Shoes Wholesale from USA,Sell to Africa for...
US $0.5-1.5 / Kilogram
1 Kilogram (Min. Order)
Hot selling product 2015-2016 cheap used shoes warehous ...
US $1.6-2 / Kilogram
0.5 Kilograms (Min. Order)
Bales 100Kg Original Summer Mix Origin Used Shoes Wholesale ...
US $1.6-2 / Kilogram
0.5 Twenty-Foot Container (Min. Order)
2016 used shoes wholesale from usa used clothing uk
US $0.7-1.5 / Kilogram
12 Tons (Min. Order)
Used Shoes for Sale
US $1-60 / Pound
15000 Pounds (Min. Order)
Mixed Paired Used Shoes
US $0-0.65 / Pound
15500 Pounds (Min. Order)
Mix Used summer shoes
US $0.85-0.95 / Pound
10000 Pounds (Min. Order)
taiwan second hand factory sell cheap used shoes for sale
US $0.5-2.5 / Kilogram
1 Kilogram (Min. Order)
Premium used shoes
US $1.65 / Pound
18000 Pounds (Min. Order)
Well sorted men sports shoes second hand shoes wholesale
US $1100-1450 / Ton
18 Tons (Min. Order)
Super cheap used shoes in usa
US $0.5-1.4 / Kilogram
1 Twenty-Foot Container (Min. Order)
used clothing and shoes in usa basketball uniform yellow man ...
US $0.7-1.5 / Kilogram
13 Kilograms (Min. Order)
export in Africa usa dubai germany used leather shoes for sal...
US $1.8-3 / Kilogram
7 Tons (Min. Order)
Second Hand Clothes And shoes,Cream fashion second hand cloth...
US $0.8-1.5 / Kilogram
1 Twenty-Foot Container (Min. Order)
Bulk Wholesale used clothes And second hand Used Clothing
US $0.5-1.5 / Kilogram
20 Feet (Min. Order)
Mixed International Brand used shoes wholesale from usa
US $28-36 / Bag
1 Forty-Foot Container (Min. Order)
Cheap used mens shoes wholesale from usa
US $1-1111 / Twenty-Foot Container
1 Twenty-Foot Container (Min. Order)
Used shoes wholesale from usa ship to Benin used shoes in ger...
US $0.5-1.2 / Kilogram
7 Kilograms (Min. Order)
original used shoes and clothing, wholesale used shoes from ...
US $31-34 / Bag
300 Bags (Min. Order)
Original bulk big used shoes wholesale from usa
US $32-35 / Bag
50 Bags (Min. Order)
children summer used clothes wholesale cheap second hand ...
US $0.7-1.5 / Kilogram
12 Tons (Min. Order)
Ladies High Heel Fashion Shoes
US $0.65-70 / Pound
15000 Pounds (Min. Order)
Used shoes for TOGO Market
US $1.3-1.35 / Pound
14000 Pounds (Min. Order)
Wholesale used shoes men sports shoes
US $1100-1450 / Ton
8 Tons (Min. Order)
Used Winter Shoes
US $1.50 / Pound
36000 Pounds (Min. Order)
2015 Premium cheap wholesale used tennis shoes
US $0.5-1.4 / Kilogram
1 Twenty-Foot Container (Min. Order)
import used clothing usa, used shoes and clothes turkey secon...
US $0.8-1.5 / Kilogram
1 Twenty-Foot Container (Min. Order)
2015 China wholesale top quality sports shoes cheap price ...
US $1.2-2.5 / Kilogram | http://www.alibaba.com/showroom/used-shoes-wholesale-from-usa.html | CC-MAIN-2016-26 | refinedweb | 603 | 79.97 |
Here we will load a CSV called iris.csv. This is stored in the same directory as the Python code.
As a general rule, using the Pandas import method is a little more ’forgiving’, so if you have trouble reading directly into a NumPy array, try loading in a Pandas dataframe and then converting to a NumPy array.
Reading a csv file into a NumPy array
NumPy’s loadtxt method reads delimited text. We specify the separator as a comma. The data we are loading also has a text header, so we use skiprows=1 to skip the header row, which would cause problems for NumPy.
import numpy as np my_array = np.loadtxt('iris_numbers.csv',delimiter=",", skiprows=1) print (my_array[0:5,:]) # first 5 rows OUT: [[5.1 3.5 1.4 0.2 1. ] [4.9 3. 1.4 0.2 1. ] [4.7 3.2 1.3 0.2 1. ] [4.6 3.1 1.5 0.2 1. ] [5. 3.6 1.4 0.2 1. ]]
Saving a NumPy array as a csv file
We use the savetxt method to save to a csv.
np.savetxt("saved_numpy_data.csv", my_array, delimiter=",")
Reading a csv file into a Pandas dataframe
The read_csv will read a CSV into Pandas. This import assumes that there is a header row. If there is no header row, then the argument header = None should be used as part of the command. Notice that a new index column is created.
import pandas as pd df = pd.read_csv('iris.csv') print (df.head(5)) # First 5 rows OUT: sepal.length sepal.width petal.length petal.width variety
Saving a Pandas dataframe to a CSV file
The to_csv will save a dataframe to a CSV. By default column names are saved as a header, and the index column is saved. If you wish not to save either of those use header=True and/or index=True in the command. For example, in the command below we save the dataframe with headers, but not with the index column.
df.to_csv('my_pandas_dataframe.csv', index=False)
One thought on “25. Reading and writing CSV files using NumPy and Pandas” | https://pythonhealthcare.org/2018/04/04/25-reading-and-writing-csv-files-using-numpy-and-pandas/ | CC-MAIN-2020-29 | refinedweb | 359 | 73.98 |
Remote Procedure Calls
REST is often compared to RemoteProcedureCalls, like XmlRpc and RPC-style usages of SOAP (SOAP encoding or DocumentLiteral).
A typical use of RemoteProcedureCalls might be to maintain a jukebox playlist, with methods like "playlist.create" to create a new playlist, "playlist.insert" to insert an item into a playlist, "playlist.delete" to remove an item from the playlist, and "playlist.list" to retrieve the current playlist. One would create this service, for example, to share playlists between work and home. These calls might be defined like:
playlist.insert(login, password, listname, songstructure, position)
playlist.remove(login, password, listname, position)
list = playlist.list(login, password, listname)
With this API, your music player could start up and retrieve your playlist (list), add and remove songs in the list order (insert, remove), and of course create new lists (create). songstructure would be a structure that includes song name, album, band, and a URL to the audio, and playlist.list returns an array of those structures.
As time goes on, users may find that they want to add descriptions to their playlists, so the API is extended to support that:
description = playlist.getDescription(login, password, listname)
Note that you have to make two calls to display a playlist with its description, because we couldn't change playlist.list to also return the description without breaking backward compatibility.
[RogerBenningfield] Please note that this is misleading. If playlist.list() returns a struct (list.items, list.description), multiple calls are in no way required. Multiple calls are often desirable, however, given that they may result in lower bandwidth consumption; one does not always need access to descriptions in order to make use of a playlist.
This API has six actions, which are unique to the management of lists which happen to be song playlists. More actions would be added as more features are added.
[RogerBenningfield] The above is not an artifact of the RPC process. A single playlist.modify() call could be implemented, with all the details contained within an extensible struct. That would usually be considered poor practice by those of an OOP-ish bent, but value aside, it would be trivial to do with an RPC API.
The Web
REST works in terms of "resources" (things at URI locations), a small set of uniform actions that are performed on those resources (primarily, but not limited to, HTTP's GET, PUT, POST, and DELETE), and transfering representations of those resources (what gets passed as the content).
The above API for playlists would be implemented in REST as a resource, a list of songs. In HTTP, one would PUT the list to create and update it, GET to retrieve it, and DELETE to remove it. The representation might look like this (abbreviated):
<playlist> <song> <name>Jazzy</name> <uri></uri> </song> <song> <name>Snappy</name> <album>Snappy Tunes</album> <uri></uri> </song> </playlist>
The same representation can be used with HTTP or a local file system, one can open() the file, read() it, write() a new version, or remove() it. A play list server might store the song lists as records in a database.
Some applications may work directly with the XML. Others may choose to use a library to serialize and deserialize the information. For example, in Python you could use
xmltramp, e.g.:
import xmltramp playlist = xmltramp.load('') for song in playlist['song']: print "Name: " + song.name print "URI: " + song.uri
Adding a "description" to the playlist is just a matter of adding it to the representation:
<playlist> <description>Light, Snappy, Jazzy tunes</description> <song> : :
A Perl equivalent to xmltramp is
XML::Generator.
Sample.
Questions
RPC is REST because it uses HTTP POST, right?
No. HTTP is not REST. HTTP can be used in the REST architectural style. RPCs define their own actions and use HTTP POST only as a "transport" to carry the call.
Can't RPCs be used to implement REST architectural styles?
Technically, yes. A resource's identity is a small, uniform set of actions performed on those resources, and the representation of state of the resources. A resource's identity characterizes REST. You can tell if a service is in the REST Architectural Style (is RESTful) when you can apply virtually all of the same, limited, set of actions on every single resource provided. Compared to the web, one could say such an RPC API would be "like the web but not the web".
Is SOAP RESTful?.
This probably doesn't have anything to do with REST; what are SOAP encoding and document-literal?
Correct, REST avoids mandating any particular representation of state. SOAP encoding is an "object graph" developed as a cross-platform representation of programming structures. DocumentLiteral allows any well-formed XML to be carried in a SOAP envelope, and is processed much like XML would be if retrieved without an envelope.
Are CGIs REST?
CommonGatewayInterface (CGI) is an API for standalone programs to respond to web server requests. Just as HTTP is not REST but can be RESTful, so a CGI is not REST but can be RESTful. You can tell if a CGI is RESTful when individual resources are available as seperate URIs. It is the representation of those resources that are passed as content using GET, PUT, POST, etc. (not "parameters to the CGI"), and the same set of small number of actions works across all resources.
Contributors: KenMacLeod,
Dotan | http://www.intertwingly.net/wiki/pie/RestAndRpc | crawl-002 | refinedweb | 896 | 65.32 |
C# Corner
ServiceStack moves to a complete Web application framework with support for Razor forms.
A few months ago, I wrote an article about using ServiceStack to breathe life into old ASP.NET Web Forms applications. Using ServiceStack, you could easily add REST support to Web Forms applications without having to deal with the headaches of running a combined Web Forms + MVC site. This time, let's look at ServiceStack Razor forms support -- making ServiceStack a complete Web application framework.
If you're not familiar with ServiceStack, I encourage you to quickly review my other article. It will give you a good overview of the DTO approach used by ServiceStack to expose services. This will help you understand the service I'll be creating in this article.
Getting Started
Because the Razor view engine used by ServiceStack is the Microsoft .NET Framework 4, the sample code will be a .NET 4 Web application, but I'll still use the free version of ServiceStack, version 3.9.71. The methods presented in this article will work for both 3.9.71, as well as the newer 4.x commercial version of ServiceStack.
To get started, I create a new ASP.NET Application in Visual Studio. When prompted to select the template, I use the Empty template. This will create a basic ASP.NET Web application, but there's no support for Web Forms (ASPX) or MVC (Razor).
Next, I install the ServiceStack.Razor NuGet package. This will automatically pull in all of its dependent packages. As you recall in my last article on using ServiceStack, I need to use the NuGet Package Manager Console to install a specific version of ServiceStack (the free one):
Install-Package ServiceStack.Razor -Version 3.9.71 -DependencyVersion Highest
ServiceStack needs an entry point. This is the "AppHost" class and this is where I'll add support for using Razor forms from ServiceStack. I create a new AppHost.cs class file and add the following code:
public class AppHost : AppHostBase
{
public AppHost() : base("ServiceStackAndHTML", typeof(AppHost).Assembly)
{
}
public override void Configure(Container container)
{
Plugins.Add(new RazorFormat());
SetConfig(new EndpointHostConfig { DebugMode = true });
}
}
In the EndpointHostConfig, I hardcoded DebugMode to true for this sample (normally, it's inferred by ServiceStack). By putting ServiceStack in debug mode, a background file system watcher will automatically restart the AppDomain for the Web site whenever a view or layout is changed. This will make for a faster refresh when I hop back to the browser to view new pages.
This AppHost class needs to be initialized just once, so I'll add a Global.asax file and plug my AppHost into the Application_Start handler:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
new AppHost().Init();
}
}
Finally, I need to make some changes to web.config. First, like last time, I need to add a handler so all requests to this application are handled by ServiceStack. I add a new system.webServer section:
>
Second, when I installed ServiceStack.Razor, changes were made to my web.config that point to an old version of the Microsoft System.Web.WebPages.Razor assembly, version 1.0. I don't have version 1.0 on my machine (it's probably an old MVC 3 distribution), but I do have version 2.0, so I just updated the assembly version number in web.config:
<add assembly="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" />
That's all I need! My ServiceStack-based Web site is ready to serve up services, as well as Razor view pages. And, as a bonus, it supports Markdown, too (and more on that later)!
Serving Up HTML
To see how easy it is to start creating Razor forms, I use Visual Studio and add a new MVC 5 View Page (Razor). I called the page "default.cshtml" and I put it right in the root directory of the Web site (no Controller needed). This inserts a very basic Razor form:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
</div>
</body>
</html>
This should look familiar to anyone that has done MVC work with Razor. Notice how I have control of setting the Layout property? I can even put in straight C# code -- just like in MVC. Because this is a Razor form and ServiceStack supports Razor, there's nothing more I need to do. But, to make sure everything is working, I'll add a little server-side Razor code. Inside the <div> in the <body> I'll add a call to get the current date/time:
Server Time: @DateTime.Now
Now I hit F5, my browser launches and I'm looking at the server's time. I didn't need to create an MVC controller and a route to get to the page. ServiceStack's Razor support allows direct access to Razor pages and it even strips off the extension to give you nice URLs -- and will also strip off any documents that are called "default." So, for my example where I created default.cshtml in the root directory, my URL in the browser shows:
If I rename "default.cshtml" to "servertime.cshtml," the page is available via:
This is a huge time saver for simple pages that don't need the overhead of an MVC controller just to display some HTML. And I also don't need to set up any custom routes to get these pretty URLs.
Markdown Support!
Markdown is a super-simple format that allows content to be expressed in simple text, but still allows that text to be converted into nice-looking HTML. StackOverflow and GitHub are just a few examples where Markdown is used heavily to maintain user-submitted content. For a quick overview of Markdown and its formatting, see the StackOverflow editing help page.
The ServiceStack HTML rendering supports Markdown files directly. Inside Visual Studio, I add a new text file called "ShowMeContent.md". I enter the following text into this file:
Section 1
==============
This is section 1.
Section 1.1
--------------
And here is a sub-section.
This part is **very** important to understand.
On its own, this text is very simple and could easily be used in a plain-text e-mail. But I'm serving this up from a Web site, so when I go back to my browser and visit this page, I'll get HTML (notice again how I don't need to include the ".md" extension and I automatically have a pretty URL):
I don't want to go into all of the details of Markdown, but if you view the rendered HTML, you'll see how "Section 1" got wrapper in an <h1> tag and "Section 1.1" is wrapped in an <h2> tag. The "**" surround the word "very" caused it to be rendered as bold (a single "*" will render it as italics).
ServiceStack has even combined the power of Razor forms with the ease of Markdown into a view engine called Markdown Razor. This gives you the ability to do all sorts of server-side code in Razor sections, but define the presentation in Markdown. Here's a simple example. Note that Markdown Razor does not support multi-line statements so I can't wrap the code in a @{ … } block:
@var goodMovies = new [] { "Star Wars: The Force Awakens", "Star Wars: The Empire Strikes Back" };
@var poorMovies = new [] { "Star Wars: The Phantom Menace" };
Good Movies
==============
@foreach var title in goodMovies {
- @title
}
Poor Movies
==============
@foreach var title in poorMovies {
- @title
}
I place this in a file called "mymovielist.md" and then go to my browser to view it in HTML:
Without any styling, it's pretty boring, but I can go back later and add a stylesheet to fix that. If I want to use this data for a plain-text e-mail, I could add a "format" URL argument and tell ServiceStack I want the bare text version of this Markdown page:
Finally, ServiceStack lets you mix and match view engines in a single page. I can go back to my servertime.cshtml page and add a new <div> to display my movie list:
<div style="background-color: #ccc">
@Html.Partial("mymovielist")
</div>
You'll see I didn't need to include the ".md" extension. ServiceStack.Razor will first look for "mymovielist.cshtml" and, if not found, will look for "mymovielist.md."
ServiceStack Services and HTML
Instead of a simple page that lists my movies, let's assume I have a real movie listing service that's exposed with ServiceStack. For this article, I'll create a very simple service that stores the list in-memory. The data for each movie will include its name and a flag indicating if it's a poor movie:
public class Movie
{
public string Title { get; set; }
public bool IsPoor { get; set; }
}
Like any ServiceStack service, I need to define a request and response DTO. For right now, I'm only implementing the query (GET) functionality, but I'll add "Title" and "IsPoor" properties to my request so this object can be used later for adds and deletes:
[Route("/movielist")]
public class MoviesRequest
{
public string Title { get; set; }
public bool? IsPoor { get; set; }
}
In my response DTO, I'll take a list of movies and split them into the Good movies and the Poor movies. Note the use of a parameterless constructor, as well as the [DataContract] and [DataMember] attributes in Listing 1. This allows my service to be exposed to SOAP clients, as well (this is all built-in functionality of ServiceStack).
[DataContract]
public class MoviesResponse
{
private readonly Movie[] goodMovies;
private readonly Movie[] poorMovies;
public MoviesResponse(IEnumerable<Movie> allMovies)
{
this.goodMovies = allMovies.Where(m => !m.IsPoor).ToArray();
this.poorMovies = allMovies.Where(m => m.IsPoor).ToArray();
}
public MoviesResponse()
: this(Enumerable.Empty<Movie>())
{
}
[DataMember]
public Movie[] GoodMovies
{
get { return goodMovies; }
}
[DataMember]
public Movie[] PoorMovies
{
get { return poorMovies; }
}
}
Now I create the service to return my list of movies. I use a static constructor to initialize the in-memory listing of movies, as shown in Listing 2.
public class MovieService : Service
{
private static List<Movie> movies = new List<Movie>();
static MovieService()
{
movies.AddRange(new[]
{
new Movie {Title = "Star Wars: The Force Awakens", IsPoor = false},
new Movie {Title = "Star Wars: The Empire Strikes Back", IsPoor = false},
new Movie {Title = "Star Wars: The Phantom Menace", IsPoor = true}
}
);
}
public MoviesResponse Get(MoviesRequest request)
{
return new MoviesResponse(movies);
}
}
Once I compile this application, any client making a GET request to my "/movielist" endpoint will get a response with the list of movies based on the Content-Type requested. To test this, I enter the URL in my browser, but tell ServiceStack I want the format to be JSON because that's what I'm used to seeing when I debug REST services:
I could leave off the "format" argument and ServiceStack will give me a basic HTML page with the data in a tabular format. Instead, I'll take advantage of ServiceStack's Razor support to return a custom Markdown page.
While I showed earlier that ServiceStack supports direct viewing of Razor pages without the need for a controller, it still uses the "/Views" and "/Views/Shared" folders when looking for views for a ServiceStack service. The resolution order used in the search is:
So I create a "Views" folder in the root of my application and create an empty Markdown file with the name "MoviesResponse.md" (same name as my response DTO). To utilize Markdown Razor, I can inherit from MarkdowViewBase<T> where T is my response object type (Note: If I was creating a regular Razor page (.cshtml), I would inherit from ViewPage<T>):
@inherits ServiceStack.Markdown.MarkdownViewBase<ServiceStackAndHTML.DTO.MoviesResponse>
This types the "Model" property inside my Markdown Razor page as my MoviesResponse DTO. Now I can take the Markdown I used earlier from "mymovielist.md" and make a few changes to pull the list of good and poor movies from the model (my service's response DTO). Here's the complete MoviesResponse.md:
@inherits ServiceStack.Markdown.MarkdownViewBase<ServiceStackAndHTML.DTO.MoviesResponse>
Good Movies
==============
@foreach var movie in Model.GoodMovies {
- @movie.Title
}
Poor Movies
==============
@foreach var movie in Model.PoorMovies {
- @movie.Title
}
I can now put in my browser and get my custom HTML.
Add and Delete Functionality
To make this service really useful, I'll implement the ability to add new movies, as well as remove movies from my list. This is as easy as adding a "Post" (add) and a "Delete" (remove) method to my service, as you can see in Listing 3.
public MoviesResponse Post(MoviesRequest request)
{
movies.Add(new Movie
{
Title = request.Title,
IsPoor = request.IsPoor.Value
});
return new MoviesResponse(movies);
}
public MoviesResponse Delete(MoviesRequest request)
{
movies = movies.Where(m => !(m.Title == request.Title && m.IsPoor == request.IsPoor))
.ToList();
return new MoviesResponse(movies);
}
To test this, I'll open up Postman (bit.ly/1YYNrkb), my favorite Chrome add-in for API testing. I'll construct a request to my service to add another movie:
{"Title":"The Godfather, Part II","IsPoor":false}
I click Postman's Send button and my response is an updated list of movies. If I go back to my browser and refresh the movielist page, I'll see the new movie. Now I can go back to Postman, leave the body the same and change the verb to DELETE. I press Send, go back and refresh the “movielist” page, and I get an updated list of movies that has the new movie removed.
Of course, we don't want our users using Postman to access this service. Download the sample code for this article and you'll see how I created a complete single-page app against this service (). I also took the time to create a Layout page to really showcase how easy it is to move your Razor knowledge to ServiceStack.
Wrapping Up
This article covered just the basics of using HTML from within ServiceStack. There's so much more I didn't have time to cover:
If you'd like to see any of these topics covered, feel free to drop me an e-mail.
Printable Format
> More TechLibrary
I agree to this site's Privacy Policy. | https://visualstudiomagazine.com/articles/2016/02/01/servicestack-and-razor-forms.aspx | CC-MAIN-2018-51 | refinedweb | 2,371 | 63.9 |
Cython can be viewed as an extension of Python where variables and functions are annotated with extra information, in particular types. The resulting Cython source can be compiled into optimized C or C++ code, and thereby yielding substantial speed-up of slow Python code. Cython is particularly favorable when working with long loops processing large numpy arrays.
Programmers will, as with most effective software development tools, need quite some experience also with Cython before Python code can be quickly extended with Cython syntax and turned into high-performance computing code. The next sections provide a quick hands-on introduction to Cython with emphasis on basic ideas and a number of pitfalls that newcomers are likely to end up with.
Quite some Cython documentation is available, partly at and partly as HTML files in the Doc folder of the Cython source code distribution. If you find yourself using Cython after having seen the capabilities from the forthcoming examples, you are strongly encouraged to read through the existing Cython documentation.
The first example involves a simple numerical method for solving a scalar first-order ordinary differential equation (ODE):
The software is created for solving general ODEs on the form
The user must provide the following input data: \(f(u,t)\), \(I\), \(T\), the time step \(\Delta t\) (dt), and the numerical method for solving the ODE.
The core of the algorithm for solving this problem consists of a time loop where a new value of \(u\) in time are computed from the previous value. The particular method for advancing \(u\) one time step is naturally put in a separate function such that this function can simply be replaced by an alternative function if an alternative method is desired.
def solver(f, I, dt, T, method): """ Solve scalar ODE: u'(t) = f(u,t), u(0)=I, 0 < t <= T method: numerical method to advance u one time step. dt: time step length. """ N = int(round(float(T)/dt)) u = I t = 0 for n in xrange(N): # may get memory error for large N u = method(u, t, f, dt) t += dt return u, t
Here is one choice of the method function, using a 2nd-order Runge-Kutta scheme:
Our particular problem can now be solved by defining
def problem1(u, t): """Right-hand side function f(u,t) for the ODE u'=-u+1.""" return -u + 1
and calling
u, t = solver(f=problem1, I=1, dt=0.1, T=5, method=RK2)
We collect the solver, RK2, and problem1 functions in a pure Python module file called ode0.py.
A trivial Cython code for the present example is simply to copy ode0.py to a new file with extension .pyx, as Cython files always have this extension. We let the name of this first file, in a series of Cython versions of ode0.py, be ode0_cy1.pyx. The pure Python code in this file is also valid Cython code (at the time of this writing Cython supports almost all of Python). However, before we can execute this Cython code, it needs to be compiled by the cython program, compiled by a C compiler, and linked as a shared library. This shared library is a Python extension module that can be imported in a Python program as any other module.
The easiest way of making an extension module from a .pyx file is to create a setup.py file that will apply the same compiler and flags as were used when compiling Python itself. A typical setup.py file for the present case looks as follows:
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext cymodule = 'ode0_cy1' setup( name='ODE test', ext_modules=[Extension(cymodule, [cymodule + '.pyx'],)], cmdclass={'build_ext': build_ext}, )
The setup.py file is run by
Terminal> python setup.py build_ext --inplace
The result is a compiled extension module ode0_cy1.so on Linux (with other extensions on other platforms). This module can be imported like any other module,
import ode0_cy1 as ode0
In the rest of the program code we cannot distinguish between the Cython and Python versions of the ode0 module.
We may compare the efficiency of the original Python module ode0 with its Cython-compiled variant by running
Terminal> python ode0_main.py 0 # runs ode0.py in pure Python Terminal> python ode0_main.py 1 # runs ode0_cy1.py in Cython
Just compiling with Cython halves the CPU time in this example.
The first step in annotating Python code with the extended syntax offered by Cython is to declare (all) variables with their type. Cython supports C-style types like int, double, and ndarray. Moreover, C versions of functions can be called directly from C code by using cdef in the function header line instead of def. With cpdef, two versions of the function are made, one to be called from C and one from Python. The code now reads
cpdef solver(f, double I, double dt, double T, method): cdef int N = int(round(float(T)/dt)) cdef double u = I # previous time step cdef double t = 0 cdef int n for n in xrange(N): u = method(u, t, f, dt) t += dt return u, t cpdef double RK2(double u, double t, f, double dt) except -10001: cdef double K1, K2, unew K1 = dt*f(u, t) K2 = dt*f(u + 0.5*K1, t + 0.5*dt) unew = u + K2 return unew cpdef double problem1(double u, double t) except -10001: return -u +1 # u = 1-exp(-t)
Annotating variables with their types decreases the CPU time by over 40 percent. The functions above appear in the test program ode0_cy2.pyx.
At this point we should mention that if exceptions occur inside Cython function, the calling code cannot detect the exception. However, when an exception do occur in such a function, a warning message is printed and execution proceeds. It is possible, for C functions that returns primitive C types (and not a Python object), to propagate exceptions to the calling environment by using the except keyword:
cpdef double RK2(double u, double t, f, double dt) except -10001: ...
In this example, the value -10001 is returned when an exception occurs and that value signals an exception. The value should not be returned under circumstances where the function works.
Functions returning void in C (None in Python) must use except *, while functions returning a Python object that is not a primitive C data type cannot make use of the except keyword.
Running cython -a on a .pyx file results in a .html file with information on what Cython has done with the code. For example, cython -a ode_cy2.pyx results in a file ode0_cy2.html which can be loaded into a web browser and inspected. White lines have resulted in efficient C code, while yellow lines still use the Python API, see Figure HTML output explaining what Cython has done with the Python code. One can click on the yellow lines to see the underlying C code. The complete C code is available in ode0_cy2.c.
HTML output explaining what Cython has done with the Python code
Our code involves two function objects as argument to functions: f for defining the right-hand side of the ODE (the problem) and method for advancing the ODE one time step (the method). When these are ordinary Python function objects, the resulting code is slow. We can easily see this by replacing the calls to f and method by the actual function names problem (in RK2) and RK2 (in solver). The complete code is in ode0_cy3.pyx. The result is a speed-up of a factor of 250!
Nevertheless, we do not want these calls to be hardcoded for a special choice of problem and method. In C one would have applied function pointers for these arguments. An efficient and flexible construction in Cython is to replace the functions by methods in classes. For example, the problem definition goes as follows with a superclass, a method rhs, and a subclass implementing the particular problem in question (see ode0_py4.py):
cdef class Problem: cpdef double rhs(self, double u, double t) except -10001: return 0 cdef class Problem1(Problem): cpdef double rhs(self, double u, double t) except -10001: return -u + 1
Note the use of cdef in the class definition: these are Cython classes with several special features that make them different from standard Python classes, see the chapter Using Cython.
A similar strategy for implementing the RK2 method in terms of classes reads
cdef class ODEMethod: cpdef double advance(self, double u, double t, Problem p, double dt) except -10001: return 0 cdef class Method_RK2(ODEMethod): cpdef double advance(self, double u, double t, Problem p, double dt) except -10001: cdef double K1, K2, unew K1 = dt*p.rhs(u, t) K2 = dt*p.rhs(u + 0.5*K1, t + 0.5*dt) unew = u + K2 return unew
We now have to feed our solver method with a Problem1 object’s rhs method in as f and a RK2 object’s advance method as method. However, we want also this Cython version to behave as the original ode0.py code so that the “main program” in ode0_main.py remains unchanged. This can easily be achieved by defining
RK2 = Method_RK2() problem1 = Problem1() problem2 = Problem2() cpdef solver(Problem f, double I, double dt, double T, ODEMethod method): cdef int N = int(round(float(T)/dt)) cdef double u = I # previous time step cdef double t = 0 cdef int n for n in xrange(N): u = method.advance(u, t, f, dt) t += dt return u, t
in the Cython source.
The implementation described above doubles the CPU time compared to hardcoding the function names, but we still have a 125-fold reduction of the CPU time of the version where these functions are standard Python objects transferred to functions the standard way.
A natural next step is to remove the except * constructions (see ode0_cy5.pyx), at least after the Cython module is debugged. The removal increases the efficiency by 25 percent. It can also be interesting to run cython -a ode_cy5.pyx and view ode0_cy5.html to see that most of the Python code is now turned into efficient C code.
Our right-hand side function has so far been very simple: \(f(u,t) = -u + 1\). Changing the problem to involve a standard mathematical function from the math library, e.g., \(f(u,t) = -u + \exp{(-2t)}\), requires a careful implementation in Cython. First, let us try the naive approach with using the standard math Python module (ode_cy6.pyx):
from math import exp cdef class Problem2(Problem): cpdef double rhs(self, double u, double t): return - u + exp(-2*t) cdef class ODEMethod: cpdef double advance(self, double u, double t, Problem p, double dt): return 0
This little change of the problem increases the CPU time by a factor of 40! The reason is that the potentially efficient rhs function must call the exp function in Python’s math module via the Python API.
Fortunately, there are ways to improve the performance. One is to import exp from C’s math library (math.h), which is already wrapped by Cython so we can write (ode0_cy7.pyx)
from libc.math cimport exp
Alternatively, if the C’s math library had not been made available through Cython, we could have written (ode0_cy8.pyx)
cdef extern from "math.h": double exp(double)
Both versions brings down the CPU time by a factor of four. Compared to the choice \(f(u,t) = -u + 1\), the use of exp is 10 times slower. There is nothing to do with this penalty, since we call the fastest available implementation of the exponential function.
For curiosity, using exp from numpy causes a slowdown of the code by a factor of 80 (ode0_cy9.pyx). Another natural test is to use __call__ in classes Problem and ODEMethod instead of method names rhs and advance, to obtain nicer syntax. However, this slows down the code by a factor of 3.
The former implementations does not store the computed values of the unknown function \(u\) in the ODE, which means that we cannot plot or further analyze the solution. Suppose we now want to allocate an array for storing the computed point values in time of the solution. We also introduce an array t specifying all the time points for computation (this array defines then the time steps). The corresponding pure Python implementation is found in the file ode1.py and looks like
import numpy as np def solver(f, I, t, method): t = np.asarray(t) N = len(t)-1 u = np.zeros(N+1)1(u, t): return -u + 1
Note the rewrite of RK2: now we transfer the whole arrays u and t, which makes it simple to implement other multi-step methods, involving multiple time levels of u and t, using the same interface.
We can also just compile this program with Cython to get a very slight performance gain. It is, however, more natural to use the experience from the former sections and (i) declare all variables with types and (ii) represent function arguments to functions by classes and methods as outlined above. The code goes as follows (ode1_cy1.pyx):
import numpy as np cimport numpy as np cdef class Problem: cpdef double rhs(self, double u, double t): return 0 cdef class Problem1(Problem): cpdef double rhs(self, double u, double t): return -u +1 # u = 1-exp(-t) from math import exp cdef class Problem2(Problem): cpdef double rhs(self, double u, double t): return - u + exp(-2*t) cdef class ODEMethod: cpdef double advance(self, np.ndarray u, int n, np.ndarray t, Problem p): return 0 cdef class Method_RK2(ODEMethod): cpdef double advance(self, np.ndarray u, int n, np.ndarray t, Problem p): cdef double K1, K2, unew, dt dt = t[n+1] - t[n] K1 = dt*p.rhs(u[n], t[n]) K2 = dt*p.rhs(u[n] + 0.5*K1, t[n] + 0.5*dt) unew = u[n] + K2 return unew # Create names compatible with ode0.py RK2 = Method_RK2() problem1 = Problem1() problem2 = Problem2() cpdef solver(Problem f, double I, np.ndarray t, ODEMethod method): cdef int N = len(t)-1 cdef np.ndarray u = np.zeros(N+1, dtype=np.float) u[0] = I cdef int n for n in range(N): u[n+1] = method.advance(u, n, t, f) return u, t
Note the double import of numpy: the standard numpy module and a Cython-enabled version of numpy that ensures fast indexing of and other operations on arrays. Both import statements are necessary in code that uses numpy arrays. The new thing in the code above is declaration of arrays by np.ndarray.
Unfortunately, the performance improvement by the code above is only a factor of 2.5 compared with the pure Python version. The reason is that array indexing is still done in the standard Python way. To obtain efficiency C-style indexing, numpy arrays must be declared with their dimension (rank) and the type of their elements. This is done by the quite comprehensive syntax (ode1_cy2.pyx)
np.ndarray[np.float_t, ndim=1]
The np.float_t data type is a compiled data type defined in Cython’s enhanced version of numpy, and ndim=1 means that the array has one dimension (rank 1). An unfortunate side effect of the “buffer” syntax above is that functions with arrays declared this way cannot be declared with cdef or cpdef, they can only use the standard def, which implies that we end up with a pure Python function instead of a C function. However, the code inside this Python function can still be compiled to fast C.
The declaration above reduces the CPU time by a factor of 10, which is a factor of about 25 reduction compared to the pure standard numpy array code.
Since functions taking numpy arrays with “buffer” syntax are forced to be functions handled by the standard Python API, such functions have a significant overhead. Our RK2.advance method takes array arguments and performs operations on two single array elements u[n] and t[n]. We could easily avoid this and instead transfer u[n] and t[n] as double arguments (ode1_cy3.pyx):
cdef class ODEMethod: cpdef advance(self, double u_1, int n, double t_1, double dt, Problem p): return 0 cdef class Method_RK2(ODEMethod): cpdef advance(self, double u_1, int n, double t_1, double dt, Problem p): cdef double K1, K2, unew K1 = dt*p.rhs(u_1, t_1) K2 = dt*p.rhs(u_1 + 0.5*K1, t_1 + 0.5*dt) unew = u_1 + K2 return unew
def solver(Problem f, double I, np.ndarray[np.float_t, ndim=1] t, ODEMethod method): cdef int N = len(t)-1 cdef np.ndarray[np.float_t, ndim=1] u = np.zeros(N+1) u[0] = I cdef int n for n in range(N): u[n+1] = method.advance(u[n], n, t[n], t[n+1]-t[n], f) return u, t
A four-fold reduction in CPU time results from this technique of avoiding array arguments. The general rule of thumb is to avoid array arguments in functions that only operates on one or a few array elements. In functions processing large arrays with long loops element the overhead of using the Python C API to parse arguments the standard way will drown in the work done on the (large) arrays, so in such functions there is no efficiency loss by using “buffer” syntax and thereby the “def” declaration of functions.
Additional efficiency can be gained by turning off array bounds checking and the possibility to use negative indices:
@cython.boundscheck(False) # turn off bounds checking for this func. def solver(Problem f, double I, np.ndarray[DT, ndim=1, negative_indices=False] t, ODEMethod method):
We can also indicate that the arrays have contiguous memory (mode='c'):
@cython.boundscheck(False) # turn off bounds checking for this func. def solver(Problem f, double I, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] t, ODEMethod method):
The efficiency increase is about 5-10 percent (ode1_cy4.pyx). Changing the data type double to np.float_t all over the Cython code has negligible effect in this example (ode1_cy5.pyx).
We also could make a Fortran implementation of the ode1.py code to test what would be considered the fastest possible implementation. The code looks like this (ode1.f):
subroutine solver(f, U0, t, n_t, u, method) integer n_u0, n_t real*8 U0, t(0:n_t-1), u(0:n_t-1) external f, method integer n real*8 dt u(0) = U0 do n = 0, n_t-2 call method(u, n, t, f, n_t) end do return end subroutine rk2(u, n, t, f, n_t) integer n, n_t real*8 u(0:n_t-1), t(0:n_t-1) real*8 dt, un, dudt, K1, K2 external f dt = t(n+1) - t(n) un = u(n) call f(dudt, un, t(n)) K1 = dt*dudt un = u(n) + 0.5*K1 call f(dudt, un, t(n) + 0.5*dt) K2 = dt*dudt u(n+1) = u(n) + K2 return end subroutine problem1(dudt, u, t) dudt = -u + 1 return end subroutine problem2(dudt, u, t) dudt = -u + exp(-2*t) return end
We could have used a Fortran function for f since the result is a scalar, but the more general implementation for systems of ODEs would force us to use subroutines when dudt is an array.
The main program used in the test has the form
program ode2 integer n_U0, n_t, n real*8 pi parameter (n_t=8000001) real*8 u(0:n_t-1), U0, dt, t(0:n_t-1) real*8 cpu0, cpu1 external problem1, problem2, rk2 U0 = 1. call cpu_time(cpu0) dt = 5./(n_t-1) t(0) = 0 do n = 1, n_t-1 t(n) = t(n-1) + dt end do call solver(problem1, U0, t, n_t, u, rk2) call cpu_time(cpu1) n = n_t-1 write(*, 1000) 'u(', n, ')=', u(n) write(*, 2000) 'CPU time:', cpu1-cpu0 1000 format(A, I8, A, F12.4) 2000 format(A, F9.3) end
Quite surprisingly, this Fortran 77 implementation was almost five times slower than the most efficient Cython version (!). The Fortran code was also compiled with the -O3 flag to gfortran, while setup.py building of Cython modules applies the -O2 optimization that Python itself was built with.
To summarize, Cython increased the performance by a factor of 130+ and was in fact faster than Fortran 77!
Remark. The Fortran program needs to be carefully examined as it is not at all expected to be slower than a Cython implementation.
The previous example codes on using Cython aimed at solving a scalar ODE with one unknown function. The more common case of a system of ODEs, having a vector of functions as unknown, represent quite a discouraging case when it comes to the performance of Cython.
For a system of ODEs, with \(m\) equations and \(m\) unknowns, we must work with arrays of length \(m\), representing the unknowns, the right-hand side of the ODEs, as well as intermediate values in computations. The core of the algorithm must now compute with \(m\) arrays. Here is a typical implementation in Python that works for both scalar ODEs and systems of ODEs (“ode2.py” “”):
def solver(f, I, t, method): t = np.asarray(t) N = len(t)-1 if isinstance(I, (float,int)): I = [I] # wrap in list, which then will be array I = np.asarray(I) if not isinstance(f(I,0), np.ndarray): raise TypeError('f (%s) must return numpy array' % f.__name__) u = np.zeros((N+1, len(I)))2(u, t): r = [u[1], -u[0]] return np.asarray(r)
Every time the function problem2 is called (and that happens twice at each time level!), a new array must be made from a list. We can avoid this by implementing a class that allocates a numpy array for the right-hand side and reusing this in subsequent calls:
class Problem1: def __init__(self): # Allocate an array for dudt for efficiency self.dudt = np.zeros(2) def __call__(self, u, t): self.dudt[0] = u[1] self.dudt[1] = -u[0] return self.dudt
This trick reduces the CPU time by a factor of about 1.7.
We can introduce all the performance tricks we have covered so far when Cythonizing the ode2.py code: declare all variables, use “buffer” syntax for arrays (specify data type and rank/dimension, turn off negative indices, indicate contiguous memory), turn off array bounds checking, and use class methods instead of plain functions as arguments to functions. The complete code looks as follows:
import numpy as np cimport numpy as np cimport cython ctypedef np.float64_t DT cdef class Problem: cdef np.ndarray dudt def __init__(self): self.dudt = np.zeros(2) def rhs(self, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] u, double t): return 0 cdef class Problem1(Problem): def rhs(self, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] u, double t): self.dudt[0] = u[1] self.dudt[1] = -u[0] return self.dudt cdef class ODEMethod: def advance(self, np.ndarray[DT, ndim=2, negative_indices=False, mode='c'] u, int n, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] t, Problem p): return 0 @cython.boundscheck(False) cdef class Method_RK2(ODEMethod): def advance(self, np.ndarray[DT, ndim=2, negative_indices=False, mode='c'] u, int n, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] t, Problem p): cdef np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] K1, K2, unew cdef double dt cdef np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] un = u[n,:] dt = t[n+1] - t[n] K1 = dt*p.rhs(un, t[n]) K2 = dt*p.rhs(un + 0.5*K1, t[n] + 0.5*dt) unew = u[n,:] + K2 return unew # Create names compatible with ode2.py RK2 = Method_RK2() problem1 = Problem1() @cython.boundscheck(False) # turn off bounds checking for this func. def solver(Problem f, I_, t_, ODEMethod method): # I_ and t_ can be flexible objects cdef np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] t = np.asarray(t_) N = len(t_)-1 if isinstance(I_, (float,int)): I_ = [I_] # wrap in list, which then will be array cdef np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] I = np.asarray(I_) if not isinstance(f.rhs(I,0), np.ndarray): raise TypeError('f (%s) must return numpy array' % f.__name__) cdef np.ndarray[DT, ndim=2, negative_indices=False, mode='c'] u = np.zeros((N+1, len(I))) u[0,:] = I[:] for n in range(N): u[n+1,:] = method.advance(u, n, t, f) return u, t
Note the way attributes are declared in Cython classes: cdef np.ndarray dudt. Such an attribute is not visible from Python, only from C. Unfortunately, “buffer” syntax of class attributes is not allowed, resulting in slow indexing of these arrays. The efficiency gain by this Cython code is hardly noticeable (15 percent). The reason is that the time is spent on array indexing which is as inefficient as in pure numpy code. Inspecting what Cython has done (cython -a ode2_cy1.pyx) shows that most of the code except variable declarations is yellow and hence not translated to efficient C code.
A Fortran 77 version of the code, in file ode2.f, is about 60 times faster than the Cython version.
It seems that the only way out of the problem is to get rid of arrays and generate problem specific code where the method and the problem is combined. Despite this negative comment regarding Cython code for systems of ODEs, Cython has an enormous potential for solving partial differential equations! | http://hplgit.github.io/teamods/cyode/cyode-sphinx/main_cyode.html | CC-MAIN-2015-40 | refinedweb | 4,305 | 64 |
Let's say we want to reach, notepad.exe.
- Get the process by its name
using System.Diagnostics;Call GetaProcess("notepad.exe"); will return notepad process, if it is already launched.
private Process GetaProcess(string processname)
{
Process[] aProc = Process.GetProcessesByName(processname);
if (aProc.Length > 0)
return aProc[0];
else return null;
}
- To Kill the process
Process myprc = Call GetaProcess("notepad.exe"); myprc.Kill();Will kill the process notepad.exe.
- Handle the Exit Event of the Process
Process myprc = Call GetaProcess("notepad.exe");Now we will noticed when the notepad process exited.
myprc.Exited += new EventHandler(myprc_Exited);
void myprc_Exited(object sender, EventArgs e)
{
MessageBox.Show (((Process)sender).ProcessName + " process has exited!");
}
5 comments:
Uhm, this is useful a lot. But I'll be grateful if u can help me further.
I got a problem here: i want my process to start only if the last process with the same name has ended. Here a example: when u add a new TeraCopy job when it's still busy, the later must wait 'til the former has done, then it's his turn.
Can u help me, please...
you can also use the process.waitExit until the process exit in a simple scenario.
Process myprc = Call GetaProcess("notepad.exe")
it should be
Process myprc = Call GetaProcess("notepad")
Need only Application Name
Process myprc = Call GetaProcess("notepad.exe")
GetProcessesByName find only with application name .it should be "notepad"
Try this:
Process[] proc = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(
"notepad"))
This will return proc array populated with one entry | https://alperguc.blogspot.com/2008/11/c-process-processgetprocessesbyname.html | CC-MAIN-2017-26 | refinedweb | 252 | 70.5 |
A few weeks ago, some friends of mine started playing a Facebook game, Puzzle Adventures. This is a (pretty fun) jigsaw puzzle game, so I played a few levels at some point. The game limits you significantly in many areas (e.g. you can only play three or four games before you have to wait for minutes to play more, or pay). The game is also geared against you in that the time limits are pretty tight, but what irked me the most was that the puzzle pieces don’t snap together unless you get them really really close to each other, which is just a tactic for you to lose time, and isn’t fair.
Another fact that really annoys me is that I suck at jigsaw puzzle games, so my friends were beating me pretty handily. However, I am pretty handy with them computers, so I figured I’d have a look at the Flash binary and see if I can change anything to my benefit.
My exploration of the game’s internals follows.
Examining the server calls
After a short look at the server responses, it became clear that that wasn’t a way to go. Although the responses were trivial to change, the game synced everything to the server before and after every level, and if something wasn’t proper, the game produced an error. For example, I couldn’t give myself more hearts or boosts or anything, as the game told the server about this after the level, and the server knew I wasn’t supposed to have any hearts, so it didn’t count the level.
Not only that, but the game sent the actual moves in the level to the server, so that was another place where attack wasn’t feasible. I decided that it would be much simpler to change a local game mechanic instead.
Decompiling the flash file
Luckily, a friend of mine does some Flash work, and he owns a copy of Sothink Flash decompiler, a most excellent piece of software. I got a copy of the source code and started looking around for things I could do. I decided that changing the annoying snapping distance would be the easiest and most reasonable thing to do, so I searched for “snap”:
Sure enough, the constant SNAPPING_DISTANCE_MUTIPLIER above looks to be exactly what I need. Now, all I need to do is change it, which should be simple enough!
Apparently, it’s not that simple. Compiling the Flash binary again from the decompiled sources rarely succeeds (or so my friend told me), and, at any rate, I don’t own a copy of Flash, nor is it even available for Linux. The only thing that can be done is finding the constant in the Flash file and editing it with a hex editor.
Finding the constant
Editing the constant should also be pretty straightforward, all we need to do is find potential locations of the number “1.15” above and change it. However, it turns out that some flash binaries (including, unfortunately, the one I’m analyzing) are compressed, so trying to find the constant in the compressed binary will not yield any useful results. I need to decompress the file.
Decompressing the binary
As it turns out, Flash binaries are compressed very simply. All one needs to do is read the magic bytes (“CWS”, if the file is compressed) and the next 5 bytes, and then decompress the rest with zlib. Here’s a very simple Python script that decompresses compressed Flash files:
import zlib infile = open("test.swf", "rb") infile.seek(0, 0) if infile.read(3) == "CWS": data = "FWS" + infile.read(5) + zlib.decompress(infile.read()) open("decompressed.swf", "wb").write(data)
Our Flash binary is now decompressed, and we can look for the number.
Finding the constant (again)
Great, we are now ready to find the constant, but what’s the representation of a decimal in a Flash binary? Well, as it turns out, it’s stored as a little-endian IEEE 754 64-bit float (or, double).
Converting 1.15 to double, we get “333333333333c33f” in hex. Using the excellent Bless hex editor, and we can change it to, say, 2, which is “0000000000000040” and save. All done! To make sure, I can send the binary to my friend to decompile again, but I was pretty sure that was the right place so I skipped that step.
Is that all? Not quite, because now we need to override the remote swf with the local, edited one.
Replacing the remote swf with the local one
To do that, I used the excellent debugging proxy, Charles. After setting it up and loading the game, Charles shows the swf request, at which point we can override it by right-clicking on it and clicking “map to local”. Selecting the file, all is done!
Launching the replaced game, everything works normally, which is always a good sign. Playing a level, I see that pieces snap to each other from a fairly larger distance, so the change works! Finally, I can play without the trackpad messing my game up, and the game is now much fairer and more enjoyable.
And that’s how you win at Puzzle Adventures! | https://www.stavros.io/posts/winning-puzzle-adventures/ | CC-MAIN-2020-05 | refinedweb | 877 | 69.52 |
Ethereum Smart Contracts: Tips for Handling Data in Solidity
Solidity is the most popular language for writing Ethereum smart contracts. Solidity was proposed by Gavin Wood in August 2014. Although it isn’t the only language you can use to write smart contracts, it is the most popular language for writing smart contracts that run in the Ethereum. It enjoys solid support from the Ethereum community and was developed by the Ethereum project’s Solidity team.
Solidity was designed to be similar to JavaScript and was influenced by a few other popular programming languages as well, including C++ and Python. The goal of Solidity is to provide a language that is familiar to web application developers but targeted at smart contract development. Solidity isn’t intended not as a general-purpose language but to support blockchain specific operations with code that runs in the EVM.
Before your code can run in the EVM, you have to compile it. That’s why one of the components you installed when building your development environment was a Solidity compiler. You first write your Solidity source code in an editor. Then you compile it into bytecode, which are the instructions that run in the EVM. After you deploy your smart contract bytecode, it runs on all Ethereum nodes.
Because smart contracts run on all nodes, Solidity must enforce determinism, that is, the results must be the same for all nodes running your smart contract code with the same input. If you look at the Solidity documentation, you won’t find a
random() function. That omission is specifically to support Solidity’s determinism. Your code gets run first by the node that mines a new block, but then all nodes verify the block and run the code to ensure that they don’t get a different result.
In many ways, Solidity is similar to other programming languages. The biggest differences are in how the programs are run and how Solidity deals with data. Note that Solidity deals with data only in the EVM or the blockchain.
Solidity doesn’t interact with the outside world much, but it is possible. Solidity supports the concept of an oracle, which is a trusted source of information from the outside world.
Calling an oracle is easy. One problem is being able to trust the oracle. Another problem is dealing with oracle data that may return different data each time it’s called. Before using any oracles, you must ensure that the data source is trustworthy and consistent. It is common for oracles to return data and some proof of authenticity.
The concept of trust with respect to oracles is just an extension of blockchain trust. Remember that blockchain technology provides a trusted ledger of data in an environment of trustless network nodes. Because trust is such a foundational property of blockchain, it isn’t surprising that trusting an oracle is an important concern.
Solidity is particular about where you can store data. You generally define two types of variables in Solidity: state variables and local variables. You define state variables in the
contract section, and those variables are available anywhere in the smart contract. These variables store the state of your smart contract by saving the values in a block on the blockchain. You define local variables inside functions. Local variables don’t save their values between function calls. Those values aren’t stored on the blockchain and go away when the function ends.
Solidity defines three places for storing data:
- Stack: Where Solidity stores local simple variable values defined in functions.
- Memory: An area of memory on each EVM that Solidity uses to store temporary values. Values stored here are erased between function calls.
- Storage: Where state variables defined in a smart contract reside. These state variables reside in the smart contract data section on the blockchain.
Variable storage location is one of the more confusing aspects of Solidity. The Solidity language doesn’t have a stack keyword but does have
memory and
storage keywords. Solidity uses its own defaults, depending on where you define variables and how you use them, but you can override some of these defaults and also use the keywords to modify how Solidity treats variables.
Here are a few rules that help keep things straight when learning about storing data in Solidity:
- State variables are storage by default (values are stored in the blockchain).
- Local variables in functions are memory by default (values are stored temporarily in memory).
- Structs are storage by default (values are stored in the blockchain).
Solidity can handle different types of data and provides different types of variables to handle each type. When you define variables, you have to specify the datatype of the variable. The datatype tells Solidity how much space to allocate for the value you will store in the variable and how to treat the data. The following table lists the data types that Solidity supports.
As your smart contracts become more complex, you’ll probably need to represent more complex types of data. For example, you might want to define a physical address type that contains several pieces of information, including street address, city, state, and postal code.
You also might need to store tables or lists of data. Solidity allows you to create your own data structures with the
struct complex data type. You can also define arrays that store groups of similar data items. Solidity arrays can be groups of simple data types or groups of structs.
Here is a smart contract that demonstrates some of Solidity’s simple data types. In this example, you’re using only state variables, which means you’re writing to the blockchain. Defining all of your variable as state variables is not a good idea unless you want to store data forever. Data stored to the blockchain requires expensive operations and shouldn’t be used unless you need to store your data persistently. For now, you’ll use state variables.
Open VS Code for the myProject project:
To open VS Code in the myProject project, open a Windows Command prompt or PowerShell (my favorite) and use the
cd command to navigate to your project directory (myProject.) From here, just enter the following command and press Enter:
code .
Then type the following code or download the Ethereum project files from Dummies.
pragma solidity 0.4.24; /* * @title Solidity data types * @author Michael Solomon * @notice A simply smart contract to demonstrate simple data types available in Solidity * */ contract DataTypes { uint x = 9; int i = -68; uint8 j = 17; bool isEthereumCool = true; address owner = msg.sender; //Ethereum address of the message sender bytes32 bMsg = "hello"; string sMsg = "hello"; function getStateVariables() public view returns (uint, int, uint8, bool, address, bytes32, string) { return (x, i, j, isEthereumCool, owner, bMsg, sMsg); } }<
Before you can deploy and test your new smart contract, you need to add it to the migration JavaScript script. In VS Code, open the 2_contracts_migrations.js file in the Migrations directory. Then add the two lines with comments so your file looks this:
var HelloWorld = artifacts.require("HelloWorld"); var DataTypes = artifacts.require("DataTypes");// Add this line module.exports = function(deployer) { deployer.deploy(HelloWorld); deployer.deploy(DataTypes);// Add this line };
Don’t forget to save your file after adding the new text!
Here are the steps you can use to deploy and test your new smart contract:
- Make sure you have Ganache running.
- In VS Code, click or tap the Terminal tab, type the following, and then press Enter:
truffle deploy --reset
- Type truffle console and press Enter.
- At the Truffle console prompt, type the following and press Enter:
DataTypes.deployed().then(function(instance) {return instance.getStateVariables() });
The following image shows the values that your new smart contract returns. Truffle displays the return values in an interesting way. Numbers are returned as
BigNumber objects. You can call functions in a
BigNumber library to convert them, but for now just read the values directly.
For the numeric returned values, the first value,
s: is the sign of the number, and the third value,
c: is the unsigned value the function returned. Also note that the address and bytes32 values are in hexadecimal format.
| https://www.dummies.com/personal-finance/ethereum-smart-contracts-tips-for-handling-data-in-solidity/ | CC-MAIN-2019-47 | refinedweb | 1,360 | 64.2 |
Example use of TestSuite. More...
#include "ns3/test.h"
Go to the source code of this file.
Example use of TestSuite.
Assume this is the test suite for
class Class in module 'module'.
Document the file as follows. (Note: for purposes of this illustration Doxygen comments are set off with triple ‘\\\’; you should use the normal Javadoc format. )
Add it to the groups module-tests and class-tests:
/// \file /// \ingroup module-tests /// \ingroup class-tests /// Class test suite.
Define the class-tests group:
/// \ingroup module-tests /// \defgroup class-tests Class test suite
Make sure test.h is included:
#include "ns3/test.h"
Put the test code in namespace ns3::tests.
namespace ns3 { namespace tests {
Write your test cases and final test suite, and put them in your test group:
/// \ingroup class-tests class ClassTestSuite : public TestSuite {...};
Create a static variable to hold the instance of your test suite:
/// \ingroup class-tests /// ClassTestSuite instance variable. static ClassTestSuite g_classTestSuite;
Finally, close the ingroup and namespace blocks:
} // namespace tests } // namespace ns3
Definition in file sample-test-suite.cc. | https://www.nsnam.org/docs/doxygen/sample-test-suite_8cc.html | CC-MAIN-2022-40 | refinedweb | 175 | 76.11 |
Tulsa Labs
By tdh on Aug 21, 2010
I just attended the Newcomers Tutorial and the take home point for me was that IETF is a commune and not a police state. I.e., the IETF looks for "rough consensus" and does not "enforce".
I recently updated my home desktop to Win7 - I wanted to get the 64 bit professional version and update my system memory to 8G. I managed to loose my Firefox config information - i.e., mainly my accounts and passwords. Not that big of a deal to recover from. I did have a recent backup of my bookmarks, so I didn't loose all of my favorite web comics.
Last night I updated my Linksys wireless router to an Airport Extreme and even though I had all of the config information, that was much more of a pain. Changing routers always is it seems.
I went with the Airport Extreme because I liked the Airport Express I carry around to quickly setup a wireless network when I travel. There was a Hilton Garden Inn in Austin that does not like my Mac Book Air, so the Express solved that issue.
I checked to make sure I could configure port translation (look in the NAT settings) and I assumed I could easily VPN out of it.
The earliest issues I had were all related to getting the internet connection established and understanding the Apple nomenclature. I could not figure out whether the DHCP pane was talking about the external connection or the internal one. I think the internal address is determined by the DHCP range that you offer.
The big problem was that the DSL modem and the Extreme didn't seem to want to communicate. I could ping the Extreme, but couldn't seem to see out. Note, make sure to record an external pingable IP before you change your network infrastructure. Don't count on DNS working!
I put back the Linksys, did some searching, and decided to reboot the DSL modem and then the Extreme. That did the trick. Note that with other routers you might try MAC address cloning to fix this issue. Evidently the DSL router I have is smart enough to detect the MAC address it is connected to upon reboot. But it will also only talk to that one device.
My other issues revolved with the Airport Utility software - making a simple change to the Extreme configuration requires a reboot. And then the Airport Utility software might not be able to detect the Extreme. I rotated among three different clients to make changes.
I got through all that and tried using my Express to extend the Extreme's network. Now I can't see it at all via Airport Utility. And searching the web does not make me feel comfortable about getting Airport Utility to work properly.
The last issue I hit was that my mail server started rejecting requests from my Thunderbird desktop mail client. I don't know how I had my earlier Thunderbird outgoing server set up, but the current one was set to my outside DNS name. The Linksys must have automatically short cut the packet back to my internal server. The Airport Extreme was sending the request back with the external address of my DSL router. And my sendmail config was rejecting the relay request.
The solution here was to modify my mail server account in Thunderbird to be in the internal DNS subdomain.
I'm happy enough with the Airport Extreme - like most Apple products, it takes some getting used to. BTW - the reason I replaced the Linksys was it started locking up - after one "We've lost the internet!" call on a business trip, it is just too much to deal with! :-> I wanted N, dual band, and GigE ports. We'll see if I stay happy with the Airport Extreme....
I'm old skool enough that I prefer a CLI versus a GUI for administration tasks. I've got that disclaimer there because I happen to like web browsers, GIMP, and even WireShark at times.
Given a choice between being able to ssh (or even telnet) in to a box versus going to a web based interface, I'll almost always chose the ASCII interface. The exceptions would be when I don't have a manual and need to do something fast. If I'm not in a hurry, I'm willing to learn by trial and error.
I've been running some tests on a 7410 and I need to be able to restart NFS. I've been using the BUI because I really find it intuitive. For example, I needed to bring up another interface on a backend network and it was very simple to go to Configuration -> Network and just click my way through it. I also liked that my routing tables were set up correctly. I had just fought that in a similar situation on a v20z running Fedora 11.
I like being able to click on the Device and getting the relevant datalinks and interfaces. I like the apply changes implementation. I like it checks for uncommited transactions if I try to leave the current entry.
But what I really like is a very understated correlation between the BUI and CLI - the BUI documents scripting actions you can do in the CLI. Likewise, if you understand the CLI commands, you can quickly navigate to a BUI counterpart.
So my goal was to be able to restart NFS from the CLI. Rather than picking up a manual, I looked at where I was at in the BUI, which was Configuration -> Services. And to restart it, I selected the circular arrows to the left of the NFS Data Service.
This was 99% of the equivalent command:
washdc:> configuration services nfs abort commit done get script show assert disable enable help set
I was looking for a "restart" option and I realized that the button must be a combination of "disable" and "enable". Sure enough, this:
washdc:> configuration services nfs disable washdc:> configuration services nfs enable
was functionally equivalent.
I find that every time I interact with either the BUI or CLI, I find something else to remind me of the tight integration and also to appreciate them both being designed at the same time.
I need to be able to see if a mount request generated an error in the mountd daemon. I have a custom kernel that has changed the mount() function call to return the error code. So, now I'm using a very simple DTrace script to catch the error codes:
#!/usr/sbin/dtrace -s pid$1::mount:return { printf("rc = %d", args[1]); } pid$1::audit_mountd_mount:return { printf("rc = %d", args[1]); }
The issue is what happens when I try to run it:
[root@pnfs-4-11 ~]> ./mountd_res.d `pgrep -x mountd` dtrace: failed to compile script ./mountd_res.d: line 18: args[ ] may not be referenced because probe description pid100824::mount:return matches an unstable set of probes
What I think this means is that I've got multiple declarations of mount() and they all do not return something. Okay, I can narrow down the probe to just the one I want:
[root@pnfs-4-11 ~]> dtrace -l -f mount ID PROVIDER MODULE FUNCTION NAME 2378 lx-syscall mount entry 2379 lx-syscall mount return 13708 fbt genunix mount entry 13709 fbt genunix mount return 31190 syscall mount entry 31191 syscall mount return 65944 pid100824 mountd mount entry 65945 pid100824 libc.so.1 mount entry 65946 pid100824 mountd mount return 65947 pid100824 libc.so.1 mount return
And if I adjust my script:
pid$1:mountd:mount:return { printf("rc = %d", args[1]); }
We see I've fixed this issue!
[root@pnfs-4-11 ~]> ./mountd_res.d `pgrep -x mountd` dtrace: failed to compile script ./mountd_res.d: line 18: index 1 is out of range for pid100824:mountd:mount:return args[ ]
Okay, I got my syntax wrong for the return code:
pid$1:mountd:mount:return { printf("rc = %d", arg1); }
And now I see the correct output:
[root@pnfs-4-11 ~]> ./mountd_res.d `pgrep -x mountd` dtrace: script './mountd_res.d' matched 2 probes CPU ID FUNCTION:NAME 0 65946 mount:return rc = 0 0 65240 audit_mountd_mount:return rc = 1 0 65946 mount:return rc = 0 0 65240 audit_mountd_mount:return rc = 1
We've had some interesting question on nfs-discuss lately about mountd and I thought I'd use an userland script I wrote, snoop, and DTrace to show some interesting properties about mountd.
My perl script will send UDP mount requests to a server and spoof the client IP. I want to control what I send and I'll sometimes spoof a request from a non-existent machine.
BTW - you will notice I don't talk about what the share is that much, unless I state otherwise, it is:
[root@silver ~]> share | grep tdh -@tank/home /export/zfs/tdh rw ""
We can try a host without a name mapping:
[tdh@slayer ~/src]> host 10.10.20.41 Host 41.20.10.10.in-addr.arpa. not found: 3(NXDOMAIN) [tdh@slayer ~/src]> sudo ./udp_raw.pl src_addr 10.10.20.42
Note that since we don't have a client to receive the reply, we'll snoop it:
30 0.01297 10.10.20.42 -> silver MOUNT3 C Mount /export/zfs/tdh 31 0.01712 silver -> thens.internal.excfb.com DNS C 42.20.10.10.in-addr.arpa. Internet PTR ? 32 0.05912 thens.internal.excfb.com -> silver DNS R Error: 3(Name Error) 33 0.00522 silver -> thens.internal.excfb.com DNS C 42.20.10.10.in-addr.arpa. Internet PTR ? 34 0.00056 thens.internal.excfb.com -> silver DNS R Error: 3(Name Error) 35 0.00777 silver -> 10.10.20.42 MOUNT3 R Mount Permission denied
BTW - right off the bat we can see that mountd tries to resolve the client IP. What happens if there is a reverse entry?
[tdh@slayer ~/src]> host 192.168.4.14 14.4.168.192.in-addr.arpa domain name pointer blast-4-14.internal.excfb.com. [tdh@slayer ~/src]> sudo ./udp_raw.pl src_addr 192.168.4.14
Well?
37 0.03198 blast-4-14.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 38 0.00089 silver -> thens.internal.excfb.com DNS C 14.4.168.192.in-addr.arpa. Internet PTR ? 39 0.00051 thens.internal.excfb.com -> silver DNS R 14.4.168.192.in-addr.arpa. Internet PTR blast-4-14.internal.excfb.com. 40 0.00290 silver -> blast-4-14.internal.excfb.com MOUNT3 R Mount OK FH=01CC Auth=unix
So a client has to have a reverse mapping from IP to host name before we allow a mount to succeed. And we can see that in the source code for usr/src/cmd/fs.d/nfs/mountd/mountd.c:
875 getclientsnames(transp, &nb, &clnames); 876 if (clnames == NULL || nb == NULL) { 877 /\* 878 \* We failed to get a name for the client, even 'anon', 879 \* probably because we ran out of memory. In this situation 880 \* it doesn't make sense to allow the mount to succeed. 881 \*/ 882 error = EACCES; 883 goto reply; 884 }
What if I change the share to be:
[root@silver ~]> zfs set sharenfs=rw=blast4-14:blast4-15 tank/home/tdh
Will it work or fail?
[tdh@slayer ~/src]> sudo ./udp_raw.pl src_addr 192.168.4.14 [tdh@slayer ~/src]> sudo ./udp_raw.pl src_addr 192.168.4.15
Note that I wanted to show something warm in the cache and something cold:
24 0.03500 blast-4-14.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 25 0.00129 silver -> blast-4-14.internal.excfb.com MOUNT3 R Mount Permission denied 41 0.03706 blast-4-15.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh (retransmit) 42 0.01419 silver -> thens.internal.excfb.com DNS C 15.4.168.192.in-addr.arpa. Internet PTR ? 43 0.00048 thens.internal.excfb.com -> silver DNS R 15.4.168.192.in-addr.arpa. Internet PTR blast-4-15.internal.excfb.com. 44 0.00089 silver -> blast-4-15.internal.excfb.com MOUNT3 R Mount Permission denied
Two points here, the DNS cache is not flushed when a share reloads, but the nfs auth cache must be. If it were not flushed, we would have gotten permission granted.
Okay, I can show you what is going on by this example:
[root@silver ~]> zfs set sharenfs=rw=blast4-14.internal.excfb.com:blast4-15 tank/home/tdh
And;
24 0.03769 blast-4-14.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 25 0.00122 silver -> blast-4-14.internal.excfb.com MOUNT3 R Mount Permission denied 41 0.03115 blast-4-15.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh (retransmit) 42 0.00092 silver -> blast-4-15.internal.excfb.com MOUNT3 R Mount Permission denied
Okay, we should have gotten permission granted for the first!
[root@silver ~]> zfs set sharenfs=rw=blast4-17.internal.excfb.com:blast4-15 tank/home/tdh
And that fails as well:
20 0.03105 blast-4-17.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 21 0.00086 silver -> thens.internal.excfb.com DNS C 17.4.168.192.in-addr.arpa. Internet PTR ? 22 0.00056 thens.internal.excfb.com -> silver DNS R 17.4.168.192.in-addr.arpa. Internet PTR blast-4-17.internal.excfb.com. 23 0.00163 silver -> blast-4-17.internal.excfb.com MOUNT3 R Mount Permission denied
Ohhh! Smug mode off
Okay, I'm interested in what the function in_access_list will tell me. I've got a small DTrace script, which I iterated over the development off, which will let me know what is going on here:
!/usr/sbin/dtrace -Fs /\* \* Thanks to Peter Harvey; \* \* \* # ./mountd.d `pgrep -x mountd` \* \*/ dtrace:::BEGIN { printf("Sampling... Hit Ctrl-C to end.\\n"); } pid$1::check_client_new:return { printf("Access permission is %d", arg1); } pid$1::in_access_list:entry { self->trace_me = 1; printf("Access list is %s", copyinstr(arg2)); } pid$1::in_access_list:return { self->trace_me = 0; printf("Access permission is %d", arg1); } pid$1::strcasecmp:entry /self->trace_me == 1/ { printf("host vs list entry: |%s|, |%s|\\n", copyinstr(arg0), copyinstr(arg1)); } pid$1::strcasecmp:entry /self->trace_me == 1/ { printf("Comparison is %d", arg1); }
Note that I need to use strcasecmp because I can't iterate over the array. I get as a result:
[root@silver ~]> ./mount_trace.sh + pgrep -x mountd + /root/mountd.d 634 dtrace: script '/root/mountd.d' matched 6 probes CPU FUNCTION 0 | :BEGIN Sampling... Hit Ctrl-C to end. 0 -> in_access_list Access list is blast4-17.internal.excfb.com:blast4-15 0 -> strcasecmp host vs list entry: |blast4-17.internal.excfb.com|, |blast-4-17.internal.excfb.com| 0 | strcasecmp:entry Comparison is 135156944 0 | strcasecmp:entry host vs list entry: |blast4-15|, |blast-4-17.internal.excfb.com| 0 | strcasecmp:entry Comparison is 135156944 0 <- in_access_list Access permission is 0 \^C
D'oh! My share is wrong, wrong I say!
If instead I try:
[root@silver ~]> zfs set sharenfs=rw=blast-4-17.internal.excfb.com:blast-4-15 tank/home/tdh
We expect blast-4-15 to fail and blast-4-17 to succeed see:
28 0.03211 blast-4-15.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 29 0.00150 silver -> blast-4-15.internal.excfb.com MOUNT3 R Mount Permission denied 49 0.03460 blast-4-17.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh (retransmit) 50 0.00087 silver -> blast-4-17.internal.excfb.com MOUNT3 R Mount OK FH=01CC Auth=unix
Which shows again, that you need an exact match and we don't append the domain name to end of the hostname. What would happen if added this to end of the server's /etc/hosts?
192.168.4.14 blast-4-15
I expect it to work. Does it?
[root@silver ~]> grep MOUNT xxx 24 0.03176 blast-4-15.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 27 0.00124 silver -> blast-4-15.internal.excfb.com MOUNT3 R Mount Permission denied 49 0.00160 blast-4-17.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh (retransmit) 52 0.00098 silver -> blast-4-17.internal.excfb.com MOUNT3 R Mount OK FH=01CC Auth=unix
Hmm, I bet the name entry is cached, which I can show by trying one which is not cached:
[root@silver ~]> zfs set sharenfs=rw=blast-4-17.internal.excfb.com:blast-4-31 tank/home/tdh
And
[root@silver ~]> grep MOUNT xxx 24 0.03633 blast-4-17.internal.excfb.com -> silver MOUNT3 C Mount /export/zfs/tdh 27 0.00102 silver -> blast-4-17.internal.excfb.com MOUNT3 R Mount OK FH=01CC Auth=unix 45 0.02997 blast-4-31 -> silver MOUNT3 C Mount /export/zfs/tdh (retransmit) 46 0.00189 silver -> blast-4-31 MOUNT3 R Mount OK FH=01CC Auth=unix
And we can see the lack of caching because of two clues, the name output in snoop, i.e., "blast-4-31", and the lack of DNS activity between the two packets.
Some of the behaviour shocked me and I made some stupid mistakes that were hard to figure out what I had done. As an exercise in triage, it was great. I now have the beginnings of a DTrace debugging tool that I can point people at if they need some help. I'm very, very happy about that part!
One of the hardest things about developing software is testing it. As a developer, you get too close to the code and what you expect it to do. So I was very happy to get a question in email about why was a set of policies not working correctly:
I tried to reset the SPE policies to the following: # cat /etc/policies.spe 101, 1, 8k, DS2, path == /diskpool/JUNK/TEST/P1 102, 2, 4k, DS1, path == /diskpool/JUNK/TEST/P2 103, 3, 2k, mix3, path == /diskpool/JUNK/TEST/P3 104, 4, 1k, mix4, path == /diskpool/JUNK/TEST/P4 #105, 5, 128k, default, path == /diskpool/JUNK/TEST/P5 || path == /export/JUNK 111, 5, 32k, default, path == /diskpool/JUNK/TEST/P5 112, 5, 64k, default, path == /export/JUNK and have the client uses the path to verify the stripe. For stripe 1,2,3 things seem working OK; however when I tried with strip 4 or 5 with the policy above, I got "nfsstat -l" to list stripe 10 and count 32k: pnfs-minipit1-3:~# pnfs-minipit1-3:~# /mntpit1-3: mount -o vers=4 pnfs-minipit1-5:/diskpool/JUNK/TEST/P5 /mnt pnfs-minipit1-3:~# nfsstat -m /mnt /mnt from pnfs-minipit1-5:/diskpool/JUNK/TEST/P5 Flags: vers=4,proto=tcp,sec=sys,hard,intr,link,symlink,acl,rsize=1048576,wsize=1048576,retrans=5,timeo=600 Attr cache: acregmin=3,acregmax=60,acdirmin=30,acdirmax=60 pnfs-minipit1-3:~# mkfile -v 1m /mnt/kk /mnt/kk 1048576 bytes pnfs-minipit1-3:~# nfsstat -l /mnt/kk Number of layouts: 1 Proxy I/O count: 0 DS I/O count: 33 Layout [0]: Layout obtained at: Sun Aug 30 00:23:47:199247 2009 status: UNKNOWN, iomode: LAYOUTIOMODE_RW offset: 0, length: EOF num stripes: 10, stripe unit: 32768 Stripe [0]: tcp:pnfs-minipit1-6.Central.Sun.COM:10.1.232.125:4920 OK Stripe [1]: tcp:pnfs-minipit1-6.Central.Sun.COM:10.1.232.125:4920 OK Stripe [2]: tcp:pnfs-minipit1-7.Central.Sun.COM:10.1.235.56:4920 OK Stripe [3]: tcp:pnfs-minipit1-7.Central.Sun.COM:10.1.235.56:4920 OK Stripe [4]: tcp:pnfs-minipit1-6.Central.Sun.COM:10.1.232.125:4920 OK Stripe [5]: tcp:pnfs-minipit1-6.Central.Sun.COM:10.1.232.125:4920 OK Stripe [6]: tcp:pnfs-minipit1-7.Central.Sun.COM:10.1.235.56:4920 OK Stripe [7]: tcp:pnfs-minipit1-7.Central.Sun.COM:10.1.235.56:4920 OK Stripe [8]: tcp:pnfs-minipit1-6.Central.Sun.COM:10.1.232.125:4920 OK Stripe [9]: tcp:pnfs-minipit1-6.Central.Sun.COM:10.1.232.125:4920 OK pnfs-minipit1-3:~# What did I do wrong?
Before we even look at the issue, what did the person asking for help do right
In short, I'm confident that the person took all reasonable steps to solve the problem on their own.
So, now let's try to figure out what is going on. I have a DTrace script which will help out here. Ouch, I should have shared that earlier. Anyway, spe.d should help. I'll start it up and monitor the results as I do a file create:
[root@pnfs-minipit1-5 ~]> ./spe.d dtrace: script './spe.d' matched 8 probes CPU ID FUNCTION:NAME 1 3420 nfs41_spe_allocate:spe-i-check_open 200096 (10) from 10.1.233.191 is checking /diskpool/JUNK/TEST/P5/foollu2 1 3419 nfs41_spe_allocate:spe-i-policy_eval Policy 101 did not match with error 0 from 10.1.233.191 1 3419 nfs41_spe_allocate:spe-i-policy_eval Policy 102 did not match with error 0 from 10.1.233.191 1 3419 nfs41_spe_allocate:spe-i-policy_eval Policy 103 did not match with error 0 from 10.1.233.191 1 3419 nfs41_spe_allocate:spe-i-policy_eval Policy 104 did not match with error 0 from 10.1.233.191 1 3419 nfs41_spe_allocate:spe-i-policy_eval Policy 111 matched with error 0 from 10.1.233.191 1 63564 mds_ds_path_to_mds_sid:return mds_sid[0] = pnfs-minipit1-6:pNFSpool1/p1DS2 1 63564 mds_ds_path_to_mds_sid:return mds_sid[1] = pnfs-minipit1-6:pNFSpool2/p2DS2 1 63564 mds_ds_path_to_mds_sid:return mds_sid[2] = pnfs-minipit1-6:pNFSpool3/p3DS2 1 63564 mds_ds_path_to_mds_sid:return mds_sid[3] = pnfs-minipit1-7:pNFSpool1/p1DS1 1 63564 mds_ds_path_to_mds_sid:return ERROR - could not find a matching pgi for pnfs-minipit1-7:pNFSpool1/p2DS1 1 56851 nfs41_spe_allocate:return No matching policy
So we did find a matching policy, but we only found 5 datasets and the policy requires 5. So, why isn't that dataset in memory?
[root@pnfs-minipit1-5 ~]> echo "::walk mds_DS_guid_entry_cache|::print struct rfs4_dbe dbe_data|::print ds_guid_info_t ds_dataset_name.utf8string_val|::eval /s" | mdb -k 0xffffff01e73e5fc0: pnfs-minipit1-6:pNFSpool3/p3DS2�����f 0xffffff01e7227078: pnfs-minipit1-6:pNFSpool3/p3DS1�����f 0xffffff01e7227120: pnfs-minipit1-6:pNFSpool2/p2DS2�����f 0xffffff01e72271c8: pnfs-minipit1-6:pNFSpool2/p2DS1�����f 0xffffff01e7227270: pnfs-minipit1-6:pNFSpool1/p1DS2�����f 0xffffff01e7227318: pnfs-minipit1-6:pNFSpool1/p1DS1�����f 0xffffff01e5d62e70: pnfs-minipit1-7:pNFSpool2/p2DS2�����f 0xffffff01e6597628: pnfs-minipit1-7:pNFSpool2/p2DS1�����f 0xffffff01e4e40468: pnfs-minipit1-7:pNFSpool1/p1DS2�����f 0xffffff01e5f84cb8: pnfs-minipit1-7:pNFSpool1/p1DS1�����f [root@pnfs-minipit1-5 ~]> echo "::walk mds_DS_guid_entry_cache|::print struct rfs4_dbe dbe_invalid" | mdb -k dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0 dbe_invalid = 0
Hmm, I need to figure out a better way to process UTF8 stings in mdb, but it appears to be there and in a valid entry. I couldn't figure this out until I lined up the dataset name output:
pnfs-minipit1-7:pNFSpool2/p2DS1 pnfs-minipit1-7:pNFSpool1/p2DS1
The naming convention shows the error, 'p2DS1' should be on pool #2, but it is on pool #1: pNFSpool1.
If this were implemented in SMF instead of a as a flat file, we would be able to do checking when we create the policy to catch this type of configuration error. But for now, DTrace and mdb can catch it.
For me, getting mdb to dump the dataset names was the hardest part. I had to experiment and search the web. I'm glad for all of the effort here, I'll use that trick again and again.
I added 3 new subdomains to my home network for testing. I added the records to my chroot'ed named at /var/named/chroot/var/named/named.conf. I just did reverse pointers and I couldn't get it to work:
[root@adept var]# host 192.168.4.120 Host 120.4.168.192.in-addr.arpa. not found: 3(NXDOMAIN)
I did this with a simple Perl script, so I debugged the heck out of it and checked for tabs galore. I finally added forward lookups, which worked:
[root@adept var]# host blast-4-120 blast-4-120.internal.excfb.com has address 192.168.4.120
Heck, I've been burnt by a bad link in /etc before, so I checked it:
[root@adept var]# ls -al /etc/named.conf lrwxrwxrwx 1 root named 21 2008-02-25 16:15 /etc/named.conf -> /var/named/named.conf [root@adept var]# ls -la /var/named/named.conf lrwxrwxrwx 1 root named 38 2008-02-25 16:24 /var/named/named.conf -> /var/named/chroot/var/named/named.conf
I even diff'ed them to be really, really sure. I ran named manually with '-g', fixed the warnings I got and then found out it didn't handle the chroot nicely. I looked at the init file and gave up on understanding it.
I couldn't find a log file for it, so I sent a SIGHUP to look for a database dump. I added logging to the config file and never saw any output. I never found that database dump.
But I did find an option that said where it should be:
dump-file "/var/named/data/cache_dump.db";
I then asked myself, is there another copy of the config file?
[root@adept var]# ps -ef | grep named named 4047 1 0 00:30 ? 00:00:00 /usr/sbin/named -u named -t /var/named/chroot root 4207 2886 0 01:00 pts/3 00:00:00 grep named [root@adept var]# cd /var [root@adept var]# find . -name named.conf ./named/named.conf ./named/chroot/etc/named.conf ./named/chroot/var/named/named.conf [root@adept var]# ls -la ./named/named.conf lrwxrwxrwx 1 root named 38 2008-02-25 16:24 ./named/named.conf -> /var/named/chroot/var/named/named.conf [root@adept var]# ls -la ./named/chroot/etc/named.conf -rw-r--r-- 1 root named 2741 2008-02-25 20:49 ./named/chroot/etc/named.conf
Why yes, yes there is and it doesn't have my new zones!
[root@adept etc]# pwd /var/named/chroot/etc [root@adept etc]# mv named.conf named.conf.fracked [root@adept etc]# ln -s ../var/named/named.conf . [root@adept etc]# ls -la ../var/named/named.conf -rw-r----- 1 root named 4920 2009-08-27 00:13 ../var/named/named.conf [root@adept etc]# service named restart Stopping named: [ OK ] Starting named: [ OK ] [root@adept etc]# [root@adept etc]# host 192.168.4.120 120.4.168.192.in-addr.arpa domain name pointer blast-4-120.internal.excfb.com.
Now what was I doing before I fell down this rat hole?.
So, my unit testing is all done and it is time to integrate. Bzzt! Wrong answer - we have to do regression testing. In our case, it is called pNFS/miniPIT and was mainly crafted by Helen Chao. And it was bombing on my new code.
First of all, the core was confusing:
[root@pnfs-minipit2-4 ~]> panic[cpu0]/thread=30008a61560: 000000047ad BAD TRAP: type=31 rp=2a100f596d0 addr=14 mmu_fsr=0 occurred in module "nfssrv" due to a NULL pointer dereference nfsd: trap type = 0x31 addr=0x14 pid=100528, pc=0x7afb3d64, sp=0x2a100f58f71, tstate=0x4414001604, context=0x29b g1-g7: 7be42af4, 2, 2000, 0, 0, 29b, 30008a61560
The NULL pointer wasn't anything to do with the function being called. Secondly, I focused on trying to reproduce it inside the test harness - it wasn't until I made a simple test case that I progressed.
Third, I focused on the server being 32 bit instead of the real difference - it was not setup as a MDS - therefore it had no DSes reporting to it. I'll show why that is important:
4463 error = nfs41_spe_allocate(&spe_va, claddr, 4464 vp->v_path, &lc, TRUE); 4465 if (error) { 4466 /\* 4467 \* XXX: Until we get the SMF code 4468 \* in place, we handle all errors by 4469 \* using the default layout of the 4470 \* old prototype code 4471 \* 4472 \* At that point, we should return the 4473 \* given error. 4474 \* 4475 \* XXX: Any way \*plo is NULL here? 4476 \*/ 4477 \*plo = mds_gen_default_layout(cs->instp); 4478 4479 /\* 4480 \* Record the layout, don't get bent out of shape 4481 \* if it fails, we'll try again at checkstate time. 4482 \*/ 4483 (void) mds_put_layout(\*plo, vp); 4484 4485 return (NFS4_OK); 4486 } 4487 4488 /\* 4489 \* XXX: Any way \*plo is NULL here? 4490 \*/ 4491 \*plo = mds_add_layout(&lc);
The fourth, and major problem, is that I had valid comments and I ignored them. Yes, it was certainly valid for the \*plo to be NULL after 4477 but probably not 4491. But they are both easy enough to code for!
The issue is that a NFSv4.1 server, i.e., no pNFS, also goes through this code path. We need to handle not having a layout:
4474 \* At that point, we should return the 4475 \* given error. 4476 \*/ 4477 \*plo = mds_gen_default_layout(cs->instp); 4478 if (\*plo == NULL) { 4479 status = NFS4ERR_LAYOUTUNAVAILABLE; 4480 } else { 4481 /\* 4482 \* Record the layout, don't get 4483 \* bent out of shape if it fails, 4484 \* we'll try again at checkstate time. 4485 \*/ 4486 (void) mds_put_layout(\*plo, vp); 4487 } 4488 4489 return (status);
Which appears okay, except with just this change, files will not be created. We want to return NFS4ERR_LAYOUTUNAVAILABLE, mainly for DTrace probing, but in the caller, we want to do:
4892 } else { 4893 status = mds_createfile_get_layout(req, vp, cs, &ct, plo); 4894 4895 /\* 4896 \* Allow mds_createfile_get_layout() to be verbose 4897 \* in what it presents as a status, but be aware 4898 \* that it is permissible to not generate a 4899 \* layout. 4900 \*/ 4901 if (status == NFS4ERR_LAYOUTUNAVAILABLE) { 4902 status = NFS4_OK; 4903 } 4904 }...
The code walk through in Austin was great for me - I ended up resolving all of my open issues and several bugs were found. I need to do another round of unit testing and then start running our regression test suite.
I also got some great help in putting the spe daemon into smf:
[root@pnfs-17-24 nfs]> svcadm enable svc:/network/nfs/spe [root@pnfs-17-24 nfs]> ps -ef | grep spe root 100882 100854 0 11:02:47 pts/1 0:00 grep spe root 100880 100004 0 11:02:30 ? 0:00 /usr/lib/nfs/sped
Not sure I have the dependencies right, but that may be because I have such a horribly hacked together test rig. I'll have to do a fresh install to make sure things start right the first time.
I'll be in Austin this week getting approval for the adoption of mds_sids to manage devices, layouts (in core and on disk), and file handles. Oh, and to add kspe!
For those of you interested, the code is over here:. I've removed the spe debug printfs and added DTRACE probes as appropriate.
On my todo list is to perhaps remove some debug DTrace probes (don't see a real need for in shipping code, kinda just kernel printfs) and to determine whether kspe lives in the nfs or nfssrv module. I made a half-hearted attempt to stuff it back into the nfs module and got reminded why I had it in nfssrv in the first place. I.e., need to get at mds_sid info and to abstract the kspe globals such that we aren't in the way of zonification. That last is the kicker - everything in the nfs module needs to know everything about kspe and it gets messy.
tdh | https://blogs.oracle.com/tdh/ | CC-MAIN-2015-27 | refinedweb | 5,312 | 65.32 |
Apr 27, 2007 11:07 AM|mark4asp|LINK
Suppose I wanted to handle errors outside of Global Application_Error() and put my code in a class in App_Code.
I have a call:Exception ex = Server.GetLastError();
But this class in App_Code clearly doesn't know what "Server" is in this context. How can I find the correct namespace to put in my using statements?
Is there a web-site where I can go to look-up namespaces? If not why not?
I seem to spend most of my time trying to figure out which using statements to include! - what a waste of time. It would be so useful to be able to narrow a search for method or class which returns the actual reference information and NOT hordes of tutorial articles repeating themselves. In other words Google is useless and msdn was of no help either! in finding this information.
Is there a way to search msdn2 - limiting the search to the reference information and ignoring the tutorials?
All-Star
26124 Points
Apr 27, 2007 01:03 PM|Haissam|LINK
You can get the Server object through HttpContext.Current
try
HttpContext.Current.Server
HttpContext.Current.Response.
HC
1 reply
Last post Apr 27, 2007 01:03 PM by Haissam | http://forums.asp.net/t/1104169.aspx | CC-MAIN-2015-18 | refinedweb | 208 | 67.04 |
Reflection in .NET 2.0 ships with a new class MethodBody, which "provides access
to information about the local variables and exception-handling clauses in a method
body, and to the Microsoft intermediate language (MSIL) that makes up the method
body". (Thanks to Glenn, who wrote
this in the MSDN doc; I simply copy & paste it). The only one method
inside this class (others are properties) is:
which returns us a byte array containing IL content for this method body.
Recently we got some questions related to reflecting IL stream: users want to check
where a specific method was used; or try to build a call graph inside an assembly;...
Reflection currently does not support this directly. Lutz Roeder's awesome tool
- .NET Reflector can indeed show
the call/callee graph for each method. I used to have the source code for his ILReader,
and noticed it did not use Reflection APIs (so for sure we can read IL without reflection
APIs)
A code sketch below shows how we can use classes in the Reflection/Emit namespace
(and other useful APIs provided in .NET 2.0) to read IL instructions.
Standard ECMA-335 is the authoritative resource to understand IL, MethodBody
format and other CLI topics if you want to know more of them.
Few comments here:
Then I can consume the ILInstruction sequence in C# as follows: | http://blogs.msdn.com/b/haibo_luo/archive/2005/10/04/476242.aspx | CC-MAIN-2013-48 | refinedweb | 228 | 67.99 |
...
Existing DSpace Java Style Guide
Per the Code Contribution Guidelines page (see "Coding Conventions" section), our existing style guide is listed as follows:
...
Because the Sun Java style guide is no longer maintained, it will not be keeping up with current Java style best practices, features, etc. We should consider whether we continue to base our style off this outdated guide, use a more modern guide, or develop our own guide.
...
Proposed DSpace Java Style Guide (work-in-progress - not yet approved)
Bolded rules are a change from our current Style Guide.
- 4-space indents for Java, and 2-space indents for XML. NO TABS ALLOWED.
K&R style braces
- Do not use wildcard imports (e.g.
import java.util.*)
-
Each source file must contain the required license header, e.g.
Other Java Style Guides
Google Java Style Guide
The Google Java Style Guide is at
... | https://wiki.duraspace.org/pages/diffpagesbyversion.action?pageId=90967266&selectedPageVersions=7&selectedPageVersions=6 | CC-MAIN-2018-13 | refinedweb | 146 | 72.87 |
How to Use the Raspberry Pi4 Camera And PIR Sensor to Send Emails
Introduction :
In this tutorial, I’ll show you how to send emails containing pictures using a Raspberry Pi4 and a motion detector and the Python programming language. We will use a PIR motion detection sensor and whenever motion is detected, the Raspberry Pi4 Camera will take a picture and send an email with the picture attached.
In this tutorial I divide this project some step if you flow this step with me I hope you can do this
Step-1:
You have to need some change in your google account flow this step
Login to your Gmail account by entering your login credentials.
Click on your profile picture and then click on “Google account”.
Under “Sign-in and Security” click “Connected apps and sites”.
Click “Allow less secure apps” to turn it on.(By Default its Turn off)
Step-2
Components Required
Circuit Diagram
The following Fritzing based images show all the connections with respect to the PIR Motion Sensor using Raspberry Pi4
Circuit Design:
Connect the VCC and GND pins of the PIR Motion Sensor to +5V and GND pins of the Raspberry Pi4. Connect the DATA Pin of the PIR Sensor to GPIO24 of the Raspberry Pi4.
A 5V Buzzer is connected to GPIO20 And Raspberry pi4 Camera Connect to the PI Connector Slot. The other pin of the buzzer connected to GND.
The Python Code to Send Emails
Before running the code, make sure the sender and receiver email addresses and the password of the email sender are all entered.
The code will read the output from the sensor and, upon detecting motion, will capture an image and save it on the database folder.
When you run the code for the first time, it will automatically create the folder. Once the camera captures an image, the image will be attached in the email and sent to the sender’s address.
import RPi.GPIO as GPIO import time import datetime import picamera import os import smtplib from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart camera = picamera.PiCamera() GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN) #PIR GPIO.setup(24, GPIO.OUT) #BUzzer ''' ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') ''' COMMASPACE = ', ' def Send_Email(image): sender = '###YOUREMAIL###' gmail_password = '###YOURPASSWORD###' recipients = ['##YOURRECIPENTEMAIL###'] # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = 'Attachment Test' outer['To'] = COMMASPACE.join(recipients) outer['From'] = sender outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' # List of attachments attachments = [image] # Add the attachments to the message for file in attachments: try: with open(file, 'rb') as fp: msg = MIMEBase('application', "octet-stream") msg.set_payload(fp.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) outer.attach(msg) except: print("Unable to open one of the attachments. Error: ", sys.exc_info()[0]) raise composed = outer.as_string() # Send the email try: with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.ehlo() s.login(sender, gmail_password) s.sendmail(sender, recipients, composed) s.close() print("Email sent!") except: print("Unable to send the email. Error: ", sys.exc_info()[0]) raise try: time.sleep(2) # to stabilize sensor while True: ##Timeloop ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') if GPIO.input(23): ##If loop GPIO.output(24, True) time.sleep(0.5) #Buzzer turns on for 0.5 sec print("Motion Detected at {}".format(st)) ##Adds timestamp to image camera.capture('image_Time_{}.jpg'.format(st)) image = ('image_Time_{}.jpg'.format(st)) Send_Email(image) time.sleep(2) GPIO.output(24, False) time.sleep(5) #to avoid multiple detection time.sleep(0.1) #loop delay, should be less than detection delay except: GPIO.cleanup() | https://maker.pro/raspberry-pi/projects/how-to-use-the-raspberry-pi4-camera-and-pir-sensor-to-send-emails | CC-MAIN-2020-40 | refinedweb | 641 | 51.75 |
As I said, this leads to a problem when the BPEL process has multiple
<provides/> tags, which is allowed.
IMHO, it seems the info we are really missing is a way to know, for a given
bpel process, the list of <provides/> and <consumes/> elements. If we can
retrieve this list at runtime, we could draw the link between the jbi
provider endpoint activated by Ode for the <provides/> element and the
partner link that is used when sending the JBI exchange.
Another way would be to activate an external endpoint to represent this
"consumer endpoint" and associate it with the EPR of the partnerlink /
myRole. But still, the relationship between the two JBI endpoints can't
really be known without an additional metadata.
On Dec 17, 2007 4:32 PM, Wielek, Lukasz <Lukasz.Wielek@sabre-holdings.com>
wrote:
> Alex,
>
> The string is in format:
> {service_namespace}Service:endpoint
>
> Example:
> The deploy.xml contains:
>
> <deploy xmlns=""
> xmlns:
> <process name="sws:Enhanced_AirBookProcess1.0.1">
> <in-memory>true</in-memory>
> <active>true</active>
>
> <provide partnerLink="Enhanced_AirBookRQPL">
> <service name="sws:Enhanced_AirBookRQ1.0.1" port="sws" />
> </provide>
>
> <invoke ....
> ...
>
> When some other service is invoked from bpel, the
> SENDER_ENDPOINT property value should be:
> {}Enhanced_AirBookRQ1.0.1:sws<>
>
>
>
> Regards,
> Lukasz Wielek
>
> -----Original Message-----
> From: Alex Boisvert [mailto:boisvert@intalio.com]
> Sent: Monday, December 17, 2007 3:50 PM
> To: dev@ode.apache.org
> Subject: Re: JbiConstants.SENDER_ENDPOINT property not set on MEX
>
> I think it's different than the correlationId case, which is meant to
> track
> the end-to-end processing of a given request.
>
> In this case, I was thinking about sending the partnerLink's myRole
> endpoint
> (if any). My only issue is the encoding of the endpoint as a String.
> I'm
> not sure how ServiceMix treats the String.
>
> What do you think?
>
> alex
>
>
> On 12/17/07, Guillaume Nodet <gnodet@gmail.com> wrote:
> >
> >
------------------------ | http://mail-archives.apache.org/mod_mbox/ode-dev/200712.mbox/%3Cb23ecedc0712170751w7b8abec3yf6ad8f05264c4ede@mail.gmail.com%3E | CC-MAIN-2016-07 | refinedweb | 309 | 58.08 |
Not only that, in developing this interface, there is no need to create any objects in the Integration Repository (IR). This means no mapping. Yes, if the data is not in XML, then no mapping can be done. So, we will only need to work in the Integration Directory (ID).
What can we do with this knowledge? Here are some examples:
- we can test adapters very easily and quickly without any IR development.
- we can send any formatted data without having to convert it to XML and back again, e.g. file->XI->file.
- we can send any document from 1 sender to multiple receivers using XI to guarantee delivery.
Here are the steps required: (some steps will not contain any details because they are no different than developing for any other XI interfaces)
- Configure sender and receiver communication channels in a Business Service or System, as usual.
- Create a Receiver Determination:
- The Service has to be a valid business service or system in the ID.
- Interface name can be anything you make up, but should be unique. In this case, it is “nonexistence_interface”.
- Namespace name can be anything you make up or already exists. In this case, it is ““.
- The following is created:
Enter a valid service for the Receiver and save.
- Create Interface Determination:
- Use the same Interface name as the sender.
- Use the same Namespace name as the sender.
- Do NOT enter any Interface Mapping.
- Create Sender and Receiver Agreements as usual.
The interface is now ready to be activated and executed. Once executed, you can examine the content of the payload in SXMB_MONI. It will contain whatever the data you sent, but you will also receive an error indicating that the message is not XML (which can be ignored).
The main points of this exercise is:
- IR is not necessary for development of interfaces in XI.
- In ID, any name can be used for Sender Interface and Namespace names, and they do not need to exist in IR.
- No Mapping can be used, since the data may not be XML.
- The Receiver Interface and Namespace names must match that of the Sender Interface and Namespace names.
- Most importantly: the data sent thru XI does NOT have to be in XML; any data can be sent thru XI.
XI in the role of a FTP
in case you need to pass a binary (or not)
file with a large size it really is not a good
idea to push through the XI with this approach
big files (many Mb) should be copied (java proxy)
and not pushed via XI I believe
example
– copying 150 Mb file (to another FTP on the same local network) with a java proxy – a few minutes
– via XI (even withoout any IR objects) … I don’t wanna know 🙂
do you agree ? 🙂
Regards,
michal
I think you are talking about using file copy through java proxy. The file destination details may be looked up using channel lookup right?
cheers,
sachin.
no as you don’t use a file channel (adapter)
Regards,
michal
Yes, sending any large message via the file adapter will result in some performance problems, depending on the file size.
Regards,
Bill
Just wondering what is the benefit of using a java proxy to perform the ftp of your large file? Why not just leave XI out of it altogether and let the application that creates the file perform the ftp? I’m trying to work out what benefit using XI gives in this scenario.
We have the issue that the legacy SAP system download huge files (10MB and even up to 300MB) and ftp’s them to a file server. Our XI instance simply cannot handle these messages! Should we just let the abap program that downloads the files also perform the ftp or should we use XI to do the ftp using a proxy as Michal suggests?
In your case, it probably makes sense to FTP from the source system, instead of using XI. Your interface, I assume, involves File/FTP to File/FTP, without any mapping. Using XI does not present any benefits.
XI should be considered if one of the following is true:
1. mapping is required
2. multiple destinations are required
3. different types of adapters are used for sender and receiver (e.g. File -> JMS)
4. BPM is require
Regards,
Bill
In my case I have binary input data which might be sent as you described, but I want to map this to an existing interface which works with XML. Could I put a java mapping in between that converts my binary stream to an XML and hands it over to the inbound interface?
To do mapping, Integration Repository (IR) objects will be required, e.g. data type, msg type, msg interface, interface mapping.
As for sending a non-XML msg and using java mapping, as you described, it is fine. But, you will still need to have all the required IR objects.
Regards,
Bill
I ve tried step by step as instructed in the Blog, but
1)I am not getting any Error Message that message is not XML.
2)Everything OK in SXMB_MONI, but the receiver Adapter is not bale to Create the Output File, nad indefinitely the Status is “To Be Delivered” and it is not resulting in an Error.
Please guide
Looks like everything executed as expected. You will not get an XML error in SXMB_MONI.
The problem you received is unrelated to your configuration. It is possible the msgs in the queue is being held up. Pls check the queues to resolve problem.
Regards,
Bill.
You can simply use different names and namespaces for the interfaces:
DummyInterface_out
DummyInterface_in
Hope you don’t mind about my question here. We are trying this method to send a PDF file to MQ via Receiver JMS adapter but MQ team is not able to receive it as PDF.
I hope you can find some time to reply in my thread.. File to JMS without using IR
Thanks,
Sarvesh | https://blogs.sap.com/2006/09/08/how-to-send-any-data-even-binary-through-xi-without-using-the-integration-repository/ | CC-MAIN-2018-43 | refinedweb | 1,004 | 72.16 |
0
Hi there;
I am having problems with using printf method in this simple loop. I am looking for a 3 decimal places in the right one column and a integers in the left. I know how to print this with system.out.println but I dont know how to write it with printf with given conditions.
Can anybody help or give me a link with good and usefull explanation ?
thanks in advance...
public class fourdot3 { public static void main(String[] args) { double gram = 1; double pound = 0.035; for (gram = 1; gram <=199; gram++) { System.out.println(gram + "\t"+ (gram * pound)); } } } | https://www.daniweb.com/programming/software-development/threads/394931/printf-with-loop-problem | CC-MAIN-2017-39 | refinedweb | 102 | 77.64 |
Since I have been talking about Java vs. Ruby, I figured I would give a recent example of where Ruby really solved my problems simply and easily. My company uses SalesForce.com for their CRM solution. Our sales, finance, and fulfillment teams have logins that are maintained and managed through the website. This is a pain for both the users and our IT team as people now have to remember their SalesForce username and password as well as their internal user name and password.
To combat this problem, SalesForce has created a method that allows authentication of users via a SOAP request. Very cool, solves the problem, so I signed up to implement it. SalesForce supplies a WSDL documenting the services that need to be supported and you supply the URL that implements the defined services. Should be simple to connect to our ActiveDirectory server using LDAP to perform the validation of users.
The Initial Attempt: Using Java Web Services…
Our standard development environment is Java 5, Maven 2 for builds, Apache 2 for HTTP(S), and JBoss 4.0.5 as an application server. I thought it would be a simple exercise to use JAX-WS combined with JAX-WS Maven Plugin for auto-generation of my stubs and the JBoss WS to simply deploy. First problem was getting the Maven plugin working correctly. After some trial and error, I got my POM setup correctly and was deploying the EAR. Unfortunately, I realized that JBoss was assuming that Tomcat was running on port 8080, causing a problem in the WSDL that was being referenced. So I had to find the JBoss property to tweak to fix that. Next problem wound up being that the default org.jboss.ws.soap.SOAPMessageImpl did not implement the setProperty method causing an UnsupportedOperationException. Awesome. To try to fix that issue, I wound up trying the following (in different combinations):
- Upgrading JBoss to 4.2.1.
- Upgrading JBoss WS to 2.0 with JBoss 4.2.1
- Trying Java 6 as JAX-WS is in the standard JDK with both JBoss 4.0.5 and JBoss 4.2.1
With all of these combinations, I kept running into class loading issues and little help on the web. After much frustration, I said to hell with this, how can I do it in ruby….
SOAP4R to the rescue
SOAP4R is the best know SOAP library for ruby and the gem is easily installed
> gem install soap4r –source
Now I could auto-generate my stubs from the WSDL and put in my business logic.
Generating Stubs from the WSDL
In general, the documentation for soap4r is non-helpful, but by looking at the source code and googling around a bit, I was able to get the gist. From the supplied SalesForce WSDL, I was able to quickly generate my stubs:
require ‘rubygems’
gem ‘soap4r’
require ‘wsdl/soap/wsdl2ruby’
DIR = File.dirname(“.”)
gen = WSDL::SOAP::WSDL2Ruby.new
gen.basedir=File.dirname(DIR)
gen.location=File.join(DIR,”AuthenticationService.wsdl”)
gen.logger.level=Logger::DEBUG
gen.opt['classdef'] = “SforceAuth”
gen.opt['client_skelton'] = nil
gen.opt['servant_skelton'] = nil
gen.opt['cgi_stub'] = nil
gen.opt['standalone_server_stub'] = nil
gen.opt['mapping_registry'] = nil
gen.opt['driver'] = nil
gen.opt['force'] = true
gen.run
Running this produces seven files:
Customizing the Generated Ruby Files to Get A Working System
Of the seven files created, I needed three of them (the client, the standalone server, and the CGI script) needed to be executable. To get them to run, I needed to set the executable flag:
> chmod +x SforceAuthenticationService.rb SforceAuthenticationService.cgi SforceAuthenticationServiceClient.rb
In addition, because I am using Ruby Gems to manage my dependencies, I needed to add the following two lines to the top of each of these three files:
require ‘rubygems’
gem ‘soap4r
To test the implementation, I started up the standalone authentication server (which listens on port 10080 by default) and called it from the client.
> SforceAuthenticationService.rb &
> SforceAuthenticationServiceClient.rb
If all is working, you will get a NoMethodError exception being thrown. To remedy this problem edit the SforceAuthServant.rb file and on line 15, change the line from raise NotImplementedError.new to {:authenticated => true}. Restarting the standalone server and rerunning the client will result in success.
Now, I just needed to implement the code to call the LDAP server. First step was obtaining and installing the Gem for the Ruby net-ldap project. Validating the username and password was as simple as putting this code into authenticate method for the SforceAuthServant class:
def authenticate(parameters)
ldap = Net::LDAP.new
ldap.host = “ldap.hmsonline.com”
ldap.auth parameters.username[0], parameters.password[0]
if ldap.bind_as(
:base => “dc=com”,
:filter => “(sAMAccountName=”+parameters.username[0]+”)”,
)
return {:authenticated=>true}
else
return {:authenticated=>false}
end
end
Again, restarting the standalone server and using the client (with some tweaks to send the right parameters over) validated that the service was working successfully.
Configuring Apache to use the CGI
Obviously, I want SalesForce to use HTTPS when sending usernames and passwords. We use
Apache as our web server for SSL. To get the CGI set up, I made sure that the directory with the files was accessible from the Apache configuration and then added a .htaccess file
Options +ExecCGI
AddHandler cgi-script .cgi
Restarted Apache and I was done. The whole exercise took about an hour, and that was with me figuring out what was going on. The soap4r team has done a great job making setting up and and deploying a SOAP service quick, powerful, and easy to manage.
[...] rob_dimarco via innovationontherun.com Submitted: Aug 02 / 10:30 Using Ruby, SOAP, and Apache to implement SSO for SalesForce.com A walk through example of how to use Ruby’s SOAP4R library and the SalesForce.com SSO service to [...]
[...] Using Ruby, SOAP, and Apache to implement SSO for SalesForce.com | Innovation On The Run on 26 Jul 2007 at 12:00 pm […] I have been talking about Java vs. Ruby, I figured I would [...]
[...] to take this approach with this module.While researching for a Ruby SOAP library, I came across this post describing an integration with SalesForce.com.I’ve heard a lot about SalesForce.com and knew it was [...] | http://www.innovationontherun.com/using-ruby-soap-and-apache-to-implement-sso-for-salesforcecom/ | CC-MAIN-2014-41 | refinedweb | 1,036 | 57.67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.