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
Lesson 4 - Introducing destructors and more about constructors in C++ In the previous lesson, A RollingDie in C++ and Constructors, we described the constructor syntax, including advanced constructs such as the delegating constructor and invoking constructors for attributes. Today, we're going to describe destructors and show the main purpose for which constructors and destructors are used. Destructors Like the constructor that is called immediately after the instance is created, the destructor is called automatically before the instance is deleted. The instance is usually deleted at the end of the block (that is, the end of the function or the closing brace }). We write the destructor as a method that starts with a tilda ( ~) followed by the class name. The destructor never has parameters and does not return a value. Such a basic destructor has already been generated by Visual Studio for us and is empty (if we don't provide a custom destructor, the compiler will create a destructor with an empty body automatically): RollingDie.h class RollingDie { public: RollingDie(); RollingDie(int _sides_count); ~RollingDie(); // destructor declaration int sides_count; }; RollingDie.cpp RollingDie::~RollingDie() // empty destructor { } To see when the destructor is called, we'll print to the console in it: #include <iostream> // if missing using namespace std; // if missing RollingDie::~RollingDie() { cout << "Calling the destructor for the die with " << sides_count << " sides" << endl; } In main.cpp, we'll put the following code, which shows the cases when the destructor is called. void function(RollingDie die) { cout << "Function" << endl; } int main() { RollingDie first(1); if (true) { RollingDie second(2); function(second); cout << "Function finished" << endl; } // cin.get(); return 0; } We see the logs in the application output: Console application Parametric constructor called Parametric constructor called Function Calling the destructor for the die with 2 sides Function finished Calling the destructor for the die with 1 sides When we analyze the example, we find that the destructor is called before the closing curly braces and at the end of the function. That's when the variable is no longer needed and C++ will remove it from memory. For a better understanding, let's add comments to the code as well: void function(RollingDie die) { cout << "Function" << endl; } // die's destructor called int main() { RollingDie first(1); // first constructor if (true) { RollingDie second(2); // second constructor function(second); cout << "Function finished" << endl; } // second's destructor // cin.get(); if we keep this call, we won't see the the first die being deleted return 0; } // first's destructor called Constructors calls are also printed because we left the code from the previous lesson. You might be surprised that three destructors are called, but only two constructors. In one case, the copying constructor is called, but we'll deal with it in another lesson. For now, we just need to know when the destructor is called. Constructors for initialization Now let's look at one case where constructors are useful - class initialization. Let's define a roll() method in the RollingDie that returns a random number from 1 to the number of sides. It's very simple, the method will have no parameter and the return value will be int. To get a random number, we call the rand() function from the cstdlib library. RollingDie.h #ifndef __ROLLINGDIE_H__ #define __ROLLINGDIE_H__ class RollingDie { public: RollingDie(); RollingDie(int _sides_count); ~RollingDie(); int roll(); int sides_count; }; #endif RollingDie.cpp #include <iostream> #include <cstdlib> #include "RollingDie.h" using namespace std; // ... already defined methods int RollingDie::roll() { return rand() % sides_count + 1; } rand () returns a pseudo random number. To be within the required range, we need to use % sides_count + 1. The number 1 is added to make the random numbers from one and not zero. A pseudo-random number means that it starts with some number and next numbers are calculated by some operation with the initial number. This approach has one disadvantage - put the following code into main.cpp (you can delete the original one): #include <iostream> #include "RollingDie.h" #include "Arena.h" using namespace std; int main() { RollingDie die; for (int i = 0; i < 10; i++) cout << die.roll() << " "; cin.get(); return 0; } Note that if we run the program several times, it always generates the same numbers (even though it should generate them randomly). This is because the initial number is always the same. We need to start with a different number every time we run the program. We'll do it using the srand() method and passing the current time to it. And because it actually initializes the instance, we'll put that code into the constructor. Note: In addition to the cstdlib library, the ctime library must also be included. RollingDie::RollingDie(int _sides_count) { cout << "Parametric constructor called" << endl; sides_count = _sides_count; srand(time(NULL)); } Now the rolling die always generates different numbers and we are done. Using Constructors for Memory Management The second case where we can use the constructor (and the destructor) is memory management. Since constructors and destructors are called automatically, we are sure that the code is always executed. So we can allocate memory in the constructor and delete it in the destructor. Let's take our arena as an example, where there are currently two warriors. Let's say we want to enter the number of warriors as a parameter - so we must create an array of the warriors dynamically. Edit the Arena.h file as follows: #ifndef __ARENA_H_ #define __ARENA_H_ #include "Player.h" class Arena { public: Player** players; int players_count; Arena(int _players_count); // the parameter name has been changed ~Arena(); }; #endif Don't be scared of the two asterisks - it's an array of pointers to Player (we cannot create only an array of players because we don't have the default = parameterless constructor which is needed for that). We allocate this array in the constructor, and we ask for the names according to the number of players. Then, in the destructor, we perform the opposite operation and delete everything. Let's see the code: Arena.cpp #include <iostream> #include "Arena.h" using namespace std; Arena::Arena(int _players_count) { players_count = _players_count; // storing the player count players = new Player*[players_count]; // creating an array for the players for (int i = 0; i < players_count; i++) { string name; cout << "Enter a player name: "; cin >> name; players[i] = new Player(name); // creating the player } } Arena::~Arena() { for (int i = 0; i < players_count; i++) delete players[i]; // deleting the players delete[] players; // deleting the array players = NULL; } If we did not delete the memory, it'd remain allocated and we wouldn't be able to access it anyhow (there would be no pointer to it) and it would also be impossible to delete it later. For example, if we were creating instances in a loop, then the program would start to consume more and more RAM until it'd take it all (and having a gigabyte of RAM for that small application is rather strange). If there's no free RAM memory and the program asks for more memory, the operating system no longer has anything to allocate and will terminate the application. Therefore, if you find your application crashing after some time, try to check how much memory space it takes and if this space is constantly growing, you may not be freeing memory somewhere, causing a memory leak. main.cpp So we have finished our arena and can use it in main.cpp: #include <iostream> #include "RollingDie.h" #include "Arena.h" using namespace std; int main() { RollingDie die; for (int i = 0; i < 10; i++) cout << die.roll() << " "; cout << endl; Arena arena(4); cin.get(); return 0; } The result: Console application Parametric constructor called Parameterless constructor called 2 6 1 2 1 6 2 3 1 4 Enter a player name: Paul Enter a player name: Carl Enter a player name: George Enter a player name: Lucas Calling the destructor for the die with 6 sides Everything works like a charm. Allocating and freeing memory is the most common thing that happens in constructors and destructors, so I suggest you take a good look at the last example to understand how it works. That's all for this lesson. The next time, The this pointer in C++, we'll remove those nasty parameter names starting with underscores. The source code of today's lesson is attached for download below the article as always. Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily. DownloadBy downloading the following file, you agree to the license terms Downloaded 1x (964.38 kB) Application includes source codes in language C++ No one has commented yet - be the first!
https://www.ictdemy.com/cplusplus/oop/introducing-destructors-and-more-about-constructors-in-cplusplus
CC-MAIN-2021-31
refinedweb
1,441
60.24
The problem Shortest Completing Word Leetcode Solution states that you are given a license plate and an array of os strings. You need to find the shortest completing word. A competing word is defined as a word that has all the alphabets in the license plate (case insensitive). The frequency of letters in completing word can be greater than the frequency of letters in the license plate but it can not be less. So, you need to find the shortest completing word among the array of strings. So, let’s take a look at a few examples. licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"] "steps" Explanation: The word given in the license plate has 2 s and 1 t. The word from the array is “step” which has only a single one. Thus “step” is not a completing word. But, “steps” has 2 s, 1 t, and other letters. The word “steps” satisfies the condition to be a completing word. And it is also the shortest completing word. Thus, it is returned as an answer. licensePlate = "1s3 456", words = ["looks","pest","stew","show"] "pest" Explanation: All the words from the array are completing words. But the last 3 words are the shortest completing words. Among the shortest completing words, we return the first shortest completing word that is “pest”. Approach for Shortest Completing Word Leetcode Solution The problem Shortest Completing Word Leetcode Solution asked us to find the shortest completing word. We have already specified what a completing word is, in the description of the problem statement. So, to find the shortest completing word. First, we have to find the frequency of the letters on the license plate. This frequency is insensitive of the case of the letter. Then we traverse over the array of strings. And once again we perform the same operation of finding the frequency of letters. Then we check if the current word is a completing word. If it is and the size of the current word is smaller than the previous completing word, we update the answer. In the end, we return the shortest completing word. Code C++ code for Shortest Completing Word Leetcode Solution #include<bits/stdc++.h> using namespace std; string shortestCompletingWord(string licensePlate, vector<string>& words) { unordered_map<char, int> m; for(auto x: licensePlate){ if((x>='A' && x<='Z') || (x>='a' && x<='z')) m[tolower(x)]++; } string answer = string(16, 'a'); for(auto word: words){ unordered_map<char, int> mm; for(auto x: word){ if((x>='A' && x<='Z') || (x>='a' && x<='z')) mm[tolower(x)]++; } bool cant = false; for(char i='a';i<='z';i++) if(mm[i] < m[i]) cant = true; if(!cant){ if(word.length() < answer.length()) answer = word; } } return answer; } int main(){ string licensePlate = "1s3 PSt"; vector<string> words({"step","steps","stripe","stepple"}); cout<<shortestCompletingWord(licensePlate, words); } steps Java code for Shortest Completing Word Leetcode Solution import java.util.*; import java.lang.*; import java.io.*; class Main { public static String shortestCompletingWord(String licensePlate, String[] words) { HashMap <Character, Integer> m = new HashMap<Character, Integer>(); int licensePlateSize = licensePlate.length(); for(int i=0;i<licensePlateSize;i++){ char x = licensePlate.charAt(i); if((x>='A' && x<='Z') || (x>='a' && x<='z')) m.put(Character.toLowerCase(x), m.containsKey(Character.toLowerCase(x)) ? (m.get(Character.toLowerCase(x)) + 1) : 1); } String answer = "aaaaaaaaaaaaaaaa"; for(String word: words){ HashMap<Character, Integer> mm = new HashMap<Character, Integer>(); int wordSize = word.length(); for(int i=0;i<wordSize;i++){ char x = word.charAt(i); if((x>='A' && x<='Z') || (x>='a' && x<='z')) mm.put(Character.toLowerCase(x), mm.containsKey(Character.toLowerCase(x)) ? (mm.get(Character.toLowerCase(x)) + 1) : 1); } boolean cant = false; for(char i='a';i<='z';i++){ int a = m.containsKey(i) ? m.get(i) : 0; int b = mm.containsKey(i) ? mm.get(i) : 0; if(b < a) cant = true; } if(cant == false){ if(word.length() < answer.length()) answer = word; } } return answer; } public static void main (String[] args) throws java.lang.Exception{ String licensePlate = "1s3 PSt"; String words[] = {"step","steps","stripe","stepple"}; System.out.print(shortestCompletingWord(licensePlate, words)); } } steps Complexity Analysis Time Complexity O(N), where N is the number of words in the array of strings. Thus the entire algorithm has linear time complexity. Space Complexity O(1), since we use two HashMaps of constant size. The space complexity for the entire algorithm is constant.
https://www.tutorialcup.com/leetcode-solutions/shortest-completing-word-leetcode-solution.htm
CC-MAIN-2021-31
refinedweb
723
57.98
Home -> Community -> Mailing Lists -> Oracle-L -> RE: library cache lock Sami Processes are not currently waiting, when you ran this SQL. Please see the state : waited short time.. Only if the state is WAITING, then the sessions are actually waiting for that specific event. This is the same reason why x$kgllk and systemstate did not give you any information. You can also see the systemstate tells 'last wait for library cache lock'. If the sessions are waiting, then you will see lines like 'waiting for library cache lock..' etc. You need to run these statements, while the sessions are truly WAITING. Thanks Riyaj "Re-yas" Shamsudeen Certified Oracle DBA (ver 7.0 - 9i) Adjunct faculty El Centro College* Dallas Oracle User Group board member <> From: Sami Seerangan [mailto:dba.orcl_at_gmail.com] Sent: Monday, April 04, 2005 9:15 PM To: rshamsud_at_jcpenney.com Cc: oracle-l_at_freelists.org Subject: Re: library cache lock Hi Riyaj Thanks for your response. I did do systemstat and ran your query too. Select * from gv$session_wait where event='library cache lock'; 1 237 165 library cache lock handle address 3285451564 C3D4032C lock address 3188447124 BE0BD794 10*mode+namespace 31 0000001F -1 13812 237 689 19837 17691 PROCESS 689: int error: 0, call error: 0, sess error: 0, txn error 0 (post info) last post received: 0 0 0 last post received-location: No post last process to post me: de136c54 1 2 last post sent: 42061 0 13 last post sent-location: ksasnd last process posted by me: de13c680 1 2(latch info) wait_event=0 bits=0 SO: de70da54, type: 3, owner: de1bbe40, pt: 0, flag: INIT/-/-/0x00 (session) trans: 0, creator: de1bbe40, flag: (41) USR/- BSY/-/-/-/-/- DID: 0000-0000-00000000, short-term DID: 0000-0000-00000000 txn branch: 0 oct: 3, prv: 0, user: 84/HIBM_TAXONOMY O/S info: user: atg, term: , ospid: 17998, machine: njprdcsmcts05 program: java_at_njprdcsmcts05 (TNS V1-V3)last wait for 'library cache lock' blocking sess=0x0 seq=165 wait_time=-1 handle address=c3d4032c, lock address=be0bd794, 10*mode+namespace=1f ---------------------------------------- SO: bf71ea90, type: 36, owner: de70da54, flag: INIT/-/-/0x00 LIBRARY OBJECT PIN: pin=bf71ea90 handle=c11b3134 mode=S lock=bef2abdc user=de70da54 session=de70da54 count=1 mask=0041 savepoint=11 flags=[00] ---------------------------------------- SO: bef2abdc, type: 35, owner: de70da54, flag: INIT/-/-/0x00 LIBRARY OBJECT LOCK: lock=bef2abdc handle=c11b3134 mode=N call pin=0 session pin=bf71ea90 user=de70da54 session=de70da54 count=1 flags=BRO/PNS/[09] savepoint=10 LIBRARY OBJECT HANDLE: handle=c11b3134 >>>> handle address=c3d4032c, Using the above 'handle address' I did look up the process that is keeping a lock on my resource by doing a search on the address within the same tracefile. But I couldn't find any. The sql you gave me {select ses.sid, ses.serial#,lck.* from x$kgllk lck , v$session ses where kgllkhdl in (select kgllkhdl from x$kgllk where kgllkreq >0) and lck.KGLLKUSE = ses.saddr Order by lck.KGLNAOBJ} also returned no rows. I have 5 such session waiting for 'library cache lock'. All of them are in similar situation. Could someone through some light on this. On Apr 4, 2005 11:58 AM, Riyaj Shamsudeen <rshamsud_at_jcpenney.com> wrote: Sami Find why that session is holding the library cache lock. Following SQL will give you a map of sessions waiting and holding library cache locks. Mon Apr 04 2005 - 23:11:24 CDT Original text of this message
http://www.orafaq.com/maillist/oracle-l/2005/04/04/0098.htm
CC-MAIN-2015-06
refinedweb
569
60.75
Here I am trying to create a vector of 5 SavingsAccount objects. Each SavingsAccount has a balance, which the user inputs. My problem is that when I print out the balance, the value of each balance equals whatever was entered last. For example, user inputs 100, 200, 300, etc, my program outputs all 500s instead of each entered balance. I know there's probably a really simple explanation for this, but I seem to be running out of gas today. My guess is that when I call accounts.push_back, I'm assigning the same object to each element of the vector so that on the last run of the for loop, I'm assigning 5 objects with a balance of 500 into the vector. If that's the case, I'm not entirely sure how to fix that. Any suggestions, or do I have another problem somewhere? Thanks in advance. #include <iostream> #include <iomanip> #include <vector> #include "SavingsAccount.h" // SavingsAccount class definition using namespace std; void initializeAccounts(vector<SavingsAccount> &, int); int main() { //Number of accounts const int NUM_OF_ACCOUNTS = 5; //Create vector vector <SavingsAccount> accounts(NUM_OF_ACCOUNTS); //Initialize all 5 vectors with input from user initializeAccounts(accounts, NUM_OF_ACCOUNTS); //Print out the balances for(int i = 0; i < NUM_OF_ACCOUNTS; i++) { accounts[i].printBalance(); } void initializeAccounts(vector<SavingsAccount> &accounts, int accountSize) { double balance = 0; for(int i = 0; i < accountSize; i++) { cout << "Please enter the balance for account " << i+1 << endl; cin >> balance; accounts.push_back(SavingsAccount(balance)); } } you already set the size of your vector with NUM_OF_ACCOUNTS elements: vector <SavingsAccount> accounts(NUM_OF_ACCOUNTS); So when you later push_back further elements in your initialize method, it adds to the already existing (empty elements) BTW you pass the size of the vector whereas it is self-contained. But that's another story. Simple fix: declare vector as empty at the start: vector <SavingsAccount> accounts;
https://codedump.io/share/QvGCGnxSwoWt/1/c-last-object-of-my-vector-is-overwriting-every-object
CC-MAIN-2017-26
refinedweb
307
53.51
unity.scopes.Object The root base class for all proxies. More... #include <unity/scopes/Object.h> Inheritance diagram for unity::scopes::Object: Detailed Description The root base class for all proxies. Member Function Documentation Returns the endpoint this proxy connects to. - Returns - The endpoint of the proxy. Returns the identity of the target object of this proxy. - Returns - The identity of the target of the proxy. Returns the category of the target object of this proxy. - Returns - The category of the target of the proxy. Returns the timeout in milliseconds if this proxy is a twoway proxy. For oneway proxies and twoway proxies without a timeout, the return value is -1. - Returns - The timeout value in milliseconds (-1 if none or timeout does not apply). Converts a proxy into its string representation. A proxy string can be converted back into a proxy by calling Runtime::string_to_proxy(). - Returns - The string representation of the proxy.
https://phone.docs.ubuntu.com/en/scopes/api-cpp-development/unity.scopes.Object
CC-MAIN-2020-45
refinedweb
153
60.92
(see section The print statement) on a line by itself. (Expression statements yielding None are not written,). print_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" a whitespace character except ' ',. by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.”. Note In Python 2.2, the yield statement was only allowed when the generators feature has been enabled. This __future__ import statement was used to enable the feature: from __future__ import generators raise_stmt ::= "raise" [expression ["," expression ["," The standard type hierarchy), 2.6 are unicode_literals, print_function, absolute_import, division, generators, nested_scopes and with_statement. generators, with_statement, nested_scopes are redundant in Python version 2.6 and above" or_expr [). [1] If it is an open file, the file is parsed until EOF and executed. If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see section File input). Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec statement. In all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Changed in version 2.4: Formerly, locals was required to be a dictionary.. Footnotes
http://docs.python.org/reference/simple_stmts.html
crawl-002
refinedweb
259
59.19
Hello, I'm digging out this thread again. I'm trying to run python scripts from C# using the DLR. Simple examples work, namely if I have just one function in one python file. How does it work when one python file imports from another python file? I get "No module named x" ImportExceptions when trying to compile these python files. I compile the main-file with 'CreateScriptSourceFromFile'. May be I am using the wrong approach in general. What I have is a bunch of python files that I used with CPython directly so far. Now I want to extend my program with C# (since database handling is much more convenient there) and I want to use the python files that I already have. What is the best approach for this scenario? Thanks for any kind of hint. Severin On Tue, Jan 20, 2009 at 5:37 PM, Michael Foord <fuzzyman at voidspace.org.uk>wrote: > Renaud Durand wrote: > >> Ok, Thank you. >> >> Does anyone know where could I find an IronPython Assembly documentation >> and/or up to date tutorials ? >> > > These tutorials are up to date - except for the one specified as being for > IP1: > > > > Michael > >> >> Thank you again. >> >> 2009/1/20 Curt Hagenlocher <curt at hagenlocher.org <mailto: >> curt at hagenlocher.org>> >> >> I believe this was valid for a long-ago alpha. For the 2.0 >> release, you'll want to create an engine by saying >> engine = Python.CreateEngine() >> >> On Tue, Jan 20, 2009 at 7:32 AM, Renaud Durand <renaud.durand.it >> <>@gmail.com <>> wrote: >> >> Hi, >> >> I want to use IronPython function through C#. To do It, I >> found a tutorial at >>. >> But the code does not seem to be updated for IronPython 2.0. >> >> the code is : >> >> using System; >> using IronPython.Hosting; >> using IronPython.Runtime; >> using Microsoft.Scripting; >> using Microsoft.Scripting.Hosting; >> >> namespace EmbeddedCalculator >> { >> public class Engine >> { >> private ScriptEngine engine; >> >> public Engine() >> { >> engine = PythonEngine.CurrentEngine; >> } >> >> public string calculate(string input) >> { >> try >> { >> ScriptSource source = >> engine.CreateScriptSourceFromString(input, "py"); >> return source.Execute().ToString(); >> } >> catch >> { >> return "Error"; >> } >> } >> >> } >> } >> // End of code >> >> When I try to compile it in visual studio, the compiler could >> not find the name "PythonEngine". I have added all the >> references to >> the needed libraries. So, what am I missing ? >> >> >> Thank you :-). >> >> -- Renaud Durand >> >> _______________________________________________ >> Users mailing list >> Users at lists.ironpython.com <mailto:Users at lists.ironpython.com> >> >> >> >> >> _______________________________________________ >> Users mailing list >> Users at lists.ironpython.com <mailto:Users at lists.ironpython.com> >> >> >> >> >> >> -- >> Renaud Durand >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Users mailing list >> Users at lists.ironpython.com >> >> >> > > > -- > > > > > > _______________________________________________ > Users mailing list > Users at lists.ironpython.com > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/ironpython-users/2009-January/009585.html
CC-MAIN-2014-15
refinedweb
433
70.39
I'm looking for a way to map a row of the following table with the following object : create table Foo ( Id BIGINT IDENTITY (1, 1) NOT NULL, A int, ACertainty float, B string, BCertainty float .... ) public class FuzzyValue<T>{ public T Value { get; private set; } public double Certainty { get; private set; } } class Foo { public FuzzyValue<int> A { get; set;} public FuzzyValue<string> B { get; set;} ... } Obviously, I can have dapper return a dynamic and do the mapping manually, but this manual tedious work kind of defeats the purpose of dapper, doesn't it? Is there an easy way to have dapper do the mapping automatically? I ended up writing a not so trivial mapper to do this. If someone needs it, the source is here and there's a nuget package available here
https://dapper-tutorial.net/knowledge-base/31772558/how-to-map-a-dapper-row-with-a--net-object-having-a-different--nested--structure
CC-MAIN-2021-25
refinedweb
134
58.32
This action might not be possible to undo. Are you sure you want to continue? v ,*? Counselors to America's Smali Brrsiness SCORE. il#h/rpAh'y CORPORATION'' www. incorp or ate.com/score2 ------."".-..-.".__THE-".-._ n#MpAlqY CORPORATION Dear Business Owner, Congratulations on taking your first step toward starting your own business! We hope we can help you achieve your American dream. As a dedicated partner to thousands of small businesses across the United states, The company corporation invites you to read the following information on starting a business. small businesses provide the foundation for our country's economic growth. We want to assist you by providing the products and services you need to succeed. The Company Corporation and SCORE have partnered to bring you this workbook written by the editors of lnc. magazine. The workbook provides information about topics ranging from your inspiration for starting a business to creating a plan, building a team, and investing in technology. lt also focuses on cash control, financlal management, selecting a business structure, and capitalizing on the Web. We're honored to provide this educational tool for use by SCORE counselors and their clients. SCORE counselors volunteer their time and expertise to help small businesses with confidential, free business counseling' The SCORE Association has helped more than 7.8 million small business clients since 1964' The company corporation has helped more than 300,000 small business owners just like you to incorporate or form Limited Liability companies (LLCs)' we provide a range of products and services including business licenses, corporate kits, self-help books, certificates of good standing, and registered agent service. Our mission is to help businesses start and succeed. With our business start-up services and our compliance management tools, more and more buslnesses are turning to The company corporation each and every month. Together with SCORE, The Company Corporation wishes America's small business community continued success. Regards, Published by lnc. magazine, a division of Mansueto Ventures, LLC. Copyright @ 2OO7 by Mansueto Ventures, New York' NY' All rights reserved. No portion of this booklet may be used or reproduced without written permission from the publisher (contact: /nc' magazine, 375 Lexington Avenue, New York. NY 10017). wwwinc.com The publisher is not engaged in rendering legal, accounting or other professional advice' lf legal advice or other expert assistance is required, the services of a competent professional should be sought. Sponsored by The Company Corporation' (wwwincorporate.com/score2) in cooperation with SCORE (). The Company Corporation@ is an incorporation service company and is not a substitute for the advice of a licensed attorney. The material in this workbook is based on work supported by the U.S. Small Business Administration (SBA) under cooperative agreement number SBAHQ-08-S-O001. Any opinions, findings and conclusions or recommendations expressed in this publication are those of the autho(s) and do not necessarily reflect the views of the SBA. R$-A-"*\\ Brett Davis -'--'/ General Manager The Company Corporation Our Web site wwwincorporate.com /scote2 L-e66 / 544-6804 (to The company I l-f ree) corporation is a service company and does not pravide legal or financial advtce F Summa rtze Your Idea Remember the following about any idea for a new business: . . . . A|ways be on the lookout for ideas. They can come from anylvhere: your work experience, a hobby or even your experiences as a consumer when an existing product or service doesn't meet your needs. ldentify a niche. Usually the niche or opportunity will be an innovation or proven idea in a new market or a unique idea in an existing market. Learn everlthing you can about the business you want to start and the marketplace you'll be operating in. This means getting work experience and collecting information so you'll know the industry inside and out, Make sure your idea is focused so that you can express it clearly in 50 words or less. Summarize your business idea in 5O words or less: Begin testing your idea by asking probing questions. Put answers in writing. Do this for each idea you have: 1. Where did your idea originate (from a specific experience, industry observation, a sudden inspiration)? 2. lf your idea is for a new product or service, describe how you expect to get it accepted in the market. 3. lf your idea is for an improvement or variation of an existing product or service, describe why consumers will use it instead of what is already available. 4. Describe your market niche in 50 words or less. 5. List at least three qualifications that you have that will allow you to pursue a business in this market niche (work experience, education, research, reputation, etc'). 6. What are your two most important personal goals for the next five years (independence, visibility, income, personal satisfaction, etc.)? 7. How will this business help you achieve those personal goals? 8. List and describe briefly the two most significant barriers to expect while launching and operating your business. 9. Explain how you expect to overcome these challenges' Take These Five Steps to Jumpstart Your Business Plannin$ 1. Clearly define your business idea. Be able to state the purpose and goal of your business using clear and simple language. Know your mission. 2. Examine your motives. Make sure you have a passion for owning a business and for this particular business. 3. Be willing to commit to the hours, discipline, learning and frustrations that are common to owning a business. 4. Conduct a competitive analysis in your market, including products, prices, promotions, advertising, distribution, quality and service. Be aware of the outside influences that can affect your business. 5. Seek help from other small businesses, vendors, professionals, government agencies, employees, trade associations and trade shows. Be alert, ask questions and vislt your local SCORE chapter' Test Your Idea As you evaluate your idea, keep in mind the following: t Market research a doesn't have to be complicated or expensive, but you must do it. Conduct research to determine whether there is an adequate number of potential customers to support your product or service. Use the following sources for statistical and demographic information: . Libraries and published directories (e.g., Gale Research directories) . Computerized databases (available at many libraries) o Web sites and search engines (posted by business resources and public agencies) . U.S. Small Business Administration (1-8OO-U-ASK-SBA;) . U.S. Bureau of Gensus (), U,S, Dept. of Commerce () . Trade associations for your industry r Local chambers of commerce a a a a Test your idea with potential customers and others who can offer constructive feedback (e.g., friends, relatives, bankers, suppliers, executives). Keep a written record of the responses. Be prepared to make changes based on the responses. Study and evaluate the competition. How will your product or service be an improvement over the competition? Price your product competitively-higher if your product or service improves on an existing one and lower if it will be equal to what is on the market. Be sure you can make a profit long-term. For each of the following categories, list two potential sources (with location and phone number) who can comment candidly about your business idear Bankers (check your local Yellow Pages under "Banks") Trade Associations (search the lnternet or check the Encyclopedia of Associations, available in most libraries) Government or University-affiliated Organizations (call your SBA district office, SCORE "Counselors to America's Small Business," or the nearest Small Business Development Center) Successful Entrepreneurs (from magazine or newspaper articles and local references) Suppliers (check local Yellow Pages, classified advertisements and publications such aslhe American Wholesalers and Distributors Directory, available at major libraries) Answer the following questions about your market: 1. ldentify your three most important groups of potential customers, defining them a. b. C. by the criteria to your product or service' (e.g., age, demographics, industry, etc.) that you believe are most relevant 2. Name your primary competitor for each of the three groups. a. b. 3. Describe how each group feels about this competitor' a. b. 4. Describe the factors that are most likely to make each group leave a competitor and switch to your product or service. b 5. Where did the answers to questions 3 and 4 come from (printed pieces, market study, questions to prospective customers, etc.)? d. b. 6. De scribe d. what makes each of your competitors successful' b. C. 7. Describe what makes each competitor vulnerable to loss of customers. Answer the following questions about your pricing policies: 1. Provide details and/or a calculation of how you arrived at the price for your product or service. 2. List the price(s) that your most significant competitors charge for their corresponding product or service. 3. lf your prices are higher, why? How will you justify them to your customers? 4. lf your prices are lower, why? How will they help you attract customers? Protect Your Idea this Start-up entrepreneurs tend to worry about having their business ideas stolen, but it is important to keep issue in perspective: . Don'tworry about protection so much that it interferes with yourtest marketing and test develoPment. . Be discrete about revealing details of your business idea, particularly with competitors. . lf you think your idea qualifies for legal protection, speak with a lawyer. The protection options are: Patent (to protect an original device or process) Copyright (for printed material, such as consulting manuals, books and maps or computer software) Trademark (to guard a product name, logo, symbol or figure) service mark (to guard a brand or service name, logo, symbol or fi$ure) Here are eight basic steps to ensure that you have sufficient legal protection: 1. 2, 3. For the best protection against having your business idea stolen, be sure you know the character of every person with whom you discuss the idea. lf you share copies of your business plan, be sure to number each one and record the name of the individual who receives it. Ask those who will review your business plan to sign a nondisclosure agreement that prohibits them from using or discussing the information. Be sure any employment agreements limit the ability of someone who leaves your company to use proprietary materials, desifns and formulas orto take customer names with them. File for a patent to prevent others from copying your invention. File for a copyright to prevent others from copying your material, including print, software, music, films' art 4. 5. 6. 7. and recordings, Register your trademark to prevent others from using a special name or logo you plan to use. your ownership rights, obtain the services of a qualified attorney who is experienced in matters irrvolving intellectual property protection. 8. To protect To obtain U.S. coPyright forms or for nrore information about copyright protection, contact the Copyright Office' Library of Congress, Washington, D,C. 20559. For more information about patents and trademarks, visit the U.S. Patent and Trademark Office online at wwwusPto,gov. Create a Business Plan A well-written business plan will play a key role in the success of your business. ln addition to being required to obtain certain loans, a carefully considered plan helps business owners focus on strategic objectives and communicate those objectives to staff. For those inexperienced in creating a business plan, free assistance is available from a variety of nonprofit sources, including SCORE "Counselors to America's Small Business" and local Small Business Development Centers. Local banks can tell you what they look for in a business plan and an accountant can help you prepare the necessary financial statements. You also may use the cash flow worksheets found on SCORE's Small Business Web site,. The planning process will not be intimidating if you keep these points in mind: . ' . Planning ahead foryour new business can mean the difference between success and failure. Use an informal plan consisting of three to six pages to convince reiatives and friends to back your venture. Be sure to cover the first eight points cited below. To approach bankers, individual investors and venture capitallsts, prepare a more formal written business plan. lt shouldn't be longerthan 40 pages and should be organized as follows: A two-page, succinct explanation of your business and its activities, wrth an overview of your key objectives and business goals. 1, Executive Summary, 2. Business Description. Describes your perception of the company. company will differ from other providers. How will your business grow and profit? 3. The Market and Gompetition. Largest sectlon. Honestly acknowledges competition and describes howyour 4. The Product or Service. Describes the core of your business. 5. Marketing/Selling. Explains how you will access the marketplace. Will you advertise, attend trade shows, establish a Web site? 6. Management and Personnel. Explains how you wili staff and manage your business. lt includes profiles-or biographies-of yourself, partners and any other key team members. one-paragraph 7. Financial Data. Contains the balance sheet, profit-and-loss statement, break-even chart and cash flow analysis. 8. lnvestment. Based on cash flow, it includes what the investor will receive as a return. 9' Appendices. lncludes testimonials from potential customers, research clips, charts and graphs relevant to your business. To create a successful business plan, consider these three questions: 1. 2. Which type of business plan (informal, less than 10 pages; or more formal, up to appropriate for your business? Why? 40 pages) is most Outline the sections of your plan (see list above). How long should each section be? ldentify areas that require more work on your part, as well as areas that you are ready to put into writing. 3. Need Help With Your Business Plan? Contact SCORE SCORE "Counselots to America's Small Business" is a nonprofit organization dedicated to helping entrepreneurs succeed as small business owners. More than 10,500 volunteer business counselors in 389 chapters nationwide are available to provide you with advice, mentoring and small business planning assistance. SCORE business counseling is free and confidential. You can rely on SCORE as a trusted resource to help you plan for success. Since 1964, SCORE has assisted more than 7.8 million aspiring entrepreneurs and small business owners just like you through counseling and business workshops. For more information about starting or operating your own business, call 1-800/63+0245 for the SCORE chapter nearest you. Or, visit SCORE on the Web at wwwscore.org. Choose a Structure For legal and financial purposes, you must have a formal structure for your business. Your four basic choices: 1. Sole proprietorship. The owner and the business are the same (often a service business, with the owner providing the service). Business and personal tax returns are filed together. Advantages: Simple and inexpensive (start-up costs are low); maximum control' Disadvantages: Unlimited personal legal and financial liability; limited abilityto raise capital; not an enduring structure. partnership. A business with more than one owner; divides profits and losses among participants' lt may be popular for lawyers, doctors and other professional service providers, but not for most new businesses. . . 2. 3, lncorporation. A safer choice for businesses that have employees or bank financing. A corporation is a state-chartered organization owned by shareholders. The shareholders can elect or appoint a board of directors who are ultimately responsible for management of the business. . Advantages: Personal assets are protected from the debts and risks of the business. This is especially important if the business fails or is sued. o Disadvantages: Corporations must hold meetings and file annual reports resulting in paperwork. There are two major types of tax status that corporations can choose: C Status. So-called because it is taxed under regular corporate income tax rules. Advantages: Limited liability; access to capital (can raise money through sale of stock); perpetual life (unlike sole proprietorship); ownership can be transferred. . Disadvantages: Profits are subject to double taxation (corporate income is taxed and then dividends paid to stockholders are taxed as part of the individual's income); regulation and paperwork; some limited start-up costs including state filing fees. S Status. So-called because it is under subchapter S of the lnternal Revenue Code; also known as a "Sub Chapter S." . Advantages: Appropriate for start-ups; limits personal liability; S corp dividends are not subjectto self-em ployment taxes; el i m i nates dou ble taxation. . Disadvantages: Taxes on many fringe benefits; restricts number of stockholders to 35. . 4. Limited Liability (LLC). State-chartered organization that allows for the reduced personal liability of a corporation, but with the tax advantages of a partnership or sub chapter S. . Advantages: Liability protection; no ownership restrictions; no double taxation; easier access to capital (compared with partnership); like a S status corporation with less paperwork; less formal; less paperwork than a corPoration. . Disadvantages: Stock not available. through? \\'Iays to Organize ype ol 0rganization lbur Business Main Disadvantages Main Advantages Sole Proprietorship o Simple and inexpensive to create and operate. . . Owner personally liable for business debts. Not a separate legal entity. More expensive to create and operate o Owner reports profit or loss on personal tax return. G Corporation . . . . Clients have less risk from government aud its. than sole proprietorship or partnership. Double taxation threat because the corporation is a separate taxable entity. Owners have limited personal liability for business debts. Owners can deduct fringe benefits as business expense. Owners can split corporate profits among owners and the corporation, paying lower overall tax rate. Clients have less risk from government audits. Owners have limited personal liability for business debts. Owners can use corpoi'ate losses to No beneficial employment tax treatment. S Gorporation . . . . . . More expensive to create and operate than sole proprietorship. Fringe benefits for shareholders are limited. offset income from other status. Owners can save on employment taxes by taking distributions instead of salary. Simple and inexpensive to create and operate. Owners report profit or loss on personal tax returns. Owners have limited liability for business debts if they participate in management. Profit and ioss can be allocated differentlv than ownership interests. Bepr rted Partnership . . . . . . Owners personally liable for business debts. Two or more owners required. No beneficial employment tax treatment. No beneficial employment tax treatment. Limited Liability Company . r wlih perm ss 0n frOm \y'/orking for Yaurself b\/ Stephen F shmaf 1N0 0) throuSh? Ways to Organize Type of 0rganization lbur Business Main Disadvantages Main Advantages Sole Proprietorship . . Simple and inexpensive to create and operate. Owner reports profit or loss on personal tax return. . . Owner personally liable for business debts. Not a separate legal entity. More expensive to create and operate than sole proprietorship or partnership. Double taxation threat because the corporation is a separate taxable entity. No beneficial employment tax treatment. C Corporation . . . r Clients have less risk from government aud its. Owners have limited personal liability for business debts. Owners can deduct fringe benefits as business expense. Owners can split corporate profits among owners and the corporation, paying lower overall tax rate. Clients have less risk from government aud its. Owners have limited personal liability for business debts. Owners can use corporate losses to offset income from other status. Owners can save on employment taxes by taking distributions instead of salary. Simple and inexpensive to create and operate. S Corporation . . . . . . More expensive to create and operate than sole proprietorship. Fringe benefits for shareholders are limited. Partnership a . . . . Owners personally liable for business debts. Two or more owners required. No beneficial employment tax treatment. Owners report profit or loss on personal tax returns. Owners have limited liability for business debts if they participate in management. Profit and loss can be allocated differentlv than ownership interests. ferently Limited Liability Company . . No beneficial employment tax treatment. Repr nted with permrsslnlwi Wailtng f)r Yaursell by Stepher Flstrmaf {Nol0) profits to cover the payments comfortably, then added equity is needed, not more debt. 3. Equipment and other fixed assets. Equipment and other fixed-asset loans are about the clearest examples of matching a loan to the need and payment base. Since these loans are ordinarily secured by the equipment, the anticipated useful life of the equipment becomes a major factor in the credit decision. A rough guideline is that you can finance equipment with a projected useful life of 10 years for up to 70% of its life and up to 90% of its value. Don't buy fixed assets on 90-day notes. The timing is wrong. lf you're trying to make your business work on sweat equity, you may want to go ahead and pay off a piece of equipment more rapidly than we'd recommend. That's an option, but a hard one to live with. While equipment loans rarely go beyond 7 years, commercial real estate may be financed for 10 or more years, depending on the situation. Since you are building equity in equipment and real estate from profits for a number of years, you should finance it the same way. Using Credit Wisely Managing cash and securing capital are the two biggest challenges small business owners face particularly in the start-up phase. To keep personal expenses separate from business expenses, use business credit cards as money management tools. Here are three ways they will help you: . Business credit card: Use it to make and manage purchases, as well as cover travel and entertainment expenses. Like a reserve of credit, a business card gives you the flexibility to pay lrills in full or revolve your balance. Business check card: An ideal replacement for cash and checks-with the convenience of a debit card-check cards allow you to draw on funds from a business checking account. They are excellent for start-ups, since they allow your company to establish a business relationship with your bank. Business credit line: Providing an unsecured Iine of credit up io $50,000, the credit line gives businesses a source of working capital for emergencies or growth opportunities. . . 4. Inventory, seasonal progress, Caution: lf you are a sole proprietor or partnership, These loans are short-term and are usually tied to a clearly you are personally responsible for your buslness defined source of repayment, such as one inventory turn, debt. Forming a corporation or LLC separates your business debt from you personally. fulfillment of a contract or sale of a specific asset. Short-term notes are repaid from short-term sources, clearly identified before the credit is granted. Medium- and long-term debts are repaid from more indirect sources. A banker looks to proven management ability (usually evidenced by a profitable history and clearly understood plans) for repayment. Since there is no single, fast source of repayment, the risk is greater and the decision more difficult. This is a crucial distinction. A poorly run company may be a good short-term credit risk, but for long-term credit, a business must show the ability to consistently generate profits, Remember, term loans come due every month, adding to the drain on resources and, in turn, increasing the risk and need for more careful financial management. 5. Sustained growth. The final major need forfinancing is growth, which can outstrip working capital. As sales go up, liquidity often goes down. A combination of investment, lines of credit to receivables and inventory and long-term working capital loans is the common answer. Notice whatthis implies. lf you plan to grow, you must plan to generate profits consistently, while at the same time keeping your business liquid to meet current obligations. To make sure that you maintain liquidity, you have to be certain of yourfinancing strategy. The answer? A solid financial plan. (For help in creating a sound financial plan, contact your nearest SCORE office. See page 10.) Work with your banker. lf you aren't comfortable preparing a financing proposal, complete with financial statements or if you feel that your banking relationships could be improved, get your banker involved in your long-term planning efforts. Like all business professionals, bankers like to use their skills. Since most businesses suffer from a lack of financial management skills and since most bankers have these skills, it is to your advantage to make the first move. lnvite your bankerto help you. Level with him or her. lf you can't keep communications open, then you won't get help-and it's quite possible that you won't get the financing you need. By being open, you'll enhance your credibility. And better yet, you'll more likely find that you can turn the banker's skills into a positive resource rather than a roadblock. Get a fix on f inancing To obtain the funds to launch your business, here are six avenues to explore: 1. Stick close to home. There may be more options than you think, including: . . . . Personal savings Business credit card Business credit line Business check card . r Second mortgage on your home Friends and relatives o Profit-sharing funds from your previous job 2. lf you need more than these sources can provide, consider: . Bank loans . Limited partnership . Private offering 3. Plug into a local network, including the following: Nearest office of SCORE "Counselors to America's Small Business": 1-800/634-0245 Nearest Small Business Development Center (SBDC) oryour state economic development department o Local business associations, such as the chamber of commerce . State and locally sponsored small business conferences 4. Seek venture capital only if your business has the potential to achieve multimillion-dollar sales within five years. (For more information, contact the National Venture Capital Association al 703/524-2549 or the National Association of Small Business lnvestment Companies al 2O2/628-EOE5.) 5, Don't get bogged down hunting for funds; if you encounter problems raising money, try to start your business on a smalier scale. . . o U.S. Small Business Administration: I-8OO/827-5722 6. history-for both you (personal credit rating) and your business. Try to find out which credit reporting service your prospective lender uses and request a report from that company. The three major credit reporting companies are: Dun & Bradstreet (1-8OO/234-3867), Eq u if ax (I-8OO / 202-4025 ) a nd Expe ri a n/TRW (1-888 / 397 37 42). Be sure you know your current credit ABC's of Rorrou'ing: Five T\pes of Rusiness Loans. Tenns and Purposes Equipment/ Loan Type Term Credit Card Evergreen Credit Line Short-Term Loan Vehicle Loan Up Commercial Real Estate Loan 12 months of evergreen 90 day note Short-term to 7 years 10 years + e Purchase or Purpose Cover travel, . . entertainment and office supplies Cover short-term cash-flow needs Carry accounts receivable Unexpected events items Iike inventory Purchase or refinance business refinance commercial . equipment and/or veh icles real estate Use the five questions below to provide a framework for focusing on funding your business: 1. List the banks in your area where you will apply for a loan and individuals who might provide you with introductions to bankers. 2. ldentify individuals at the bank to whom you should approach with your request. a) b) c) d) 3. What are the key questions you will ask your banker? (Find out how much experience the bank has in lending to your type of business, then ask about the lending/borrowing details-e.9., loan limits, collateral requirements, interest rates and other terms.) 4. How will you answer each of these five questions that the banker will inevitably ask you? need? b) How long do you need it? a) How much money do you c) What are you going to do with it? d) When and how will you repay it? e) What will you do if you don't get the loan? 5. Should you seek venture capital rather than a bank loan? Begin answering this question by comparing the key factors bankers and venture capitalists focus on: Banker Collateral Covenants in loan agreement Ration analysis Ability to repay Financial statements Venture Capitalist Market demand for your market or service Equity position and value of stock Compound annual rate of return (typically 35o/olo Exit within 5 to 7 years 5Oo/o) Management's background Both, of course, will expect you to present a sound business plan. Check the sources you plan to approach for funding: Personal Resources Close'to-Home L- Friends Outside Sources tr n Savings n Bank loan SBA loan Second mortgage lnsurance Profit-sharing n Family I I I I n E Business credit card Business credit line Venture capital tr Limited partnership n Private offering Build a Team For your new business to have a chance to grow, it must have good people. With this in mindn be sure to do the following: 1. 2. 3. Consider outsourcing first. With employees comes payroll tax, HR issues and recordkeeping. When it is time to hire, look for those who: a) share your values and goals for the business, and b) have winning attitudes and track records. Approach investor relationships with caution. Describe everyone's responsibilities in writing and work with a lawyer on a buy-sell agreement that covers who owns what and how the partners can sell their shares to end the partnership. Use outside advisers such as an accountant, a lawyer, a mentor and a board of advisers consisting of two to five professionals whose judgment you respect, including SCORE counselors. 4. Personal assessment. List your business-related strengths and weaknesses and likes and dislikes. lnclude personal traits, skills and behavior. For example, if you like numbers but dislike making presentations to groups of people, write that down. lf you don't enjoy working with raw data or performing in-depth analysis, but would rather spend your time in people-oriented situations, then put that down. This exercise will enable you to determine the personal contributions that you will bring to your own company, as well as define the gaps that can be filled by hiring qualified key employees. Strengths Weaknesses Likes Dislikes This should give you some specific ideas about the qualities you'd most like to see in your employees. Next, think about the skills, traits and backgrounds you would like them to bring to the business. List and prioritize them from the most to the least important: Based on the qualities above, write a job title and description for each of the key people you plan to hire: a) b) c) d) Gompensation 1. 2. How much would you expect to pay to outsource this role, such as bookkeeping, packing/shipping, etc? What is the market value for each job title or individual described at the bottom of page 1"6? Tifle (a): Title (b): Salary: $ Salary: $ Salary: $ Salary: $ Tiile (c): Title (d): 3. How much salary might he or she expect to receive from one of your competitors? a) Starting salary: $ b) Starting salary: $ c) Starting salary: $ d) Starting salary: $ 4. What salary are you prepared to offer? a) Starting salary: $ b) Starting salary: $ c) Starting salary: $ d) Starting salary: $ 5. What other forms of compensation or benefits might you provide in lieu of higher salary? 6. When do you need to lrring these people on board? (Create a schedule for when you plan to have each person working for your company.) a) b) c) d) Outside Advisers Name the outsiders who can contribute to your operation by providing valuable advice and services (e.9. bookkeeper): Invest in Technology Secure Data Storage All small businesses are required to record and report more data than ever as a result of Sarbanes-Oxley and the Patriot Act, which were passed into law by Congress. ln addition, according to Internal Revenue Service rules, your business information must be maintained for anywhere from two years to permanently (to learn more about what must be kept and for how long, visit and search for "business record retention"). As a small business owner, these regulations mean data back-up. Typically, for smaller businesses, it's easy to back your data up to CD or DVD, both of which are common options on most PCs sold today. As an alternative, you can purchase a server PC that can be networked for data back-up. ln that case, a tape drive is often a good choice. You can also choose to store key documents securely in an off-site location, such as a safety deposit box. Some small businesses choose to outsource their electronic document storage. Providers offer a relatively low-cost alternative to in-house storage networks (there are also standalone electronic document storage systems, but they tend to be prohibitively expensive for small businesses). Most provider systems offer highly secure off-site scanning, storage, indexing, searching and file retrieval. The process is fairly simple: You give these providers your documents with keywords for indexing. Then they provide you with a search engine for all your documents, making file retrieval painless. ln addition, most data storage providers allow you to search for your documents online. Before making any decision regarding data and document storage, think about your data storage requirements forthe longterm, how much capacityyou'll require, how often you'll be retrieving documents and data and your objectives for growth and security. Gomputers Before you buy a computer, be clear about what you want the system to do for you. Check off the tasks that you would like to use a computer for and take this iist with you when shopping for one: tr Write correspondence tr Keep a customer list I J Presentations Contract management Send,/receive faxes n Generate mailing labels Design a brochure Create a catalog Lay out a newsletter f ! tr n L_l n Maintain an appointment calendar tr Design your office n Conduct research for a proposal Lr Surf the lnternet pi tr Send/receive e-mail Accou nti nglboo kkee ngls preads heets tr Check writing l n 1 Set up a "storefront" on the lnternet Network internally (printer, multiples offices) E Track inventory/order entry I Financial planning n Do "what if" financial calculations I Work/network with associates' computers Fortunately, there are several off-the-shelf software solutions designed to help you take on management and operations tasks. The following list offers a few available products in each group. . Bookkeeping/Accounting-Among the most popular packages for small owners are QuickBooks () and Peachtree (). Both packages handle a variety of profit and loss (P&L) functions, checking and accounts receivable and payable. They also offer great reporting functions to support you at tax time. Customer Relationship Management (CRM)/Sales Automation-CRM has become a nearly ubiquitous term. For small business owners, CRM software means having comprehensive contact information at your fingertips, including an understanding of every interaction a customer has with your company. Sample . solutions include Surado Small Business CRM (wwwsurado.com), Terrasoft CRM (wwwterrasoft-ctm-software,com), Act! ('com) and lnsidesales.com (wwwinsidesales.com), which is an online solution. . production,/Project Management-scheduling and project management software is crucial for any company with a multitude of deadlines and employees performing a variety of tasks. A few good examples are Visual Staff Scheduler Pro (), FastTrack Schedule 9 (wwwaecsoft.com), Office Tracker 7.0 () and Project Standard 2007 ()' Regardless of your operational need, you can probably find a package that supports it. Once you do your research and find a productyou like, check out its manufacturer and search the Web for independent reviews and comparisons. Look at buying a computer and other office equipment as an investment, not a cost. Your choice of systems should be based on more than the price of the basic unit. When conducting your preliminary research, ask these questions: . . . . . . . . . . . . . ! f I I How easy is it to use? Will I need to hire someone to set it up? How difficult are the software programs to learn? Will I need to pay for training (for myself, managers or other staff)? How easy is it to add extra equipment such as scanners, hard drives or backup devices? Can I exchange information easily with other computers? As my business grows, how easily can I connect/network with other computers? How soon is my business likely to outgrow the unit? Will I need a server (data storage) for my business? Will I be protected against computer viruses and other online security risks? ls there a toll-free number to call for help? What are the warranty and repair policies? How satlsfied have other users been with this system? To help you choose the computer that's right for your business, use this checklist of features to consider when talking to a salesperson: Processor (type and speed) RAM (MB) Hard drive size (GB) CD-RON//DVD Burner Monitor f Keyboard ' Mouse .l Fax/modem I Multimedia-ready fl lnternet-ready tr Networking capabilities Upgrade capabilities Bundled software Warrantv Ll Expansion capabilities l f l Fax Machines After a computer, the most common piece of small business technology is a fax machine. Some computer modems have fax capabilities built in, but your computer must be running to receive incoming faxes' Computer fax/modems also don't allow you to easily send freestanding material, since you must first scan the material into the computer. For these reasons, most businesses invest in a fax machine or a multifunctional unit that combines fax, printer, scanner and copier capabilities. When selecting a f ax machine, keep these features in mind: Features i Memory Send,/receive speed Speed-dial capabi ities I Telephone line sharing Telephone handset I I I Resolution Cost of cartridges TyPe,/cost of PaPer Lr Broadcast capabi ities Technical support options I L- Repair options Multifunction capabilities (printer/scanne r / copier) L Warranty Telephone Equipment: How many lines do you need? Many small businesses rely on a two-line phone-one llne for incoming calls and one for outgoing, fax and modem (i.e., lnternet) calls. Determining how many lines you need depends on what type of business you're in and the number of people requiring phone access. While there is no universal rule regarding lines to people ratios, many businesses find that a 1:3 ratio (one line for every three stations) is adequate. lf your business will rely heavily on telephones and data lines (i.e., for lnternet access, fax machines, creditcard authorization terminals and answering machines), you will need multiple lines. You might also want to consider high'speed access to the lnternet via cable modem or DSL. Contact your local phone company and ask the business representative for a busy-line study. This is a statistical printout of the number and frequency of incoming calls that receive busy signals and it will help you determine how many lines you should have. To understand more about telephone capabilities, here are 10 pointers you may also want to discuss with your phone company rep: 1,. lf you are setting up a home business, installing distinctive ringing will allow you to piggyback a different telephone number on your existing line, making it ring in a different tone and pattern. lf you want a separate telephone line in your home-based business, you can save money by installing a residential line. To obtain a business listing in the Yellow Pages, however, you need to install a 2. 3. business line. lf you don't mind being interrupted during a call, call waiting can notify you when another call is coming in. Customers often find this option annoying, however and business telephone etiquette experts suggest investing in voice mail, which allows customers to avoid a busy signal and leave a detailed recorded message. lf you want to be able to speak to several individuals in different places at the same time, you can arrange 4. 5. 6. 7. 8. 9, for conference cal ling. When you frequently call the same numbers, speed dialing can save you time by allowing you to preprogram a one- or two-digit code into your telephone. You can save money on calls of short duration if your telephone provider offers billing in six-second incre- ments instead of full minutes. CallerlDallowsyoutoidentifywhoiscallingbeforeyoupickupyourtelephone, When you sign up for additional telephone lines or services, inquire about installment billing, which allows you to spread out the payments over several months, often without finance charges. lf you're often away from your office and want your calls to follow you to another number, invest in call-forwarding options. 10. To encourage customers to contact you for information and orders, establish a toll-free number. l--r$r [Jse the Internet their The lnternet is a cost-effective communications medium that small businesses can use to complement service efforts. For example, you can use the lnternet to: existing research, sales and marketing and customer . . . . . . . Get information and updates to your customers. Solicit feedback and ideas from customers' communicate and collaborate with agencies, vendors and suppliers. located' Exchange information and questions with peers and consultants, no matter where they're Search for information about products, technologies, statistics and your competition. Sell products or services 24 hours a day,7 days a week, to a global audience (see Chapter 10). Assist and service your existing customers and prospects with current orders, product/service information and other customer service functions' To connect your computer to the lnternet, you'll need to subscribe to an onllne commercial service (such as (lSP) in your area. When choosAmerica Online, Earthlink or MSN) or sign up with an lnternet Service Provider ing an lSP, start by asking these questions: Making Your Gonnection . . . . . How long has the firm been in business and how stable is the company? What kind of access speed does my lrusiness need? DSL? Cable Modem? How many customers does it have in relation to the number of modems? (lf the ISP doesn't have enough modems, you'll be frustrated by busy signals when you wantto connect.) Are its rates timed orflat-fee? (lf you're a heavy lnternet user, a monthlyflat-rate arrangement maY be most economical.) What are its technical support services? Are they free or for afee? Does it offer any other services, such as design or hosting of Web sites? Web Sites busiMany companies and government agencies have set up Web sites with valuable information for small the lnternet, take time to visit the following sites: nesses. Once you've connected to Site URL/address AllBusiness One of the most comprehensive small business resource sites, featuring extensive bloggers/advisers, videos, forms and more' www. incorporate.com/score2 The Company CorPoration' One-stop incorporation service company; includes writing and filing articles of incorporation' name registration, registered agent and compliance tools' wwwebaY.com popular site for purchasing new or used office equipment, furniture, hardware/software and A other office-related products for small business. Ebay Edward Lowe Foundation and educational experiences that support entrepreneurship and the free lnformation, research enterprise system. E-Myth wwwe-mYth'com Seminars and workshops designed to help the small business owner grow his,/her company' eVenturing public service provided by The Ewing Marion Kauffman Foundation; includes Entrepreneur's Search Engine offering more than 1,000 Web resources for smali businesses. lnternationalTradeAdministration Broad range of export-related information, statistics and country reports. IRS (Tax Forms and Publications) wwwirs.gov Downloadable forms and tax information, as well as an electronic filing interface. National Retail Federation Advice and upcoming events from the world's largest retail trade association. Nolo SCORE Find self-help legal information for small businesses. Topics include: Business & Human Resources; Patents, Copyright & Art; Property & Money; and Rights & Disputes. Ask SCORE offers email business counseling or read small business articles from SCORE "Counselors to America's Small Business." Click Find SCORE for a local office. U.S. Federal Government wwwbusiness,gov One-stop resource for federal government information; links to 1000,000+ databases. U.S. Patent and Trademark Office Search databases, print forms and find statistics concerning registering trademarks and patents. U.S. Small BusinessAdministration lnformation on starting and runninS a small business from the U.S. Government. lf you want to search the lnternet for specific information, it is best to use a search engine. Afler typing in key words or phrases, your results will be displayed on the screen. Here are some popular search engines: SearchEngine URL/address AllTheWeb Ask Jeeves Google HotBot Yahoo! One of the best ways to learn about the lnternet is to browse on your own. Bookmark those sites that you find are worth frequent visits. Web Site Domain Names To register a Web site domain name for your business, you may contact a number of different domain registration service companies. They include and among a host of others. Rates vary but expect to pay no more than $10-$50 for a one or two year registration. Combating Online Fraud Whether you're surfing the Web or using email, once you're online, your computer and network are at risk for viruses, fraud and other problems. There are easy steps you and your employees can take to protect yourselves: r . . . Bookmark the sites you visit frequently and know can be trusted. Access those sites only through your favorites or saved links. Don't automatically click on any links provided in an email. lnstead, open a new Web browser window and type or paste the Web site's URL into the browser's address bar. Be wary of clicking on any pop-up message. Be suspicious of Web sites that display an lP or numerical address (such as 1,19.991-.2.L) in your browser's address bar instead of a domain name (such as). Put the Web to Work for Your Business Just l-O years ago, the typical entrepreneur would launch a business by installing a landline phone system, printing business cards and letterhead, and designing marketing materials such as brochures and direct mail pieces. That's all changed now, The lnternet enables you to accomplish these critical tasks-and many more-with less money and more productivity. Whether you sell services or products, you can use the Web to advertise, communicate with customers and reinforce your brand identity. Consider something as basic as your phone. Voice over lnternet Protocol (VolP) technology can cut costs for business calls and multiple lines. On a larger scale, your company's Web site can be used to produce significant savings. Establishing your firm's presence online can help you promote your company, generate leads and deliver customer service. The beauty of the lnternet is that even the smallest start-ups can raise their profile and reach a global audience. 5 Steps to Launch a Web Site Think of your company's Web slte as a different kind of storefront. Your goals in creating a business Web site may involve informing, educating, marketing and selling your products or services. Armed with an awareness of your goals, the process of developing a Web site is simple and straightforward. Follow these steps to maximize your site's success: 1. Decide whether you'll set up your Web site on your own or hire a consultant or Web design firm. While fees vary widely if you seek outside help, you will probably pay only $4 to $20 a month for a site-hosting service (plus annual registration of your domain name) if you do it yourself. 2. Select a succinct, memorable domain name (i.e.,) that communicates what makes your business special. Avoid abbreviations or anything that makes it hard for others to remember. You will need to register your domain name (the sooner the better) before launching your Web site. Some site-hosting firms will register the domain name for you when you set up your account. Devise a Smart Strategy ln designing your Web site, think through each of these issues: AUDIENCE: Who is your target audience? lf you 3. Whether you proceed on your own or by hiring a Web designer, conduct due diligence to make sure you partner with reputable vendors. ln selecting a site-hosting firm-which provides the server space for your Web site-research the right one for your needs. Get referrals from other business owners and check the hosting firm's background. Review the number of customers it serves, its fee structure, the speed of its connections and lts level of customer support. Similarly, ask lots of questions before hiring a consultant to help you design your Web site. want to reach more than one audience, prioritize your primary target, secondary target, etc' PURPOSE: What is the purpose of your Web site? What business need will it fill? How will it enhance profitabil ity? GOALS: How is the site ali$ned with your company goals? Will you sell a product or service online? Will you showcase a portfolio of prod- ucts? How does the site help you obtain or retain customers? SIZE: How big will your site be? (larger sites cost more) INTERACTIVITY: Will your site offer interactive features? Can visitors send email, give feedback, submit an order or request information? 4. Keep the design clean and visually appealing. The best Web sites incorporate simple colors, fonts and graphics. Use a font size of 10 points or above and limit each paragraph lo I2O words or less. 5. As you add content to the site, run periodic tests to confirm that ever).thing works properly and online visitors can navigate your site easily. Avoid Web Site Traps The power and potential of the Web can overwhelm you if you're not careful. Using the lnternet to Market Your Business Beware of these pitfalls: Most consumers use the Web for two reasons: to get direct information or to locate a link that will take them to the inforOverlooking Personal Service. lf you mation they want. Because many shoppers start with a conduct e-commerce, send email updates search engine like Google, you want them to find your Web on orders. answer customer inquiries site as quickly and easily as possible. promptly and call to follow up when A Web design and maintenance firm can help you impleapproprlate. ment an online marketing strategy. At their best, these ser vice providers fully manage all aspects of the site and drive Failing to lntegrate Your Web Site with Web users to discover your business. the Rest of Your Business. lnclude your To increase your site's exposure, these Web specialty Web address in all traditional print adverfirms offer "search engine optimization" (SEO)-a service tising, business cards, press releases, that lures search engines to recognize your site. People are company brochures-even emblazoned on more apt to find your site if the search engine they use lists your service vehicles. it prominently. Neglecting to Test. To prevent customers The SEO firms will work with you to regularly update your from leaving your site due to an errorWeb content, improve the density of industry-specific keyprone ordering process, run frequent words that comprise your Web site's title pages and headtests to gauge the shopper's experience. "page rank" (a measure used by ers, and increase your Google that calculates both how many links point to your site and the "quality" of the sites providing the links). To save money, borrow some of the same tricks that SEO firms use to call attention to a Web site. Here are some steps you can take on your own: 1. Trade links with as many people and organizations as you can. Provide a "helpful links" page on your and arrange for those Web sites to link to your site in return. your industry to spread the word about your site. sitein 2. Publicize your Web site aggressively. lnvite people to download free material and urge influential bloggers 3. Consider email marketing to cultivate customer relationships. Consumers prize personal service-and the lnternet provides a low-cost way to deliver il. Warning: lf you choose to send a promotional email to customers or prospects, make sure they have requested to hear from you. 4. Search the Internet for free or low-cost Web directories that relate to your industry or consumer base. submit your business name and web address to those directories so that your firm gains exposure. Then 5. Write short articles and submit them to relevant Web sites in your industry. Focus on the Iatest trends in your business or practical, how-to information. Many Web sites will trade a free plug for your company for a well-written article. Better yet, your article can position you and your firm as a credible leader in your business. Another option to raise your company's lnternet proflle is to experiment with pay-per-click advertising. This means you set a price that you will pay each time an individual clicks on your online advertisement (which can be placed on a popular Web site that's heavily trafficked by consumers). The advantage of this type of Webbased advertising is that you only pay for actual clicks on your ad. This gives you flexibility in managing your advertising budget, because you can usually terminate and then resume your ads whenever you want. Once you get accustomed to marketing your business on the Web, you may decide to sell directly to the consumer online. The benefits of electronic transactions, billing and even inventory control can boost your efficiency while reducing your accounting, database management and other costs. Control Cash and Credit What levels of debt can your business safely support? Can you control the amount, timing and availability of credit? That is, can you ensure the timely inflow of cash from new debt? Assume that you have done all you can realistically to control your cash flow, but you still face occasional periods of cash shortfalls. To tide you over these periods, you have to borrow from an outside source-e'9., a commercial bank or credit-card company line of credit. How do you go about preparing a financing proposal? Begin by focusing on receivables and inventory. Chances are they might be your largest current assets against which you can borrow. ldeally, receivables and inventory turn into cash as Steps soon as you wish. However, unless you manage them carea problem. To fully, cash flow and carrying costs become Managing Receivables manage your working capital properly, you must know: 1. Age your receivables. of your receivables and inventory. 1. The age 2. Calculate your collection period and 2. The turn of your receivables and inventory. apply the " 4O-day /3O-day" rule of thumb 3. The concentration of your receivables (how many custo see if you have a Problem. tomers comprise the majority of your receivables, what 3. ldentify slow-paying customers. amount of receivables they represent, what products the receivables cover) and inventory by product lines. 4. Pursue delinquent accounts vigorously. Five for You also must know what your credit and collection poli5. ldentify fast-paying accounts and try to cies are doing to your working capital. All too often small increase their number. business owners mistake sales for profits. They extend more and more credit, pursue lax collection policies and end up financlng Receivables management. control receivables, begin by examining their age. Break receivables out weekly to spot the slow-pay accounts as soon as possible. Then you can try to collect before the accounts costs you your profits. Aging receivables is simple: Separate invoices into Current, 30 days, 60 days, 90 days and more than 90 days. Then calculate your collection period: Divide annual credit sales by 365 to find the average daily credit sale. Next, divide your current outstanding receivables total bythe average daily credit sale. This yields your collection period. Here's a good ruie of thumb for a quick test of your receivables management: lf your collection period is more than one third greater than your creclit terms (for example, 40 days if your terms are net 30), you have a looming problem. Managing yout inventory. lnventory management, like receivables management, is often overlooked as a source of operating profits. Careful attention to how you manage these two areas can often free up cash and improve operating profits without resorting to bank borrowing. lf you are managing both of these areas well, congratulate yourself-you are in a distinct minorlty. Carrying costs of inventory can run as high as 30% of average inventory, a substantial drain on working capital. Consider the costs of storage, spoilage, pilferage, inventory loans and insurance. They add up fast. Determining the right level of inventory to carry is difficult. On the one hand you want to avoid unnecessary expenses, while on the other you want to avoid as many stock-outs as possible. Trying to manage inventory on a day-to-day basis invites trouble; accordingly, most businesses use some kind of inventory policy. The three most important factors ln creating an inventory policy are inventory turnover (how many times per year and how that compares with other businesses in the same line), reorder time (planning on a 1-0-day reorder time is vastly different from a 2O-day reorder time) and who your suppliers are. lnventory control is a balancing act. lf your inventory gets too high, you run out of cash. lf it's too low, chances are you're buying in uneconomical quantities (a danger sign to bankers), you're too undercapitalized to ever become profitable (another danger sign) or you're bleeding the business. Bankers are increasingly interested in the quality of inventory as well as the more standard indicators of good management (liquidity, profitability and track record). lf you have a cogent inventory policy and follow it carefully, you will upgrade both inventory quality and profitability. Establish a contingency plan. A contingency plan is a plan you hope never to use. lt outlines what you would do if all of your optimistic plans go wrong. lt doesn't have to be lengthy. ln some cases, it can be as short as a single page and still be more than adequate, although for most businesses such a plan should provide answers to these questions: 1. What suppliers would give you extended terms or carry you in case of a crunch? Why would they carry you? How long and how much? 2. What new investment 3. 4. 5. and major trade creditors on your side? Have you examined all possible Follow-Up Form sources of additional working capital in your business? Where might you have some leverage? 6. creditors. I No answer l- Not available Tighten and maintain cash controls. Cash flow control begins with the cash flow budget. lf you don't have a cash flow budget, you will have cash flow problems. You also need a sales budget or its equivalent to keep the sales level where it should be. Small sales lags can add up to big problems if not spotted earlyranging from a sluggish salesperson to a less than honest clerk. .l Requested info _l Order never received Will send check Duplicate billing L- Requested proof of deliverY I I f f f Payment previously sent Merchandise returned Payment lreing held Your cash flow tludget is a good tool for keeping overhead costs down. You have a degree of control over costs that you don't have over sales; while you Three Credit Policl' Steps 1. Divide your customer list into three groups: Prime, Good, Olher. Prime customers always pay within term; Good usuaily doi Others seldom, if ever, do. Look for similarities within the groups. What kinds of customers are Prime or Good? How do they differ from Other? Look for ways to upgrade as many customers as possible to Prime and Good. Remember: You don't have a sale until you're paid. can almost always cut costs, you can't generate sales (especlally cash sales) whenever needed. lf you could, you'd never have a cash flow problem. Every budget has some fat in it. Tightening control means always asking whether this or that purchase or expenditure will have a positive effect on your busi- 2. 3. ness. lf there is no clear answer, examine the expenditure closely. This effort must be consjstent to work. All the controls in the book mean nothing unless they're applied-whether the control is a separation of purchasing from paying, making sure that bills and reorders go out when they should or even keeping a physical count of the inventory. Credit and collection. The cost of extending credit is one of those hidden costs that eats up working capital. Very few smaller businesses have explicit credit policies. lf they did, they could dramatically increase both profits and the quality of their current assets. Investigate accepting credit cards and encouraging customers to use them. They cost little in return for the headaches they save you. Consider the cost, in direct comparison to bad-debt losses and in time, effort and attention that slow-pay accounts cost you. The added costs of capital tied up in receivables, for example, is frequently greater than any fee charged by the financial institution supporting the transaction. Use a follow-up form (see page 26 for a sample) each time you call a lagging account. The completed slip will provide back-up information and should be filed for reference on further calls. Remember to ask for specific payments on specific dates. lf payment is not received, call back and ask again. SoeakinE About Financial Management Accounts payable Accounts receivable Balance sheet Budget Cash flow Liabilities resulting from purchases of goods or services on an open'account basrs. Amounts owed by customers as a result of clelivering goods or services and extending credit in the ordinary course of business. A financial statement that shows a company's assets and liabilities. A forecast of revenues and expenditures for a specific period of business actlvity. Usually refers to net cash provided by operating activities; there is also cash flow from financing and investing. A report on cash receipts and cash payments for a particular period. Cash flow statement General ledger A record containing the group of accounts that supports the amounts shown in the financial statements. The difference between sales revenue and cost of goods sold. A report of all revenues and expenses pertaining to a specific period. Tlre number of times during an accounting period that a business sells the value of its inventory. Turnover is calculated by dividing the cost of goods sold by the average inventory during the period. (Average inventory is figured by adding beginning ancl ending inventory, then dividing by two.) An agreement by which a financial institution (usually a bank) holds funds available for a business's use. A secured LOC is ordinarily renewed annually; an unsecured line may have to be paid down once a year. Gross profit lncome statement lnventory tutnover Line of credit (LOC) Project Your Cash F low Cash Flow is the movement of cash in and out of your business within a given period, usually a week or a month. It is not the same as profit. A business can show a profit on the day it goes bankrupt-simply because it has insufficient cash to meet its obli$ations. Cash Flow Protection is looking ahead to determine what your cash flow is Iikely to a business running. be-thjs is critical to keeping Cash ln and Cash Out are the dynamic sections of your cash-flow projection, representing the flow of money in and out of a business. Electronic cash flow worksheets are available at. Elements of Cash Flow 1. 2. Starting Cash (or starting balance). Each monthly projection begins with the amount of cash you have on hand at the start of the month. Your Starting Cash is the same number as the previous month's Ending Cash. Cash ln. This section of the statement is also called "sources of cash." lt includes all cash received during the month. There are several possible sources: a. Sales are a primary source of cash, but remember to include only cash sales. Sales that have been invoiced do not represent money you can spend this month, so list only the cash sales you expect to have. Month 1 STARTING CASH CASH IN s2,5OO ') Cash Sales Paid Receivables Other TOTAL CASH IN s1,ooo o 0 s1,OOO b. Paid Receivables are those sales that were previously invoiced and have been paid this month. lt is important to project accurately when you expect to be paid-3O days, 60 days, etc. lf a sale made in January is actually going to be collected in March, you want your projections to be realistic and reflect that lag time. CASH OUT Rent Payroll Other TOTAL CASH OUT s700 S1,ooo $300 c. lnterest. When your business is fortunate enough to have money in the bank, it will be earning interest. d. Other. Additional sources of cash might be a bank loan, sale of stock or the sale of an asset such as a company car. sz,ooo ENDING BALANCE CHANGE $1t509, 3. Cash Out. This section is also referred to as "uses of cash." Cash leaves the business in two basic ways: fixed expenses and variable expenses. (Cash Flow) a. Fixed Expenses are incurred regularly and are not easily eliminated. Generally, they do not fluctuate with sales volume; they are "fixed" from month to month: rent and payroll, payroll taxes, estimated taxes, utilities, interest on loans and insurance payments. b. Variable Expenses can change from month to month and often vary with sales volume or production volume. They can be more easily changed than fixed expenses. Some examples: supplies, commissions, advertising, raw materials, consulting services and promotion. 4. Ending Cash (or Ending Balance) is how much cash is left atthe end of the month. lt is the result of the numbers in Cash ln and Cash Out. Simply add the Starting Cash to Total Cash ln and then subtract Total Cash Out. The cash you end the month with is the cash you have to start the next month-so, you get the number for Starting Cash by copying if from the previous month's Endin$ Cash' 5. Gash Flow is the amount that has flowed through the business (see box below). lt is a measure of what has happened that month. lf nothing has happened-say you began with $l-,000 and didn't take any cash in or pay out a nickel-you would end up with $1,000, but your Cash Flow would be $0. To calculate Cash Flow, subtract the Ending Cash from the Starting Cash. The secret to success is positive cash flow. Quarterly Cash Flow Worksheet (by Month) MONTH: STARIING CASH CASH IN Cash Sales Paid Receivables TOTAL CASH IN CASH OUT Rent Payroll TOTAT CASH OUT ENDING CASH CHANGE (Gash Flow) Ch aft Your Business Progress Once you're open for business, how should you monitor your company's health and progress? Besides sales and profits, what other indicators will help you measure performance? And how often should you track those measurements? As your company grows, it will be in a constant state of flux, with hundreds of variables at play each day. Each of them will have a pull on you and your employees, dictating behavior and priorities. But at the end of the day, which variables will really count? One of the most significant management tools for growing a company is the development of a clear set of performance indicators that represent the criteria from which the business is managed and monitored. These critical numbers are most often associated with financial performance-sales, margins and accounts receivables. But other important aspects of your business also impact overall performance, such as customer-service ratings, inventory, number of complaints, quality statistics, employee morale and satisfaction ratings, sales figures and collections. To ensure your success as a new business owner, make a list of the factors that are most important to your company's performance and then select a group of key indicators to track on a regular basis. Choose those factors that are critical to sustaining you company's competitive advantage as well as maintaining its general health. The tracking reports to which you refer most often should be kept short and, therefore, user-friendly. For instance, you probably should only track three of four key indicators-at most-on a daily basis, They should be the ones that can have the most significant impact on your business. A more detailed report may be more appropriate for weekly or monthly review. Areas to consider for performance measures include: . Sales growth (number of calls, close rations, etc.) \\hy Are You in Business? You and your employees should be able to articulate the true mission of your company and hence, its critical-success factors., 7. 8. How do we make life better for our customers? How do we create competitive advantages for our customers? What do we want our reputation to be? Horlr to Take Your Company's Pulse Which numbers should you keep an eye on to monitor your business's financial health-and how often should you check them? Here are 10 critical checkpoints: L. 2. 3. 4. 5. 6. 7, 8. 9. Weekly Updates Current cash position (how much cash was received, when and from whom) Cash disbursements (e.g., payroll, materials and purchasing) New sales . . . . Cash management (accounts receivable/payable, cash balances, inventory levels, future projections) Profit measures (key drivers of profitability) Customer feedback scores (e.9., service ratings) Employee feedback scores (periodic surveys measur- Accounts receivable (beginning balances, outstanding credit and cash receivables) Accounts-payablepayments Order backlog Number of employees (with a productivity metric; e.g., sales per employee) ing morale, commitment, communication, etc.) The development of performance measurements is one of the most important keys to long-term growth. lt will facilitate management control and communication throughout your company and it will support your efforts to perform at the highest level. Once successfully launched and in business, re-evaluate your need to incorporate or form an LLC to protect yourself and your family. Monthly Updates Inventory (with accounting or physical tests of accuracy) Accounts-receivable average days outstanding breakdown) 10. Accounts-payable obligations (with aging
https://www.scribd.com/document/32685927/How-to-Start-a-Business
CC-MAIN-2017-30
refinedweb
11,704
55.54
? Well, * In the first case, we need to #undef the macro and introduce a declaration in namespace std; * In the second case, we also #undef the macro and introduce a declaration. But here, we need to be careful and introduce a function name with an external "C" linkage -- see below. |. You are right. | Maybe we should just #undef the macro, in this case, which would also | get us rid of the optimization provided by the preprocessor macro? If the target provides *both* forms then it is OK to #undef the macro and introduce a function declaration with "C" linkage in namespace std. | What I don't understand is why it is so important that the inline | function in the std namespace be extern "C". To introduce a plateform independent behaviour -- this is actually more than a quality of implementation issue. Consider the following example. Consider a target which provides only the macro version (I'm not sure that is valid, but let's make that assumption for the sake of exposition). If we didn't mark the corresponding function with a C linkage then the following will be OK #include <xxx> // this happens to include <cstdlib> // but user Jack doesn't know // This is silly but happens from time to time namespace MyNamespace { // Jack's "improved" version of mblen inline int mblen(const char* p, size_t l) // WRONG { /* ... */ } } Jack will use MyNamespace::mblen() in his code and that will "works" on his target until his code is moved to a target which provides both forms of mblen(). Then user Jack will send us a bug report saying his code used to work on target foo. We could then reply "that was not guaranteed to work, as it is unspecified whether mblen() has C linkgage or not". That abstract answer will be abstractly right but will be of no much practical help for user Jack. Since we have the ability to catch that error earlier, I don't see why we should not do it in the first place. And, removing that "unspecified status" from our implementation introduces one more deterministic bit into the library behaviour. I don't see any compeling reason not to do it. Am I still mistunderstanding your situation? -- Gaby CodeSourcery, LLC
http://gcc.gnu.org/ml/libstdc++/2000-12/msg00296.html
crawl-001
refinedweb
375
60.45
Sample Transforms for taking samples of the elements in a collection, or samples of the values associated with each key in a collection of key-value pairs. Examples In the following example, we create a pipeline with a PCollection. Then, we get a random sample of elements in different ways. Example 1: Sample elements from a PCollection We use Sample.FixedSizeGlobally() to get a fixed-size random sample of elements from the entire PCollection. Output: Example 2: Sample elements for each key We use Sample.FixedSizePerKey() to get fixed-size random samples for each unique key in a PCollection of key-values. import apache_beam as beam with beam.Pipeline() as pipeline: samples_per_key = ( pipeline | 'Create produce' >> beam.Create([ ('spring', '🍓'), ('spring', '🥕'), ('spring', '🍆'), ('spring', '🍅'), ('summer', '🥕'), ('summer', '🍅'), ('summer', '🌽'), ('fall', '🥕'), ('fall', '🍅'), ('winter', '🍆'), ]) | 'Samples per key' >> beam.combiners.Sample.FixedSizePerKey(3) | beam.Map(print)) Output: Related transforms Last updated on 2021/02/05 Have you found everything you were looking for? Was it all useful and clear? Is there anything that you would like to change? Let us know!
https://beam.apache.org/documentation/transforms/python/aggregation/sample/
CC-MAIN-2021-31
refinedweb
173
60.11
Threads are subroutines that can run concurrently. Every Haskell program begins with one thread, called the main thread. Starting an additional thread is called forking a thread. import Control.Concurrent (forkIO) import Control.Concurrent.STM.TVar import Control.Monad.STM import Data.Foldable (for_) import System.IO = main do Setting the output stream’s buffer mode to line-buffering will make the output of this example more readable. LineBuffering hSetBuffering stdout <- atomically (newTVar 0) tasksCompleted let We define a function called task, which: = task x do - Prints three times; then 1..3] $ \i -> for_ [putStrLn (x ++ ": " ++ show i) - Increments the taskCompletedvariable. $ atomically + 1) modifyTVar' tasksCompleted ( We run task three times: Once in the main thread, and then twice in new forked threads. "main" task "forkA") forkIO (task "forkB") forkIO (task At this point, our two forked threads are now running, and we do not want the main thread to end (thus terminating the program) before the other threads have time to finish. So we wait until the value of tasksCompleted reaches 3. $ atomically do <- readTVar tasksCompleted x == 3) check (x putStrLn "done" $ runhaskell threads.hs The lines from task "main" are printed first; no fork has occurred yet. main: 1 main: 2main: 3 Because task "forkA" and task "forkB" run concurrently, their putStrLn effects are interleaved. forkA: 1 forkB: 1 forkA: 2 forkB: 2 forkA: 3 forkB: 3done The interleaving is nondeterministic; if you run this program multiple times, you may see different orderings. $ runhaskell threads.hs main: 1 main: 2 main: 3 forkA: 1 forkB: 1 forkB: 2 forkB: 3 forkA: 2 forkA: 3done
https://typeclasses.com/phrasebook/threads
CC-MAIN-2021-43
refinedweb
265
65.73
Although Web development tools are rapidly progressing, they still lag behind most graphical user interface (GUI) toolkits such as Swing or VisualWorks Smalltalk. For example, traditional GUI toolkits provide layout managers, in one form or another, that allow layout algorithms to be encapsulated and reused. This article explores a template mechanism for JavaServer Pages (JSP) that, like layout managers, encapsulates layout so it can be reused instead of replicated.. . Using. Optional content All template content is optional, which makes a single template useful to more Webpages. For example, Figure 2.a and Figure 2.b show two pages -- login and inventory -- that use the same template. Both pages have a header, footer, and main content. The inventory page has an edit panel (which the login page lacks) for making inventory changes. Below, you'll find the template shared by the login and inventory pages: <%@ taglib <tr><td width='60'></td> <td><template:get</td></tr> <tr><td width='60'></td> <td><template:get</td></tr> <tr><td width='60'></td> <td><template:get</td></tr> <tr><td width='60'></td> <td><template:get</td></tr> </table> ... The inventory page uses the template listed above and specifies content for the edit panel: <%@ taglib ... <template:put ... </template:insert> In contrast, the login page does not specify content for the edit panel: <%@ taglib <template:put <template:put <template:put <template:put </template:insert> Because the login page does not specify content for the edit panel, it's not included. Role-based content Web applications often discriminate content based on a user's role. For example, the same JSP template, which includes the edit panel only when the user's role is curator, produces the two pages shown in Figures 3.a and 3.b. The template used in Figures 3.a and 3.b uses template:get's role attribute: <%@ taglib</td></tr> ... </table> ... The get tag includes content only if the user's role matches the role attribute. Let's look at how the tag handler for template:get uses the role attribute: public class GetTag extends TagSupport { private String name = null, role = null; ... public void setRole(String role) { this.role = role; } ... public int doStartTag() throws JspException { ... if(param != null) { if(roleIsValid()) { // include or print content ... } } ... } private boolean roleIsValid() { return role == null || // valid if role isn't set ((javax.servlet.http.HttpServletRequest) pageContext.getRequest()).isUserInRole(role); } } Implementing templates The templates discussed in this article are implemented with three custom tags: template:insert template:put template:get The insert tag includes a template, but before it does, put tags store information -- a name, URI, and Boolean value specifying whether content should be included or printed directly -- about the content the template includes. template:get, which includes (or prints) the specified content, subsequently accesses the information. template:put stores beans in request scope but not directly because if two templates use the same content names, a nested template could overwrite the enclosing template's content. To ensure that each template has access only to its own information, template:insert maintains a stack of hashtables. Each insert start tag creates a hashtable and pushes it on the stack. The enclosed put tags create beans and store them in the newly created hashtable. Subsequently, get tags in the included template access the beans in the hashtable. Figure 4 shows how the stack is maintained for nested templates. Each template in Figure 4 accesses the correct footer; footer.html for template_1.jsp and footer_2.html for template_2.jsp. If the beans were stored directly in request scope, step 5 in Figure 4 would overwrite the footer bean specified in step 2. Template tag implementations The remainder of this article examines the implementation of the three template tags: insert, put, and get. We begin with sequence diagrams, starting with Figure 5. It illustrates the sequence of events for the insert and put tags when a template is used. If a template stack does not already exist, the insert start tag creates one and places it in request scope. A hashtable is subsequently created and pushed on the stack. Each put start tag creates a PageParameter bean, stored in the hashtable created by the enclosing insert tag. The insert end tag includes the template. The template uses get tags to access the beans created by put tags. After the template is processed, the hashtable created by the insert start tag is popped off the stack. Figure 6 shows the sequence diagram for template:get. Template tag listings Tag handler implementations for the template tags prove straightforward. Example 3.a lists the InsertTag class -- the tag handler for template:insert. Example 3.a. InsertTag.java
http://www.javaworld.com/article/2076174/java-web-development/jsp-templates.html
CC-MAIN-2014-10
refinedweb
775
57.06
0 Hi I have written a program, it doesn't work and i can't figure out why. It does compile, but it doesn't run. The whole program: #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { int a; int j; int c; int d; int dig; c = 0; int i; a = 0; d = 0; for (i = 0;i == i;i++) { a = a + i; // from this for (j = 1;j < a; j++){ dig = a / j; if (isdigit(dig)){ d++; } //to this doesn't work if (d == 500) { printf("%d\n",a); system("sleep 10s"); } else { d = 0; } } } return 0; } The part which doesn't work should count how many divisors the number 'a' has. What am i doing wrong?
https://www.daniweb.com/programming/software-development/threads/444506/segmentation-fault-in-my-program
CC-MAIN-2017-09
refinedweb
122
89.99
Class representing a Lorentz Boost along the Z axis, by beta. For efficiency, gamma is held as well. Definition at line 37 of file BoostZ.h. #include <Math/GenVector/BoostZ.h> Default constructor (identity transformation) Definition at line 30 of file BoostZ.cxx. Definition at line 50 of file BoostZ.cxx. Get components into a Scalar beta_z. Definition at line 44 of file BoostZ.cxx. Return inverse of a BoostZ. Definition at line 99 of file BoostZ.cxx. Invert a BoostZ in place. Definition at line 94 of file BoostZ.cxx. Lorentz transformation operation on a Minkowski ('Cartesian') LorentzVector. Definition at line 83 of file BoostZ.cxx. Lorentz transformation operation on a LorentzVector in any coordinate system. Definition at line 138 of file BoostZ.h. Re-adjust components to eliminate small deviations from a perfect orthosyplectic matrix. Definition at line 64 of file BoostZ.cxx. Set components from a Scalar beta_z. Definition at line 32 of file BoostZ.cxx.
https://root.cern.ch/doc/master/classROOT_1_1Math_1_1BoostZ.html
CC-MAIN-2020-05
refinedweb
159
55.3
One benefit of Grails is its robust and versatile controller logic. It can render responses in a multitude of formats, validate input, and handle a lot of processing behind the scenes. This is all great and helpful during implementation, but when it comes to testing controllers, it is easy to get tripped up knowing exactly what to mock out and what to verify. In this post I’ll try to document some common and no-so-common issues I’ve run across unit testing controllers. I’ll focus primarily on HTML and JSON, although most of the logic can be applied to XML responses as well. Setup Let’s first start with the basics. In order to use some of the framework that Grails provides for testing, we will need to extend the ControllerUnitTestCase in our testing class. Among other things, for Grails to properly hook up the controller variable to our intended controller class, we need to follow two rules, as explained in the Grails documentation: - Your test class needs to be in the same package as the controller class under test - The name of your test class needs to be “<YourControllerName>Tests” Doing these two steps will make testing our controller a lot easier. Finally, as with all Grails unit tests, be sure to include the setUp() and tearDown() methods (note the camel-case) to ensure everything works properly: protected void setUp() { super.setUp() } protected void tearDown() { super.tearDown() } Input In addition to the common mocks that you may encounter in regular service and domain object unit tests, controllers have a few extra properties that may be helpful to know. Most of these are specific to web applications, and deal with things such as the Spring MVC scope objects, requests, and URL parameters. Thankfully most of the hard work has been done for us since we extended the ControllerUnitTestCase class. All we have to do is understand the purpose of these methods and how to use them effectively. Let’s start with a basic controller action and command object: def foo = { SimpleCommandObject simpleCommandObject -> if (params.id) { render (template: 'fooTemplate', model: [ simpleCommandObject: simpleCommandObject ]) } else { def response = [ note: 'No id' ] render response as JSON } } class SimpleCommandObject { Long id String code static constraints = { code (nullable: false, blank: false, size: 1..100) } } Obviously this is a pretty non-sensical action, but it will serve for example’s sake. The first thing we notice is that there is a command object being used for validation. Even though the parameters are bound to the object when a web request is made, when testing we will need to manually set the properties on the object and pass it in to the action when we call the controller action. Simply setting the params will not work as the two are mutually exclusive. So we can set one up like so: void testFooCommandObject() { SimpleCommandObject simpleCommandObject = new SimpleCommandObject(id: 1, code: 'Testing') controller.foo(simpleCommandObject) } If we want to ensure that the object meets constraints, we can call mockCommandObject(SimpleCommandObject.class) before creating our command object or mockForConstraintsTests(SimpleCommandObject, [simpleCommandObject]) afterwards to add the validate() suite of methods. The two are mostly equivalent, and most importantly call the addValidateMethod that we need. So now that we have successfully added a command object to our tests, the step is to mock the parameters. Luckily Grails makes this simple as well, and provides us with a map we can use. To add the id key that we need for the if statement in our action, we write: mockParams.id = 1 Quick and painless. The same can be done with mockFlash, redirectArgs, forwardArgs, and mockSession, although mockSession is a Spring MockHttpSession, and not a map. Nonetheless, we can set up almost all the expectations for our controller using those variables. Response The crux of most unit tests is validating the output. Since Grails is so flexible with the output that controllers can render, this can be the trickiest part of testing controllers. I’ll give a brief rundown of some of the most common scenarios and how to test them. Looking back to our original example, we can see that if we have an id in our params, we render a template and pass the command object through the model. We can verify this behavior by extending our test: void testFooWithId() { mockCommandObject(SimpleCommandObject.class) // Option 1 SimpleCommandObject simpleCommandObject = new SimpleCommandObject(id: 1, code: 'Testing') mockForConstraintsTests(SimpleCommandObject, [simpleCommandObject]) // Option 2. Only need one of the two mockParams.id = 1// Remember that the command object will not auto-populate this, or vice versa def response = controller.foo(simpleCommandObject) assertEquals simpleCommandObject.id, response.simpleCommandObject.id assertEquals simpleCommandObject.id, controller.renderArgs.simpleCommandObject.id assertEquals 'fooTemplate', controller.renderArgs.template } A few things to note here. The most obvious is that there are numerous ways to verify the model from the controller. Whether passing the model in explicitly, or if we simply return a map from the action, the return value will have that object. Secondly, we can validate the template name through the renderArgs call. It’s important to note that renderArgs is just a map as well, so if we were rendering a view rather than a template, we would be able to access that property through renderArgs.view. The same holds true for redirectArgs and forwardArgs. These are useful is we are rendering a gsp, but what if we want to return plain text, or JSON? For that we need to make a few changes to our tests. First let’s remove the mockParams.id declaration so that we fall to the else part of our action. This will mean the controller will return a JSON response using the render syntax. We can assert that the proper JSON is rendered like so: void testFooNoId() { SimpleCommandObject simpleCommandObject = new SimpleCommandObject(id: 1, code: 'Testing') mockForConstraintsTests(SimpleCommandObject, [simpleCommandObject]) controller.foo(simpleCommandObject) def jsonResponse = JSON.parse(controller.response.contentAsString) assertEquals 'No id', jsonResponse.note } When we verify the response, we need to parse it with the grails.converters.JSON class, which then allows us to much more easily verify its contents. Now, it’s worth noting that this is just one way to render json, and that Grails 2.0 has better support for building JSON. Until then, Grails still offers a pretty lightweight and straightforward way to render JSON. One last gotcha Let’s say we were to render our response using an explicit contentType: def response = [error: 'No id'] render(contentType: "text/json") { response } Examining the controller.renderArgs, we would see that it only returns contentType:text/json, but not the map that we wanted to render. We’ve run into an issue. This article does a good job explaining the problem and a workaround, but as far as I’m aware, the only fix is change the controller metaclass’s render method or to use a different syntax for rendering. Fortunately this problem does not seem to exist for rendering xml. Last Point Hopefully this post has shed some light has shed some light on a few of the less-documented gotchas you might come across, and has demonstrated that with a little knowledge, testing Grails controllers is really quite simple. Grails’ wide array of rendering options may seem complicated at first, but fortunately it has provided us with just as extensive of a testing framework. If you have any questions or comments (or if you’re still not writing tests for your controllers!), please feel free to post here and I’ll do my best to address them. Igor Shults
https://objectpartners.com/2012/04/20/unit-testing-controllers-in-grails-1-3-7/
CC-MAIN-2018-22
refinedweb
1,256
54.02
Pre-compile and cache yer dang regular expressions By greimer on Jan 27, 2008 We have a function called hasClassName(el, cls) that checks whether a given DOM element has a given class. More and more, we're relying heavily on this function, and on certain pages it can run thousands of times. In these situations a little performance tuning can go a long way, as demonstrated here: // BEFORE function hasClassName(el, cls){ var exp = new RegExp("(\^|\\\\s)"+cls+"($|\\\\s)"); return (el.className && exp.test(el.className))?true:false; } // AFTER (function(){ var c={};//cache regexps for performance window.hasClassName=function(el, cls){ if(!c[cls]){c[cls]=new RegExp("(\^|\\\\s)"+cls+"($|\\\\s)");} return el.className && c[cls].test(el.className); } })(); This simple change cut the function's average runtime in half and reduced the page's overall onload setup time by over 25%! (According to Firebug.) All because it caches regular expressions. Edit: removed unnecessary ?: operator per Nate's comment. Why the ?: why not just return the test? Posted by Nate on January 28, 2008 at 11:15 AM MST # @Nate Some have told me they leave the literals there for clarity; I've also seen CS grads who didn't realize you didn't need the literals. @greimer Thanks for the tip, but having encountered similar constructs in the past, I'm curious if there's a "break-even" point, where once you get N elements in the cache it'd be slower to look them up than to exec them fresh? Other than testing, is there a way to compute this? Posted by kenman on January 28, 2008 at 06:33 PM MST # @kenman From experience using an Object as an associative array like that in Javascript is pretty scalable. If you're dealing with such a large number of RegExp calculations that you hit the limits of Javascript Objects then you're doing something pretty intense indeed. I don't know of a way to compute it other than testing, since performance will differ in different browsers. Give it a go. Let us know what you find. Posted by Richard on January 29, 2008 at 01:00 AM MST # @kenman I've benchmarked JavaScript performance with objects containing ten thousand properties, and adding new properties and property lookup still appears to be on the order of O(1), and performs well into the sub-millisecond range. @Nate I honestly can't remember why I used the ?: instead of just returning the test. It's probably a vestigial holdover from the early days of the function. :P Posted by Greg on January 29, 2008 at 02:27 AM MST # @myself Actually I should be careful using computer-sciencey terms like O(1). My benchmarks probably weren't scientific enough to come to that conclusion. However I stand by the "well into the sub-millisecond range" statement. Posted by Greg on January 29, 2008 at 02:38 AM MST #
https://blogs.oracle.com/greimer/entry/pre_compile_and_cache_yer
CC-MAIN-2014-10
refinedweb
490
64.2
Layer tree node points to a map layer. More... #include <qgslayertreelayer.h> Layer tree node points to a map layer. When using with existing QgsMapLayer instance, it is expected that the layer has been registered in QgsMapLayerRegistry earlier. The node can exist also without a valid instance of a layer (just ID). That means the referenced layer does not need to be loaded in order to use it in layer tree. In such case, the node will start listening to map layer registry updates in expectation that the layer (identified by its ID) will be loaded later. A map layer is supposed to be present in one layer tree just once. It is however possible that temporarily a layer exists in one tree more than just once, e.g. while reordering items with drag and drop. Create a copy of the node. Returns new instance. Implements QgsLayerTreeNode. Return string with layer tree structure. For debug purposes only. Implements QgsLayerTreeNode. emitted when a previously unavailable layer got loaded emitted when a previously available layer got unloaded (from layer registry) Write layer tree to XML. Implements QgsLayerTreeNode.
http://www.qgis.org/api/classQgsLayerTreeLayer.html
CC-MAIN-2014-42
refinedweb
185
58.18
A virtual DOM library for Dart. The goal of package:dom is to be absolutely framework or implementation agnostic and instead provide a rich but simple set of classes to represent a virtual DOM tree and utilities for working with them. By default, nodes are: JSONcodec) This should be enough to build on or extend for most implementations. Attributeand add a Mapof attributes for Element Add this to your package's pubspec.yaml file: dependencies: dom: ^0.2.0 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:dom/dom.
https://pub.dev/packages/dom
CC-MAIN-2019-26
refinedweb
119
65.73
- Tutorials - User Interface (UI) - Controlling the game Controlling the game Checked with version: 5.3 - Difficulty: Beginner We now need to turn this foundation behavior into a game. To do this we will need to move the control into a central place by creating a Game Controller. The Game Controller will set the starting player's side, either "X" or "O", keep track of whose turn it is and when a button is clicked, send the current player's side, check for a winner and either change sides or end the game. We will need a new script to do this, so let’s create one attached to its own GameObject. - Create a new Empty GameObject using Create > Create Empty. - Rename this GameObject "Game Controller". - With the Game Controller selected, - ... reset the Game Controller’s Transform component. - ... add a new script called "GameController". - File the GameController script in the Scripts folder. - Open the GameController script for editing. Again, we are using the UI toolset, so we need the appropriate namespace. - Add the UI Namespace to the top of the script. using UnityEngine.UI; The GameController script will need to know about all of the buttons in the game so it can check their state and determine if that has been a win. For this, the script should hold a collection of all of the Grid Space buttons. We will want to check the button’s Text component for the Player Side to see if there are 3 matching values in a row, so let’s make an array of the type Text. - Remove all of the sample code from the class. - Create a public Text array called "buttonList". public Text[] buttonList; The square brackets [] after the type indicate that this variable is an array. The final script should look like this: GameController Code snippet using UnityEngine; using UnityEngine.UI; using System.Collections; public class GameController : MonoBehaviour { public Text[] buttonList; } - Save this script. - Return to Unity. Now that we have created this Button List array, we must populate it with the Text components of our Grid Space buttons. Remember, order here is important. It is also important that we link the child Text GameObjects to the Button List array, not the parent Grid Space GameObjects. One way of populating the Button List array on the Game Controller in the Inspector is to set the size of the array to 9 and then drag each Text GameObject, one at a time, into the array. This is a bit tedious and time consuming. There is, however, an easier way to do this, and it involves "locking" the Inspector Window and dragging all GameObjects at once into the array. - Select the Game Controller GameObject in the Hierarchy. - In the upper right of the Inspector Window, click the Lock button. What this does is prevent the Inspector Window from changing focus from current selection, in this case the Game Controller. If we didn't do this, when, in the next step, we select the child Text GameObjects, the focus of the Inspector would change to these child Text GameObjects and we wouldn't be able to drag them into the array on the Game Controller. It's also worth noting that we can open multiple Inspector Windows, locking only the ones we want. This allows for complex views of various GameObjects in the Hierarchy and Project Windows. - Open the 9 Grid Space buttons in the Inspector using the turn down arrow. - Using + click on Windows or + click on the Mac, select only the child Text GameObjects from every Grid Space GameObject. - Drag these onto the locked Inspector for the Game Controller GameObject and drop them on the Button List name above the Size field. When the dragging cursor is in the correct position, a small "+" icon will appear next to the cursor. If you miss a the location, the cursor will change to show a circle-and-slash icon indicating the drop will fail. Successfully dropping the 9 Text GameObjects will automatically size the Button List array and add all of the items to the array. In this particular case, it is important to check the order now. These should be in order automatically, but it’s worth checking to make sure. - Select each element in order by clicking on the element field. This should highlight the GameObject linked as a reference. Each element in the Button List array should correspond in order to the correct GameObject. Element 0 should be associated with Grid Space, Element 1 should be associated with Grid Space (1), Element 2 should correspond with Grid Space (2) and so on. If this is correct, - Unlock the Inspector Window. - Save the scene. Now, for the player to take a turn, the Grid Space button needs to inform the Game Controller that a move has been made and win conditions need to be checked. This means that the Grid Space button needs to have a reference to the GameController component. This can be held in a local variable with of the type GameController. One way to associate the GameController component with each of the Grid Space buttons in the scene would be to make this variable public and populate this public property in the Inspector for each Grid Space button instance in the scene. We can’t make the association between the Grid Space prefab in the Project View and the instance of the Game Controller in the scene, as the assets cannot hold references instances. All this dragging can be a bit tedious, but it also opposes one of the basic workflow related to using a prefab: we can’t simply drop the prefab into the scene and have it "just work". Another way to associate the GameController component with each of the Grid Space buttons in the scene is to do it in code. Now, if we do this in code, we could have each Grid Space button search the scene's Hierarchy for the Game Controller when they are first created at the start of the game. The Game Controller, however, already has a list of all of the Grid Space buttons in the buttonList array. In our case, I feel it would be better for the Game Controller to push the reference to itself to the buttons directly. To push the references to the Grid Space buttons, the GridSpace script will need a local variable with of the type GameController and a public function to set it. - Open the GridSpace script for editing. - Add a new private variable to hold a reference to the GameController. private GameController gameController; - Create a new public function which returns void that can take a GameController as a parameter and assign it to the gameController variable as a reference. public void SetGameControllerReference (GameController controller) { gameController = controller; } The final script should look like this: GridSpace Code snippet using UnityEngine; using System.Collections; using UnityEngine.UI; public class GridSpace : MonoBehaviour { public Button button; public Text buttonText; public string playerSide; private GameController gameController; public void SetGameControllerReference (GameController controller) { gameController = controller; } public void SetSpace () { buttonText.text = playerSide; button.interactable = false; } } - Save this script. - Open the GameController script for editing. - Create a new function that returns void called "SetGameControllerReferenceOnButtons". void SetGameControllerReferenceOnButtons () { } - In SetGameControllerReferenceOnButtons write code that loops through all of the buttons. This is best done with a for loop that iterates through all of the elements in the buttonList array. for (int i = 0; i < buttonList.Length; i++) { } The loop is easy. Loop through the entire length of the Button List... but the Button List is referencing the child Text GameObjects and we need to get a hold of the GridSpace component on the parent of the Text GameObjects. How can we do this? There is a convenient call we can make to GetComponentInParent. With this we can give GetComponentInParent a type, in our case GridSpace, and it will return that component if it exists. - Add code to check each item in the Button List and set the GameController reference in the GridSpace component on the parent GameObject. buttonList[i].GetComponentInParent< GridSpace>().SetGameControllerReference(this); The keyword this refers to this class - or the class that the code is written in. By passing in this to SetGameControllerReference we are passing in a reference to this instance of the class. Each GridSpace instance will use this to set their reference to the GameController. The function SetGameControllerReferenceOnButtons now needs to be called when the game starts. - Create an Awake function that returns void. - Call SetGameControllerReferenceOnButtons. void Awake () { SetGameControllerReferenceOnButtons(); } Now that the buttons know about the GameController and have a proper reference to it, we want the buttons to do two things: Get the Player Side from the Game Controller before the buttons set the Text value so the buttons know what symbol to place in their grid space and, once they’ve done that, inform the Game Controller that the turn is now over so that the Game Controller can check the win conditions and either end the game or change the side taking the turn. To do this, we need to set up additional functionality in the GameController script. - Open the GameController script for editing. - Create a new empty public function that returns string called "GetPlayerSide". public string GetPlayerSide () { return "?"; } To successfully compile, GetPlayerSide must return some string value, so we will add a dummy line here for now returning "?". - Create a new empty public function that returns void called "EndTurn". public void EndTurn () { Debug.Log("EndTurn is not implemented!"); } Note how, at this stage in our development, we have created two essentially empty functions. We know the basic idea of what we want these functions to do but we have not yet developed the content. We can "fill these out" later, but by creating these empty but viable functions, we can continue our development in another part of our game without getting lost in a tangle of other code we are not yet ready to think about in detail. Both of these functions do have indicators that they are not complete if we ever run the game to test. GetPlayerSide returns "?" and EndTurn prints a line to the console warning us that "EndTurn is not implemented!". This way it will be clear that we will need to go back and work on these functions later. The final script should look like this: GameController Code snippet using UnityEngine; using UnityEngine.UI; using System.Collections; public class GameController : MonoBehaviour { public Text[] buttonList; void Awake () { SetGameControllerReferenceOnButtons(); } void SetGameControllerReferenceOnButtons () { for (int i = 0; i < buttonList.Length; i++) { buttonList[i].GetComponentInParent<GridSpace>().SetGameControllerReference(this); } } public string GetPlayerSide () { return "?"; } public void EndTurn () { Debug.Log("EndTurn is not implemented!"); } } - Save the script. With these two new public functions in GameController we need to make use of them in GridSpace. - Open the GridSpace script for editing. - In the function SetSpace, - ... change the first line so that buttonText.text is assigned the value of GetPlayerSide directly from the current value in GameController. buttonText.text = gameController.GetPlayerSide(); - In the function SetSpace, - ... as the last line in the function, add a line calling EndTurn. gameController.EndTurn(); At this point, it is worth remembering that code in a function is executed in order, from top to bottom, so by placing the call to EndTurn at the end of the function, we know it will be called last, after all of the other business in SetSpace is done. We now no longer need a local variable for playerSide. This value is now taken directly from the Game Controller. - Remove the line defining the variable playerSide. public string playerSide; The final script should look like this: GridSpace Code snippet using UnityEngine; using System.Collections; using UnityEngine.UI; public class GridSpace : MonoBehaviour { public Button button; public Text buttonText; private GameController gameController; public void SetGameControllerReference (GameController controller) { gameController = controller; } public void SetSpace () { buttonText.text = gameController.GetPlayerSide(); button.interactable = false; gameController.EndTurn(); } } - Save the script. - Return to Unity. - Enter Play Mode. - Test by clicking any of the spaces. We should see that everything now works, at least technically. It may look bad that the spaces are getting a "?" from the Game Controller and every turn our console tells us "EndTurn is not implemented!", but the Player Side value is now coming from the Game Controller and when the player takes their move by clicking a button, control of the game is handed back to the Game Controller to process the turn. We have now taken our foundation game play behavior away from the button elements themselves and expanded it so we now have overall control from a central point. In the next lesson we will test the game for a win.
https://unity3d.com/learn/tutorials/tic-tac-toe/game-control?playlist=17111
CC-MAIN-2018-09
refinedweb
2,106
64.41
Created on 2013-08-26.15:50:22 by irmen, last changed 2014-06-25.16:04:09 by zyasoft. When creating an ipv4 socket and binding it on ipaddr_any, getsockname returns an ipv6 address: >>> s=socket(AF_INET, SOCK_STREAM) >>> s.bind(("",0)) >>> s.listen(1) >>> s.getsockname() (u'0:0:0:0:0:0:0:0', 58526) Expected behavior: return the ipv4 address "0.0.0.0" instead.. Same result with the new socket-reboot code in beta 3, but this is not surprising since this part is unchanged (the internal function _socket._get_jsockaddr) Target beta 4 Also need to fix the nearly identical issue (from an implementation perspective) as reported in #2079: from socket import * s=socket(AF_INET6, SOCK_STREAM) s.bind(("",0,0,0)) s.listen(1) assert len(s.getsockname()) == 4 Netty4 is strange... you can bind its ServerBootstrap with an Inet4Address, but when you query the Channel it returns for its local address, you get an Inet6Address! Here's a print-peppered _realsocket.listen() method: def listen(self, backlog): # ... print 'Binding to {:s} with type {:s}'.format(repr(self.bind_addr.getAddress()), type(self.bind_addr.getAddress())) future = b.bind(self.bind_addr.getAddress(), self.bind_addr.getPort()) # ... self.channel = future.channel() localaddr = self.channel.localAddress() print 'The channel is bound to {:s} with type {:s}'.format(repr(localaddr.getAddress()), type(localaddr.getAddress())) # ... And what you get when you execute that modified method: Binding to /0.0.0.0 with type <type 'java.net.Inet4Address'> The channel is bound to /0:0:0:0:0:0:0:0 with type <type 'java.net.Inet6Address'> And that's why you get an IPv6 '0' address from getsockname() after binding it with IPv4 '0' address. As for @zyasoft test case outputting the correct number of tuple elements for AF_INET6 socket address, here's a simple patch to address just that. The original issue still remains since I don't know how to work around that Netty 4 quirk yet. How about this hack-ish workaround? Merged in this commit:
http://bugs.jython.org/issue2078
CC-MAIN-2018-05
refinedweb
336
52.46
This is a tutorial on coding a basic "hello world" JavaFX application. We'll take a look at scenes, nodes and the stage and create a simple window to get started with JavaFX. We're going to move on in the next tutorials to look at Scene Builder, actions and stylesheets. At the moment I'm not sure what direction future tutorials will take, but we'll certainly build a little demo application of some sort, and it might be interesting to investigate 3D graphics, who knows ... App.java: import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; public class App extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Group root = new Group(); Scene scene = new Scene(root, 600, 400); primaryStage.setScene(scene); primaryStage.setTitle("Hello World!"); primaryStage.show(); } } Download complete code here.
https://caveofprogramming.com/javafx-tutorial-video/hello-world-javafx.html
CC-MAIN-2018-09
refinedweb
150
50.02
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. You have to write a create function on that object. There are loads of examples on the web. You just have to write a create function then check if those values are different from zero. If they are you call the create of the super. If they are zero you can create a osv error. def create(self, cr, uid, vals, context=None): if(vals.get('field1'))==0: raise osv.except_osv(_('Warning'), _('Value must be different from zero')) else: return super(module_name, self).create(cr, uid, vals, context) It's a generic way to do it. But basically it's what you need. If it helped you please mark the answer as correct to help others. Below your question there is a section that now says "1 answer". There is a tick circle below a number and that number is to vote for the answer. You have to do it on all your questions answered because this helps to many people to find quickly answers. If the answer is correct you have to check it, if other answer helped you, you have to vote for it. Hi Grover Menacho, I also want to know how to validate float data type time field. For example in the validation code float(time) it accepts the format only xx:yy and not accept other format time for example 100:00 pl given me sample code based on this. Thanks I don't want to do it in create function. That validates when we save the entire form and that is a custom validation done by us. We need a way to have automatic validation just like the validation for the mandatory fields (Char, date) when they are empty. But integer and float have default value of 0. Because of that, the validation of mandatory field is not applied. Its not fair About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-validate-float-field-24690
CC-MAIN-2017-26
refinedweb
365
66.64
C library function - memchr() Description The C library function void *memchr(const void *str, int c, size_t n) searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to by the argument str. Declaration Following is the declaration for memchr() function. void *memchr(const void *str, int c, size_t n) Parameters str -- This is the pointer to the block of memory where the search is performed. c -- This is the value to be passed as an int, but the function performs a byte per byte search using the unsigned char conversion of this value. n -- This is the number of bytes to be analyzed. Return Value This function returns a pointer to the matching byte or NULL if the character does not occur in the given memory area. Example The following example shows the usage of memchr() function. #include <stdio.h> #include <string.h> int main () { const char str[] = ""; const char ch = '.'; char *ret; ret = memchr(str, ch, strlen(str)); printf("String after |%c| is - |%s|\n", ch, ret); return(0); } Let us compile and run the above program, this will produce the following result: String after |.| is - |.tutorialspoint.com|
http://www.tutorialspoint.com/c_standard_library/c_function_memchr.htm
CC-MAIN-2014-52
refinedweb
201
60.55
Innovations in SAP Master Data Governance 7.0 SP02 (Feature Pack) May the 19th be with you! May 19th marked a great day for our SAP MDG customers. After an entirely overbooked and extremely successful Ramp-Up that started in November, SAP MDG 7.0 was released for general availability. In addition, SAP Master Data Governance 7.0 SP02 (Feature Pack) was released to customers on the same day, and marks the new go-to release that from now on everyone who is planning to install SAP MDG should consider. The MDG SP02 (Feature Pack) is very easy to consume. Similar to SAP MDG 7.0, it can be installed on top of Enhancement Package 6 for SAP ERP 6.0 as well as on top of Enhancement Package 7 for SAP ERP 6.0. For existing installations of SAP ERP 6.0 EhP6 or SAP MDG 6.1, this means that you don’t need to upgrade to any higher Enhancement Package, but can just upgrade to SAP MDG 7.0 SP02 in that system. What’s new in SAP MDG 7.0 SP02 (Feature Pack)? The Feature Pack builds on SAP MDG 7.0. With that release, we firstly enabled faster search with SAP HANA, duplicate detection, cleansing and matching. We secondly provided better usability for all standard and custom-defined master data objects, and thirdly, we delivered a more flexible foundation for higher business efficiency and refined process control. In addition to that, the Feature Pack now provides a further improved user experience and easy access for business users, for example, by offering device-independent SAP Fiori apps for master data request scenarios and real-time insight into governance processes by enabling “smart business” KPIs. SAP MDG Fiori apps for master data requests SAP Fiori apps enable request scenarios for multiple master data domains like Business Partner, Supplier, Customer, Material, Cost Center, and Profit Center. Business users can access these apps from their device of choice. They will then enter some basic data, optionally run a duplicate check to see if the master data already exists, attach supportive documents to their request as needed, and submit their request. This will trigger the creation of an SAP MDG change request, which is forwarded to the next person for completion or approval. Figure 1: SAP MDG Fiori app that allows business users to request a new cost center SAP Smart Business for real-time insights into SAP MDG process KPIs The use of SAP HANA is optional in SAP MDG 7.0. However, if you decide to run SAP MDG on top of SAP HANA SAP MDG uses SAP HANA’s capabilities, for example, for duplicate-detection and similarity-ranked search (for more details, see my last blog post on SAP MDG. 7.0). You can also make use of HANA being an in-memory, column-based database, and benefit from this in a multi-attribute drill-down selection that allows you to filter and analyze the intrinsic structures in your master data. In the Feature Pack, we provide additional HANA-enabled values allowing for easy access, insight, and follow-up actions for the business. Since SAP HANA allows for fast access to aggregated data across multiple data sources, we enable fast calculation of key performance indicators, for example, to analyze the quality of SAP MDG’s governance process execution. This can be done to present the information in a Smart Business dashboard for real-time insight, and then to allow for follow-up and issue resolution. The appropriate Smart Business content can be configured based on customer-defined HANA views. Examples of such key performance indicators include: the total number of change requests, the number of currently open change requests, change requests with the status final approval, long-running change requests that are still open, change requests with an exceeded processing time compared to an SLA, overdue change requests compared to due dates. Figure 2: Key performance indicators in SAP Smart Business showing process quality in SAP MDG Improved user experience: highlighting changes and the undo / redo feature The main purpose of the Feature Pack is to improve the user experience. Let’s look at one example in more detail: the highlighting of saved and unsaved changes. If you switch on this new feature for end-users, the system displays saved and unsaved changes in two different colors on the SAP MDG user interface. When you create a new object, the system highlights all unsaved changes in a certain color. If you change an existing object, the system also highlights unsaved changes, but in addition, it also highlights already saved changes in a second color. These are typically changes that were made by a different person earlier in the change request process, or changes you made yourself, but that have already been saved. “Changes” in this context refer to those values on the screen that would change a master data attribute compared to the last approved version of the master data – that is, compared to the “active” master data in SAP MDG terms. Of course, this feature also works in conjunction with SAP MDG’s editions. If you change an edition-based object, for comparison. the system uses the active value either from the validity period the change refers to, or from the previous validity period. In case the object did not exist before the validity period the change refers to, or if the object was deleted in the previous validity period, the system highlights unsaved changes, but does not highlight saved changes. The system also highlights table rows that refer to changes you can only see when navigating from a table row to the details of a dependent entity. It also allows you to distinguish new rows from changed rows in a table. When you move your mouse over a highlighted field, the tooltip of the field displays the previous value. If you change a value several times before saving it, the tooltip displays the active value and the last saved value. Figure 3: Highlighting saved and unsaved changes in two colors and displaying previous values in the tooltip Another example of improved user experience is the new undo / redo feature. When you are processing a change request, the SAP MDG system records all your actions. For this, it collects exactly those actions in one “undo” step that are made in the web applications between two client/server roundtrips. Each of these steps carried out since you last saved the object can be undone. You can undo steps until you save or cancel. After having used the undo feature, you can use “redo” to recover your actions. Figure 4: New undo / redo feature allows users to take back their proposed changes step by step Other usability improvements There are further usability improvements provided with SAP MDG 7.0 SP02. Let me just mention a few of them briefly. SAP MDG for Financial Data now allows users to efficiently create general ledger account data for multiple company codes by copying existing data from one company code to a new company code. It also allows creating a new general ledger account and the corresponding cost element in one maintenance step.. In SAP MDG for Customer or Supplier, it is now possible to change the account group within MDG’s single object maintenance user interface. With the Feature Pack, the standard delivery also provides dedicated role-specific user interface configurations for efficient processing by experts. These include a specialized user interface covering company code data for customers or suppliers, a specialized user interface covering sales area data for customers, and one for purchasing organization data for suppliers. Users navigate directly to the specialized user interface from their (workflow) inbox based on their role and based on the step in the change request process. This saves the users several clicks for navigating to the right screen within the full change request. Figure 5: Example of a specialized user interface covering sales area data for customers SAP MDG for Customer or Material have also been enhanced. For example, there is an improved printing and an an enhanced copy function for material master data, as well as enriched integration with SAP PLM via Change Number and Material Revision Level, and a display option for thumbnail pictures in the SAP MDG Side Panel. The database search using SAP HANA was improved for material master data. The SAP Document Management System integration was improved. And the standard content was further enhanced: additional attributes are supported, such as storage location and the views containing material data for the warehouse. In addition, several enhancements of previously delivered material master data views are provided in the data model and the corresponding user interfaces. As pointed out in one of my earlier blog posts, whenever we make additional investments in the MDG Application Foundation, the main focus is on extensibility, flexibility, usability, and ease of consumption. This means that we want to allow companies to create very flexible governance processes, with role-based user interfaces, but with very reasonable implementation efforts. One example of this in the Feature Pack is that we now provide customizing and configuration for all relevant SAP MDG user interfaces from one single place. A dedicated WebDynpro application is provided to manage all user interface configurations, for example, across single-object processing, multiple-record processing, and search. You can also copy a standard SAP user interface configuration to the customer namespace and configure it to your requirements. Summary and outlook You may have seen earlier documents about SAP MDG that describe how the focus of SAP MDG is on comprehensive master data ready for use in business processes by offering ready-to-run governance applications for specific master data domains. There, it is also stated that SAP MDG allows for customer-defined master data objects, processes, and user interfaces, and how it can distribute master data to SAP and non-SAP systems. SAP MDG is an important part of SAP’s Information Management portfolio that you might want to combine with additional tools like the SAP Information Steward for the monitoring of master data quality in all relevant systems and correction in SAP MDG, or like SAP Data Services for data quality services, validations and data enrichment. If you look at SAP MDG 7.0 in particular, and at the recent Feature Pack, you’ll see that these enhancements focus on three aspects: Firstly, SAP MDG now provides an even more flexible MDG Application Foundation that allows for refined control in the governance processes, leading to more flexibility and higher efficiency in the business. One example of this is the flexible Edition management for easier and more flexible scheduling of changes, a very intuitive access to the different states of master data that is valid in certain timeframes, higher transparency of past and planned changes, and a more granular control of replication timing. Another example is the parallel change requests combined with the concept of “interlocking”, which allows for many changes of the same master data object at the same time but without the risk of conflicting changes. Secondly, enhancements to SAP MDG enable better usability providing easy access and insight for business people and allowing direct follow-up on found issues. We have looked at SAP Fiori, Smart Business, and several other usability improvements in this post. In addition, there are also the improved user interfaces for single-object maintenance, the cleansing case that allows for a reduction of duplicates during search or creation, and the multi-record processing function that allows changing multiple master data objects simultaneously in one single user interface. Thirdly, as an option, SAP MDG can use SAP HANA for advanced duplicate-detection and search, or for multi-attribute drill-down selection. You can also use SAP HANA for efficient access to key performance indicators that are aggregated across multiple data sources to analyze the quality of governance process execution in your company. We have already started the development of the next SAP MDG release. Stay tuned to read about more exciting enhancements and new capabilities as soon as we are ready to announce them. You can find more information about SAP MDG on the SAP Master Data Governance page on SCN. Love the look of the KPIs, Markus. Very excited to see the MDG 7.0 on HANA, Duplicate check and DMS integration feature with the new release! thanks, Parvez Nice looking UI... Users will love it ! Hi Markus, Nicely written blog !!! Self illustrative. How ever from an usability standpoint I do have few queries with respect to MDG 7.0. Thanks, Guru Hi Guru, thanks for the feedback. The user interfaces in SAP MDG along the change request process are built using Floorplan Manager (FPM) for WebDynpro ABAP. They are not UI5, neither in 6.1 nor 7.0. In addition to those user interfaces, we created dedicated SAP Fiori apps for master data request scenarios for selected master data domains. These additional apps are UI5, same as all SAP Fiori apps. The Fiori apps will trigger an SAP MDG change request in the exact same way as if you would create it using the FPM-based user interface. You may of course use a different change request type for those triggered through a Fiori app if you like. In order to enable the new Fiori apps, we created dedicated new OData services for SAP Gateway in SAP MDG 7.0 SP02 (Feature Pack). You will find all the technical names of the UI5 Applications and OData Services in the SAP MDG documentation in the section => MDG 7.0 => SAP Fiori Apps for SAP Master Data Governance. Examples are MDG_CUSTOMER_SRV (OData Service) and MDG_REQ_CUST (UI5 Application) for the Fiori customer master data request. Other than these, I am not aware of any MDG-specific changes to OData configuration. The underlying SAP AS ABAP version, and therewith the SAP Gateway version, might of course be different in your SAP MDG 6.1 vs. SAP MDG 7.0 implementation (e.g. if you implemented it either on SAP ERP 6.0 EhP6 or EhP7). Best regards, Markus Hi Markus, Very interesting blog , with a host of useful enhancements for MDG in this version. I have a couple of questions though. 1. For the HANA view of the master data governance process KPIs - do we need Enterprise HANA for creating these views? Is this Smart dashboard available even if we do not have HANA db? 2. For certain master data objects like Equipment/location etc, could you possibly share if and when SAP is planning to include them in the standard content (or through certified product extensions)? Thanks and regards Asidhara Lahiri. Hello Asidhara Lahiri, I copy the answer for the first question from the mail we exchanged - HANA is required for the SAP Smart Business KPI dashboard. HANA is a prerequisite to create the views. This can be done with a side-by-side approach with SLT replication or with integrated stack. Find here the link to the RKT session on the feature pack: On your second question: we are currently planning on the mentioned EAM/PM objects for co-innovation together with a dedicated partner. Because the process is ongoing I cannot reveal details and dates, but the plan is to deliver a certified product extension that includes those two objects already in this year. Best regards, Ingo Hi Markus, Thanks for the blog. I have a question regarding Vendor Like UI in 7.0. Is the functionality for creating/adding Contact Persons available on this UI in 7.0? Thanks & Regards, Kiran Hi Kiran, the feature to create / add a Contact Person also in the Vendor Like UI is not yet available in SAP MDG 7.0 (SP02), but we plan to provide this in a future Support Package or release of SAP MDG. Best Regards, Birgit Hi Markus, thanks for the blog,I have few question 1.Search cleansing case is provided in BP governance,customer and suplier governance not in Vendor UI and Supplier UI's,any reason for that. 2.Any docs for cleansing cases. regards shankar Hi Shankar, Please refer the below link for details of cleanse and merge functionality Cleansing Cases - SAP Master Data Governance - SAP Library Thanks & Regards, Ibrahim. Hi Shankar, I am not totally sure what you are referring to. The way to access "Search Cleansing Case" is via the role menu - in standard for example via > Business Partner Governance > Change Requests > Business Partner Processing > Search Cleansing Case, or also identically via > Customer Governance > Change Requests > Customer Processing > Search Cleansing Case. This menu structure is not related to the user interface configuration, like for a "BP-like" UI or a "vendor-like" UI. Best regards, Markus Dear Markus, thanks for your quick reply,if we want to use the Vendor Like UI then with cleansing features,will this be possible. regards shankar Again Shankar, cleansing cases are not related to a specific UI configuration in the change request processing. Cleansing cases can be created from search result lists or based on duplicate detection results. I would recommend to re-read my blog on SAP MDG 7.0 (see the link at the very top) which touches the topic very briefly and to carefully read the documentation that Ibrahim linked above. Best regards, Markus Dear Markus, Sure thanks for the Update.. Hi Markus, Does cleansing /merge functionality requires HANA underneath? I guess so. Thanks Pravin Hi Pravin, The merge of a few duplicates via the cleansing case does not require SAP MDG 7.0 to run on top of SAP HANA. Best regards, Markus Hi Markus, Very informative and at a glance. Thank you. Had a quick question on BCV side panels. In MDG 7.0 innovations blog you mentioned that BCV CHIPs fetch open PO, Open SO info dynamically, how does that happen in real time info if we are using MDG Hub which is on a different box? Are there any other dependencies ? Regards Pravin Hi Pravin, The deployment as a hub or co-deployed with an operational SAP ERP system does not create dependencies here. The BCV side panel user interface will be executed on the SAP MDG hub system. The content can be fetched at run-time from remote systems, though. You could for example display sales orders from a remote operational SAP ERP system related to the customer you are currently changing in the SAP MDG hub. Best regards, Markus Thank you Markus. Appreciate your response. Regards Pravin Hi Markus, Very useful information Quick question regarding the new enhancements: 1. In SAP MDG 7.0, the mass data import has also been improved, in particular for loading data into MDG’s “flexible mode” models, like for financial master data and custom objects. Q: Is this similar to DIF? If so what exactly has changed which makes SAP say that functionality has improved? 2. The integration scenarios have been enriched, for example for exchanging customer master data with SAP CRM, or for distributing SAP Configuration data that is managed in custom-built MDG objects and processes. Q:Is this Configuration data regarding reference data such as countries or more complex ones such as plants, company codes which are managed in T005 table? Hi Sridhar, 1 ... A: Actually it is using DIF - which was not available with out of the box content for financial master data and now is also easier to implement for custom objects. 2 ... A: It can also be used for more complex objects - but depending on the object and the scope of the attributes that should be maintained centrally the implementation might have to include additional steps. Like the handling of an address attached to the object. Hope this helps ... regards, Michael UI looks Very Good and SAP Fiori Apps is very useful for Master data requests. Hi Markus, Regarding to highlighted fields, do you know if is it achievable to highlight fields when there is an error? since you can not navigate from the error log straight to the error, is there any way to highlight the error so the user does not spend a lot of time searching for the field? Thank you, Javi Hi Javier, highlighting is only intended to visualize the "delta". From the error log we do have navigation capabilities, but not for all kind of errors / all fields. The errors we capture in the MDG framework on field level are hyperlinked and you can navigate directly there by clicking on the message in the error log. If errors come from calling backend logic we normally do not have the reason on field level. BR Ingo Hi Ingo, thank you for your replay. but how does the hyper-link know that it has to navigate to the error field? if i am raising an error in the badi for validation ( either custom field or standard field ) how do i link the error to the field itself? thank you, Javi Hi Javier, do you have an example for us - depending on the domain, if it is possible to do a 1:1 mapping to the backend and also which badi you are using the solution might look slightly different. We do not have a one fits all API for this ... BR, Ingo Hi Markus Thanks for blog Can you throw some more highlight on Here need one clarification can it possible to assign internal numbers for financial objects at the requestor step and later on Master data steward can update with correct number . Now it seems that finacial objects are required fields for respective UI like GL account,Cost Center,Profit Center,Cost Element. Also Can it possible to add duplicate check for description fields for Finance Domain as well? Hi Sanjay, neither internal numbering nor the duplicate check are supported by MDG-F 7.0. Best regards Michael Hello Markus, In a discussion today, I was told that SAP MDG 7.02 supports Create using template option for Customer data model. This was available for MDG F, but I have not seen this for customer, is there any note or patch that needs to be applied to use this functionality. Your inputs on this please. Thanks and Regards, Shahid Noolvi Hi Shahid Noolvi, your information is almost accurate. We introduced (what we call) a "copy" option for Business Partner, Customer & Vendor with the latest MDG 8.0 (which is currently in RampUp). You can trigger a copy to a new e.g. Customer from the search results list. Within a record we also added the feature to copy organizational data to one or many new company codes / sales organizations / purchase organizations. Which fields are copied can be controlled using so-called "copy-profiles". The good news for you: Functionality is also included in MDG 7.0 SP03 and with some additional effort you can also downport to MDG 7.0 SP02. Please have a look at note 2020896 (). Best Regards Ingo Thanks Ingo. I was looking for this information. Thanks again.
https://blogs.sap.com/2014/05/20/innovations-in-sap-master-data-governance-70-sp02-feature-pack/
CC-MAIN-2021-49
refinedweb
3,841
52.8
H. The first row shows the distance, and the second row shows the speed if the object is moving. There is also an LED that signals the distance at which the object is placed. If the distance is less than 5 cm, the LED lights up continuously. As the distance increases the LED starts flashing at a speed that depends on the distance of the object. If the object moves away, the blinking is slower, and vice versa. When the object is moving in the opposite direction, the speed represented on the display has a negative sign. #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2);// RS,E,D4,D5,D6,D7 // defines pins numbers const int trigPin = 9; const int echoPin = 10; // defines variables long duration; int distance1=0; int distance2=0; double Speed=0; int distance=0; void setup() { lcd.begin(16, 2);// LCD 16X2 pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input pinMode( 7 , OUTPUT); Serial.begin(9600); // Starts the serial communication } void loop() { //calculating Speed distance1 = ultrasonicRead(); //calls ultrasoninicRead() function below delay(1000);//giving a time gap of 1 sec distance2 = ultrasonicRead(); //calls ultrasoninicRead() function below //formula change in distance divided by change in time Speed = (distance2 - distance1)/1.0; //as the time gap is 1 sec we divide it by 1. //Displaying Speed Serial.print("Speed in cm/s :"); Serial.println(Speed); lcd.setCursor(0,1); lcd.print("Speed cm/s "); lcd.print(Speed); // LED indicator if (distance >0 && distance <5) { digitalWrite( 7 , HIGH); delay(50); // waits for a second } if (distance > 5 && distance <10 ) { digitalWrite( 7 , HIGH); delay(50); // waits for a second digitalWrite( 7 , LOW); // sets the LED off delay(50); // waits for a second } if (distance >10 && distance < 20) { digitalWrite( 7 , HIGH); delay(210); // waits for a second digitalWrite( 7 , LOW); // sets the LED off delay(210); // waits for a second } if (distance >20 && distance < 35) { digitalWrite( 7 , HIGH); delay(610); // waits for a second digitalWrite( 7 , LOW); // sets the LED off delay(610); // waits for a second } } float ultrasonicRead () { // distance distance= duration*0.034/2; // Prints the distance on the Serial Monitor Serial.print("Distance in cm : "); Serial.println(distance); lcd.setCursor(0,0); lcd.print("Dist. in cm "); lcd.print(distance); lcd.print(" "); return distance; }
https://maker.pro/anduino/projects/speed-measurement-using-hc-sr04-ultrasonic-sensor
CC-MAIN-2021-39
refinedweb
387
52.8
webtest-sanic provides integration of WebTest with sanic applications Project description webtest-sanic Integration of WebTest with Sanic applications Initially it was created to enable Sanic support in Webargs module Example Code import asyncio from sanic import Sanic from sanic.response import json from webtest_sanic import TestApp app = Sanic() @app.route('/') async def test(request): return json({'hello': 'world'}) loop = asyncio.new_event_loop() def test_hello(): client = TestApp(app, loop=loop) res = client.get('/') assert res.status_code == 200 assert res.json == {'message': 'Hello world'} Installing It is easy to do from pip pip install webtest-sanic or from sources git clone git@github.com:EndurantDevs/webtest-sanic.git cd webtest-sanic python setup.py install Running the tests To be sure everything is fine before installation from sources, just run: python setup.py test Or pytest tests/ Credits This code is based on webtest-aiohttp by Steven Loria and pytest-sanic by Yun Xu Please check NOTICE for more info. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/webtest-sanic/
CC-MAIN-2018-39
refinedweb
181
58.28
Super Charge Python with Pandas on GPUs Using Saturn Cloud. By Tyler Folkman, Head of Artificial Intelligence at BEN Group Photo by Guillaume Jaillet on Unsplash I once asked on LinkedIn what libraries people are most likely to import when first opening up a Jupyter Notebook. Do you know what the number one response was? Pandas The Pandas library is used extensively by data scientists, but the truth is it can often be quite slow. And if your data processing is slow it can really lead to a lot of delays in a project. If every time you want to generate a new feature for your model takes even 10 minutes, you find yourself sitting around just waiting (or doing other things :) ). Source: The time it takes for data to process and models to train is similar to the compiling time for programmers. And while you might enjoy some of your data processing breaks due to long processing times, I want to show you a better way. I want to show you how you can easily avoid being over 1,000,000% slower when using Pandas. The Setup Before we dig into the experiments, let’s talk about the hardware we will be using. To make this incredibly easy for you to follow along with, we will be using Saturn Cloud. Source: Saturn Cloud Saturn Cloud is a really slick platform that gives you access to: - 10 hours of free Jupyter per month (including GPU) - 3 hours of Dask per month (including GPU) - Deploy dashboards You can use it for free here. Making it a great place to experiment with large-scale data processing! When you start up a project on Saturn, you get access to two very important pieces of hardware. A Jupyter Server and a Dask Cluster. Source: Saturn Cloud Our Jupyter Server is running with 4 cores, 16 GB of RAM, and a single GPU. The Dask cluster is 3 workers with 4 cores, 16GB of RAM, and a single GPU. The other amazing thing you get when selecting the RAPIDS base project is a Python kernel with all of NVIDIA’s RAPIDs libraries including CUDF, which allows us to run our Pandas processing on a GPU. Getting this setup with a few clicks is no small win. Even if you have a computer with a GPU, getting the RAPIDs libraries working can be time-consuming because you have to make sure you have the right drivers and CUDA library. The Data Alright — now that we have our hardware setup, we need to talk about the dataset we will be using. We will use the Yellow Taxi trip record data. These data have 7,667,792 rows and 18 columns. Here is what you get when running info() on the data frame: <class 'pandas.core.frame.DataFrame'> RangeIndex: 7667792 entries, 0 to 7667791 Data columns (total 18 columns): # Column Dtype --- ------ ----- 0 VendorID int64 1 tpep_pickup_datetime datetime64[ns] 2 tpep_dropoff_datetime datetime64[ns] 3 passenger_count int64 4 trip_distance float64 5 RatecodeID int64 6 store_and_fwd_flag object 7 PULocationID int64 8 DOLocationID int64 9 payment_type int64 10 fare_amount float64 11 extra float64 12 mta_tax float64 13 tip_amount float64 14 tolls_amount float64 15 improvement_surcharge float64 16 total_amount float64 17 congestion_surcharge float64 dtypes: datetime64[ns](2), float64(9), int64(6), object(1) memory usage: 1.0+ GB So, a decently sized dataset, but nothing too crazy. It comes in at about 1GB of memory usage. The Function Lastly, for our experiments, we need a function to run on our data. I selected a pretty simple function that creates a new feature for a potential model. Our function will calculate the total amount paid divided by the trip distance. def calculate_total_per_mile(row): try: total_per_mile = row.total_amount / row.trip_distance except ZeroDivisionError: total_per_mile = 0 return total_per_mile When we find a zero value for trip_distance, we will just return a value of zero. Note: You can easily vectorize this function as taxi_df[“total_per_mile”] = taxi_df.total_amount / taxi_df.trip_distance, which would be significantly faster. We are using a function instead so we can compare apply speeds for our experiments. If you’re curious, the vectorized version took about 50 ms. Experiment #1 — Raw Pandas For our first experiment, we are just going the read the data using raw Pandas. Here is the code: taxi_df = pd.read_csv( “s3://nyc-tlc/trip data/yellow_tripdata_2019–01.csv”, parse_dates=[“tpep_pickup_datetime”, “tpep_dropoff_datetime”] ) With the data read in, we can apply our function to all our rows: taxi_df[‘total_per_mile’] = taxi_df.apply(lambda x: calculate_total_per_mile(x), axis=1) It took 159,198 ms (2 minutes and 39.21 seconds) to run this calculation. While that isn’t terribly slow, it is definitely slow enough that you notice the time it takes and it throws off your flow. I found myself sitting around waiting and that waiting time could easily tempt you to get distracted by email, Slack, or social media. And those types of distractions can really kill productivity beyond the time almost 3 minutes this calculation took to run. Can we do better? Experiment #2 — Parallel Pandas Swifter is a library that makes it incredibly simple to use all the threads of your CPU when running Pandas apply. Since apply is easily parallelized because you can just break the data frame into chunks for each thread, this should help. Here is the code: taxi_df[‘total_per_mile’] = taxi_df.swifter.apply(lambda x: calculate_total_per_mile(x), axis=1) Adding swifter to the mix brought our processing time to 88,690 ms (1 minute and 28.69 seconds). Raw pandas was 1.795 times slower and you definitely notice when running the code that it got faster. That being said, you still find yourself waiting for it to finish. Experiment #3 — Pandas on a GPU This is where things start to get interesting. Thanks to the cuDF library will allow us to run our function on the GPU. The cuDF library, “provides a pandas-like API that will be familiar to data engineers & data scientists, so they can use it to easily accelerate their workflows without going into the details of CUDA programming.” To use the cuDF library, though, we have to change the format of our function slightly: def calculate_total_per_mile(total_amount, trip_distance, out): for i, (ta, td) in enumerate(zip(total_amount, trip_distance)): total_per_mile = ta / td out[i] = total_per_mile Now our function takes in the total_amount, trip_distance, and out. Out is the array in which we will store the results. Our function then loops over all the values of total_amount and trip_distance from our data frame, calculates our total_per_mile, and stores the results in out. We also have to change how we apply this function to our data frame: taxi = taxi.apply_rows(calculate_total_per_mile, incols={‘total_amount’:’total_amount’, ‘trip_distance’:’trip_distance’}, outcols={‘out’: np.float64}, kwargs={} ) We now specify what the input columns are from our data frame and how they map to the function parameters. We also specify which parameter is the output (outcols) and what type of value it is (np.float64). Note: reading in the data remains the same except you use cudf.read_csv() instead of pd.read_csv(). Using the cuDF library and leveraging our GPU takes the processing time down to 43 ms! That means raw pandas was 3,702 times slower! That is insane! At this point, the processing time doesn’t feel like a delay at all. You run the function and before you know it, you have results. Honestly, I was amazed by how much faster it was to run our processing on the GPU. But! We have 1 more experiment to run to see if we can make it even faster. Experiment #4— Pandas on a Multiple GPUs Dask_cuDF is a library that we can use in order to leverage our dask cluster which has 3 workers, each with a GPU. Essentially, we will be running our function on 3 GPUs distributed across our dask cluster. This might sound complicated, but Saturn makes it really easy. With the following code, you can connect to your dask cluster: from dask.distributed import Client, wait from dask_saturn import SaturnClustern_workers = 3 cluster = SaturnCluster(n_workers=n_workers) client = Client(cluster) client.wait_for_workers(n_workers) Once connected, you read in the data as so: import dask_cudftaxi_dc = dask_cudf.read_csv( “s3://nyc-tlc/trip data/yellow_tripdata_2019–01.csv”, parse_dates=[“tpep_pickup_datetime”, “tpep_dropoff_datetime”], storage_options={“anon”: True}, assume_missing=True, ) And finally, you can run the function in the exact same way you did with cuDF. The only difference is that we are now running on a data frame read-in with the dask_cudf library, so we will be leveraging our dask cluster. How long did it take? 12 ms That is 13,267 times faster than raw Pandas or you could also say that Pandas is 1,326,650% slower than running on a cluster of 3 GPUs. Wow. That is fast. You could get a much larger dataset and still run this function fast enough to not notice much of a delay at all. Note: This is still over 4 times faster than the Pandas vectorized version of our function! Speed Matters Hopefully, I’ve convinced you to drop everything right now and go try out Pandas on a GPU using Saturn Cloud. You could argue that almost 3 minutes to wait for a function to run really isn’t that long, but when you’re focused on programming and in the flow, 3 minutes really feels like forever. It is enough time that you start to get distracted and could easily end up wasting even more time via distraction. And if you have even larger data, those wait times will only get longer. So, go try it out for yourself. I think you will be amazed by how much better 12 ms or even 43 ms feels when running on a GPU as compared to over 159,000 seconds. Also, thank you to Saturn Cloud for working with me on this article! It was my first deep dive into the platform and I was truly impressed. Bio: Tyler Folkman is the Head of Artificial Intelligence at BEN Group. His work explores applications of machine learning in disrupting and transforming the entertainment and marketing industries. Tyler's work has earned multiple patents in the areas of entity resolution and knowledge extraction from unstructured data. Related: - Applying Python’s Explode Function to Pandas DataFrames - How to Speed Up Pandas with Modin - ETL in the Cloud: Transforming Big Data Analytics with Data Warehouse Automation
https://www.kdnuggets.com/2021/05/super-charge-python-pandas-gpus-saturn-cloud.html
CC-MAIN-2021-39
refinedweb
1,736
62.88
XXE vulnerability during rasterization of SVG images Bug Description Inkscape is vulnerable to XXE attacks during rasterization/ Impact: The impact of this vulnerability range form denial of service to file disclosure. Under Windows, it can also be used to steal LM/NTLM hashes. PoC: During rasterization, entities declared in the DTD are dereferenced and the content of the target file is included in the output. Command-line used: "inkscape -e xxe-inkscape.png xxe.svg" Attached files: - xxe.svg: malicious SVG file to convert - xxe-inkscape.png: result of the rasterization of xxe.svg References: CWE-827: Improper Control of Document Type Definition http:// Regards, Nicolas Grégoire Related branches Yes. In libxml2 (which is the XML parser used by Inkscape), the xmlParserOption should used : http:// possible fix: src/xml/repr-io.cpp line 297: This disables reading of a file on Windows (quick test), but it still allows <!ENTITY stroke_color "#666666"> so that's nice. Also, read: https:/ note that FileImportFromO here a file that tries to construct an URL from a local file. (so it could potentially send the contents of that file to a webserver, similar to "http:// it also shows nice usage with color substitution, that still works when calling xmlReadIO with options /*XML_PARSE_NOENT |*/ XML_PARSE_NONET | XML_PARSE_HUGE (so *without* the XML_PARSE_NOENT option right now, I feel we should disable this functionality per default, and perhaps provide an option/preference to enable local file access and web access. @johanengelen: "here a file that tries to construct an URL from a local file" This behavior is forbidden by the XML spec. You can't use an entity inside the URL of an external entity. ok perfect, good to know. regardless of the validity of the thread: i am not so happy with inkscape accessing internet because an SVG requests it. I think that should be optional, possibly on a per file or per access basis. If anyone knows, please comment on what is wrong with the fix proposed in #6 The best way to configure the parser (but this would need some functional testing) would imho be: - without XML_PARSE_NOENT ("Substitute entities") - without XML_PARSE_XINCLUDE ("Implement XInclude substitution") - without XML_PARSE_DTDLOAD ("load the external subset") - with XML_PARSE_NONET ("Forbid network access") For your information, here's the patch that XML::Atom applied regarding CVE-2012-1102: http:// fixed in r11931. removed the _NOENT option, and made network access optional through preferences.xml (/options/ backported to 0.48.x, r9932 Please note CVE-2012-1102 has already been assigned to a similar XXE issue in Perl-Atom, as per: http:// This flaw needs to be a assigned a different CVE. Details at: http:// Adding patch for backporting to Linux distros Follow-up report: - Bug #1093433 “XML Entities used for namespace declarations prevent file loading in trunk and 0.48.4” <https:/ would simply disabling the DTD dereferencing be good enough of a fix?
https://bugs.launchpad.net/inkscape/+bug/1025185
CC-MAIN-2015-11
refinedweb
478
52.49
(For more resources related to this topic, see here.) Writing out a custom FTP scanner module Let's try and build a simple module. We will write a simple FTP fingerprinting module and see how things work. Let's examine the code for the FTP module: require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::Ftp include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'Apex FTP Detector', 'Description' => '1.0', 'Author' => 'Nipun Jaswal', 'License' => MSF_LICENSE ) register_options( [ Opt::RPORT(21), ], self.class) End We start our code by defining the required libraries to refer to. We define the statement require 'msf/core' to include the path to the core libraries at the very first step. Then, we define what kind of module we are creating; in this case, we are writing an auxiliary module exactly the way we did for the previous module. Next, we define the library files we need to include from the core library set. Here, the include Msf::Exploit::Remote::Ftp statement refers to the /lib/msf/core/exploit/ file and include Msf::Auxiliary::Scanner refers to the /lib/msf/core/auxiliary/scanner.rb file. We have already discussed the scanner.rb file in detail in the previous example. However, the file contains all the necessary methods related to FTP, such as methods for setting up a connection, logging in to the FTP service, sending an FTP command, and so on. Next, we define the information of the module we are writing and attributes such as name, description, author name, and license in the initialize method. We also define what options are required for the module to work. For example, here we assign RPORT to port 21 by default. Let's continue with the remaining part of the module: def run_host(target_host) connect(true, false) if(banner) print_status("#{rhost} is running #{banner}") end disconnect end end We define the run_host method, which will initiate the process of connecting to the target by overriding the run_host method from the /lib/msf/core/auxiliary/scanner.rb file. Similarly, we use the connect function from the /lib/msf/core/exploit/ file, which is responsible for initializing a connection to the host. We supply two parameters into the connect function, which are true and false. The true parameter defines the use of global parameters, whereas false turns off the verbose capabilities of the module. The beauty of the connect function lies in its operation of connecting to the target and recording the banner of the FTP service in the parameter named banner automatically, as shown in the following screenshot: Now we know that the result is stored in the banner attribute. Therefore, we simply print out the banner at the end and we disconnect the connection to the target. This was an easy module, and I recommend that you should try building simple scanners and other modules like these. Nevertheless, before we run this module, let's check whether the module we just built is correct with regards to its syntax or not. We can do this by passing the module from an in-built Metasploit tool named msftidy as shown in the following screenshot: We will get a warning message indicating that there are a few extra spaces at the end of line number 19. Therefore, when we remove the extra spaces and rerun msftidy, we will see that no error is generated. This marks the syntax of the module to be correct. Now, let's run this module and see what we gather: We can see that the module ran successfully, and it has the banner of the service running on port 21, which is Baby FTP Server. For further reading on the acceptance of modules in the Metasploit project, refer to. Writing out a custom HTTP server scanner Now, let's take a step further into development and fabricate something a bit trickier. We will create a simple fingerprinter for HTTP services, but with a slightly more complex approach. We will name this file http_myscan.rb as shown in the following code snippet: require 'rex/proto/http' require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::HttpClient include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'Server Service Detector', 'Description' => 'Detects Service On Web Server, Uses GET to Pull Out Information', 'Author' => 'Nipun_Jaswal', 'License' => MSF_LICENSE ) end We include all the necessary library files as we did for the previous modules. We also assign general information about the module in the initialize method, as shown in the following code snippet: def os_fingerprint(response) if not response.headers.has_key?('Server') return "Unknown OS (No Server Header)" end case response.headers['Server'] when /Win32/, /\(Windows/, /IIS/ os = "Windows" when /Apache\// os = "*Nix" else os = "Unknown Server Header Reporting: "+response.headers['Server'] end return os end def pb_fingerprint(response) if not response.headers.has_key?('X-Powered-By') resp = "No-Response" else resp = response.headers['X-Powered-By'] end return resp end def run_host(ip) connect res = send_request_raw({'uri' => '/', 'method' => 'GET' }) return if not res os_info=os_fingerprint(res) pb=pb_fingerprint(res) fp = http_fingerprint(res) print_status("#{ip}:#{rport} is running #{fp} version And Is Powered By: #{pb} Running On #{os_info}") end end The preceding module is similar to the one we discussed in the very first example. We have the run_host method here with ip as a parameter, which will open a connection to the host. Next, we have send_request_raw, which will fetch the response from the website or web server at / with a GET request. The result fetched will be stored into the variable named res. We pass the value of the response in res to the os_fingerprint method. This method will check whether the response has the Server key in the header of the response; if the Server key is not present, we will be presented with a message saying Unknown OS. However, if the response header has the Server key, we match it with a variety of values using regex expressions. If a match is made, the corresponding value of os is sent back to the calling definition, which is the os_info parameter. Now, we will check which technology is running on the server. We will create a similar function, pb_fingerprint, but will look for the X-Powered-By key rather than Server. Similarly, we will check whether this key is present in the response code or not. If the key is not present, the method will return No-Response; if it is present, the value of X-Powered-By is returned to the calling method and gets stored in a variable, pb. Next, we use the http_fingerprint method that we used in the previous examples as well and store its result in a variable, fp. We simply print out the values returned from os_fingerprint, pb_fingerprint, and http_fingerprint using their corresponding variables. Let's see what output we'll get after running this module: Msf auxiliary(http_myscan) > run [*]192.168.75.130:80 is running Microsoft-IIS/ 7.5 version And Is Powered By: ASP.NET Running On Windows [*] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed Writing out post-exploitation modules Now, as we have seen the basics of module building, we can take a step further and try to build a post-exploitation module. A point to remember here is that we can only run a post-exploitation module after a target compromises successfully. So, let's begin with a simple drive disabler module which will disable C: at the target system: require 'msf/core' require 'rex' require 'msf/core/post/windows/registry' class Metasploit3 < Msf::Post include Msf::Post::Windows::Registry def initialize super( 'Name' => 'Drive Disabler Module', 'Description' => 'C Drive Disabler Module', 'License' => MSF_LICENSE, 'Author' => 'Nipun Jaswal' ) End We started in the same way as we did in the previous modules. We have added the path to all the required libraries we need in this post-exploitation module. However, we have added include Msf::Post::Windows::Registry on the 5th line of the preceding code, which refers to the /core/post/windows/registry.rb file. This will give us the power to use registry manipulation functions with ease using Ruby mixins. Next, we define the type of module and the intended version of Metasploit. In this case, it is Post for post-exploitation and Metasploit3 is the intended version. We include the same file again because this is a single file and not a separate directory. Next, we define necessary information about the module in the initialize method just as we did for the previous modules. Let's see the remaining part of the module: def run key1="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion \\Policies\\Explorer\\" print_line("Disabling C Drive") meterpreter_registry_setvaldata (key1,'NoDrives','4','REG_DWORD') print_line("Setting No Drives For C") meterpreter_registry_setvaldata (key1,'NoViewOnDrives','4','REG_DWORD') print_line("Removing View On The Drive") print_line("Disabled C Drive") end end #class We created a variable called key1, and we stored the path of the registry where we need to create values to disable the drives in it. As we are in a meterpreter shell after the exploitation has taken place, we will use the meterpreter_registry_setval function from the /core/post/windows/registry.rb file to create a registry value at the path defined by key1. This operation will create a new registry key named NoDrives of the REG_DWORD type at the path defined by key1. However, you might be wondering why we have supplied 4 as the bitmask. To calculate the bitmask for a particular drive, we have a little formula, 2^([drive character serial number]-1) . Suppose, we need to disable the C drive. We know that character C is the third character in alphabets. Therefore, we can calculate the exact bitmask value for disabling the C drive as follows: 2^ (3-1) = 2^2= 4 Therefore, the bitmask is 4 for disabling C:. We also created another key, NoViewOnDrives, to disable the view of these drives with the exact same parameters. Now, when we run this module, it gives the following output: So, let's see whether we have successfully disabled C: or not: Bingo! No C:. We successfully disabled C: from the user's view. Therefore, we can create as many post-exploitation modules as we want according to our need. I recommend you put some extra time toward the libraries of Metasploit. Make sure you have user-level access rather than SYSTEM for the preceding script to work, as SYSTEM privileges will not create the registry under HKCU. In addition to this, we have used HKCU instead of writing HKEY_CURRENT_USER, because of the inbuilt normalization that will automatically create the full form of the key. I recommend you check the registry.rb file to see the various available methods. Breakthrough meterpreter scripting The meterpreter shell is the deadliest thing that a victim can hear if an attacker compromises their system. Meterpreter gives the attacker a much wider approach to perform a variety of tasks on the compromised system. In addition to this, meterpreter has many built-in scripts, which makes it easier for an attacker to attack the system. These scripts perform simple and tedious tasks on the compromised system. In this section, we will look at those scripts, what they are made of, and how we can leverage a script in meterpreter. The basic meterpreter commands cheat sheet is available at. Essentials of meterpreter scripting As far as we have seen, we have used meterpreter in situations where we needed to perform some additional tasks on the system. However, now we will look at some of the advanced situations that may arise during a penetration test, where the scripts already present in meterpreter seem to be of no help to us. Most likely, in this kind of situation, we may want to add our custom functionalities to meterpreter and perform the required tasks. However, before we proceed to add custom scripts in meterpreter, let's perform some of the advanced features of meterpreter first and understand its power. Pivoting the target network Pivoting refers to accessing the restricted system from the attacker's system through the compromised system. Consider a scenario where the restricted web server is only available to Alice's system. In this case, we will need to compromise Alice's system first and then use it to connect to the restricted web server. This means that we will pivot all our requests through Alice's system to make a connection to the restricted web server. The following diagram will make things clear: Considering the preceding diagram, we have three systems. We have Mallory (Attacker), Alice's System, and the restricted Charlie's Web Server. The restricted web server contains a directory named restrict, but it is only accessible to Alice's system, which has the IP address 192.168.75.130. However, when the attacker tries to make a connection to the restricted web server, the following error generates: We know that Alice, being an authoritative person, will have access to the web server. Therefore, we need to have some mechanism that can pass our request to access the web server through Alice's system. This required mechanism is pivoting. Therefore, the first step is to break into Alice's system and gain the meterpreter shell access to the system. Next, we need to add a route to the web server. This will allow our requests to reach the restricted web server through Alice's system. Let's see how we can do that: Running the autoroute script with the parameter as the IP address of the restricted server using the –s switch will add a route to Charlie's restricted server from Alice's compromised system. However, we can do this manually as well. Refer to for more information on manually adding a route to Windows operating systems. Next, we need to set up a proxy server that will pass our requests through the meterpreter session to the web server. Being Mallory, we need to launch an auxiliary module for passing requests via a meterpreter to the target using auxiliary/server/socks4a. Let's see how we can do that: In order to launch the socks server, we set SRVHOST to 127.0.0.1 and SRVPORT to 1080 and run the module. Next, we need to reconfigure the settings in the etc/proxychains.conf file by adding the auxiliary server's address to it, that is, 127.0.0.1 on port 1080, as shown in the following screenshot: We are now all set to use the proxy in any tool, for example, Firefox, Chrome, and so on. Let's configure the proxy settings in the browser as follows: Let's open the restricted directory of the target web server again: Success! We have accessed the restricted area with ease. We have an IP logger script running at the target web server in the directory named restrict. Let's see what it returns: Success again! We are browsing the web server with the IP of our compromised system, which is Alice's system. Whatever we browse goes through the compromised system and the target web server thinks that it is Alice who is accessing the system. However, our actual IP address is 192.168.75.10. Let's revise what we did because it may have been a bit confusing: We started by compromising Alice's system We added a route to Charlie's restricted web server from Alice's system through a meterpreter installed in Alice's system We set up a socks proxy server to automatically forward all the traffic through the meterpreter to Alice's system We reconfigured the proxy chains file with the address of our socks server We configured our browser to use a socks proxy with the address of our socks server Refer to for more information on using Nessus scans over a meterpreter shell through socks to perform internal scanning of the target's network. Setting up persistent access After gaining access to the target system, it is mandatory to retain that access forever. Meterpreter permits us to install backdoors on the target using two different approaches: MetSVC and Persistence. Let's see how MetSVC works. The MetSVC service is installed in the compromised system as a service. Moreover, it opens a port permanently for the attacker to connect whenever he or she wants. Installing MetSVC at the target is easy. Let's see how we can do this: We can clearly see that the MetSVC service creates a service at port 31337 and uploads the malicious files as well. Later, whenever access is required to this service, we need to use the metsvc_bind_tcp payload with an exploit handler script, which will allow us to connect to the service again as shown in the following screenshot: The effect of MetSVC remains even after a reboot of the target machine. This is handy when we need permanent access to the target system, as it also saves time that is needed for re-exploitation. API calls and mixins We just saw how we could perform advanced tasks with meterpreter. This indeed makes the life of a penetration tester easier. Now, let's dig deep into the working of meterpreter and uncover the basic building process of meterpreter's modules and scripts. This is because sometimes it might happen that meterpreter alone is not good enough to perform all the required tasks. In that case, we need to build our custom meterpreter modules and can perform or automate various tasks required at the time of exploitation. Let's first understand the basics of meterpreter scripting. The base for coding with meterpreter is the Application Programming Interface (API) calls and mixins. These are required to perform specific tasks using a specific Windows-based Dynamic Link Library (DLL) and some common tasks using a variety of built in Ruby-based modules. Mixins are Ruby-programming-based classes that contain methods from various other classes. Mixins are extremely helpful when we perform a variety of tasks at the target system. In addition to this, mixins are not exactly part of IRB, but they can be very helpful to write specific and advanced meterpreter scripts with ease. However, for more information on mixins, refer to. I recommend that you all have a look at the /lib/rex/post/meterpreter and /lib/msf/scripts/meterpreter directories to check out various libraries used by meterpreter. API calls are Windows-specific calls used to call out specific functions from a Windows DLL file. Fabricating custom meterpreter scripts Let's work out a simple example meterpreter script, which will check whether we are the admin user, whether we have system-level access, and whether the UAC is enabled or not: isadd= is_admin? if(isadd) print_line("Current User Is an Admin User") else print_line("Current User Is Not an Admin User") end issys= is_system? if(issys) print_line("Running With System Privileges") else print_line("Not a System Level Access") end isu = is_uac_enabled? if(isu) print_line("UAC Enabled") else print_line("UAC Not Enabled") end The script starts by calling the is_admin method from the /lib/msf/core/post/windows/priv.rb file and storing the Boolean result in a variable named isadd. Next, we simply check whether the value in the isadd variable is true or not. However, if it is true, it prints out a statement indicating that the current user is the admin. Next, we perform the same for the is_system and is_uac_enabled methods from the same file in our script. This is one of the simplest scripts. This script will perform basic functions as its function name suggests. However, a question that arises here is that /lib/msf/scripts/meterpreter contains only five files with no function defined in them, so from where did meterpreter execute these functions? However, we can see these five files as shown in the following screenshot: When we open these five files, we will find that these scripts have included all the necessary library files from a variety of sources within Metasploit. Therefore, we do not need to additionally include these functions' library files into it. After analyzing the /lib/msf/scripts/meterpreter.rb file, we find that it includes all these five files as seen in the preceding screenshot. These five files further include all the required files from various places in Metasploit. Let's save this code in the /scripts/meterpreter/myscript1.rb directory and launch this script from meterpreter. This will give you an output similar to the following screenshot: We can clearly see how easy it was to create meterpreter scripts and perform a variety of tasks and task automations as well. I recommend you examine all the included files within these five files discussed previously. Summary In this article, we learned how to write custom FTP scanner module, custom HTTP server scanner, and post-exploitation modules. We learned about meterpreter scripting, pivoting the target network, and setting up persistent access. We also learned about API calls and mixins and how to fabricate custom meterpreter scripts. Resources for Article: Further resources on this subject: - So, what is Metasploit? [Article] - Exploitation Basics [Article] - Understanding the True Security Posture of the Network Environment being Tested [Article]
https://www.packtpub.com/books/content/metasploit-custom-modules-and-meterpreter-scripting
CC-MAIN-2015-48
refinedweb
3,535
51.99
Make Teaching R Quasi-Quotation Easier Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. To make teaching R quasi-quotation easier it would be nice if R string-interpolation and quasi-quotation both used the same notation. They are related concepts. So some commonality of notation would actually be clarifying, and help teach the concepts. We will define both of the above terms, and demonstrate the relation between the two concepts. String-interpolation String-interpolation is the name for substituting value into a string. For example: library("wrapr") variable <- as.name("angle") sinterp( 'variable name is .(variable)' ) ## [1] "variable name is angle" Notice the " .(variable)" portion was replaced with the actual variable name " angle". For string interpolation we are intentionally using the " .()" notation that Thomas Lumley’s picked in 2003 when he introduced quasi-quotation into R (a different concept than string-interpolation, but the topic of our next section). String interpolation is a common need, and there are many R packages that supply variations of such functionality: base::sprintf R.utils::gstring() rprintf::rprintf() stringr::str_interp() glue::glue() wrapr::sinterp()(requires version 1.8.3, or newer). Quasi-quotation A related idea is "quasi-quotation" which substitutes a value into a general expression. For example: angle = 1:10 variable <- as.name("angle") evalb( plot(x = .(variable), y = sin(.(variable))) ) Notice how in the above plot the actual variable name " angle" was substituted into the graphics::plot() arguments, allowing this name to appear on the axis labels. evalb() is is a very simple function built on top of base::bquote(): print(evalb) ## function(..., where = parent.frame()) { ## force(where) ## exprq <- bquote(..., where = where) ## eval(exprq, ## envir = where, ## enclos = where) ## } ## <bytecode: 0x7fa0181b4470> ## <environment: namespace:wrapr> All evalb() does is: call bquote() as intended. A way to teach this is to just call bqoute() alone. bquote( plot(x = .(variable), y = sin(.(variable))) ) ## plot(x = angle, y = sin(angle)) And we see the un-executed code with the substitutions performed. There are many R quasi-quotation systems including: base::bquote() gtools::strmacro() lazyeval wrapr::let() rlang::as_quosure() nseval If you don’t want to wrap your plot() call in evalb() you can instead pre-adapt the function. Below we create a new function plotb() that is intended as shorthand for eval(bquote(plot(...))). plotb <- bquote_function(graphics::plot) plotb(x = .(variable), y = sin(.(variable))) Conclusion When string-inerpolation and quasi-quotation use the same notation we can teach them quickly as simple related.
https://www.r-bloggers.com/2019/01/make-teaching-r-quasi-quotation-easier/
CC-MAIN-2022-40
refinedweb
421
51.55
import numpy as np import numpy.random as nr import matplotlib.pyplot as pl %matplotlib inline # Size matters in plots. pl.rcParams['figure.figsize'] = (12.0, 10.0) # Plotting with style! import seaborn as sb The linear perceptron algorithm can be used to classify data points according to pre-selected features they have. The idea is to find a curve (or hyperplane) that separates points with different features. Once we have the curve, we can use it to decide if future points are of feature A or B based on where they are with respect to the curve (above or below it). Below, I generate a collection of points and then paint them according to a line. If the points are above the line, they are blue, if they are below, green. # Generate some points N = 100 xn = nr.rand(N,2) x = np.linspace(0,1); # Pick a line a = nr.rand(); b = nr.rand(); f = lambda x : a*x + b; fig =pl.figure() figa = pl.gca(); pl.plot(xn[:,0],xn[:,1],'bo'); pl.plot(x,f(x),'r') # Linearly separate the points by the line yn = np.zeros([N,1]); for i in xrange(N): if(f(xn[i,0])>xn[i,1]): # Point is below line yn[i] = 1; pl.plot(xn[i,0],xn[i,1],'go') else: # Point is above line yn[i] = -1; pl.legend(['Above','Separator','Below'],loc=0) pl.title('Selected points with their separating line.') figa.axes.get_xaxis().set_visible(False) figa.axes.get_yaxis().set_visible(False) The curve naturally separates the space into two regions, one of green points and one of blue points. Thus, if I am given a new point, I can assign it a color based on where it is with respect to the curve. It is really that simple. What is not so simple is to find the curve given the points. However, if the points are linearly separable, i.e. if a line exists that does the job, then I can just move a line around until I get it to the correct position. This is what the linear perceptron algorithm is doing. def perceptron(xn,yn,MaxIter=1000,w=np.zeros(3)): ''' A very simple implementation of the perceptron algorithm for two dimensional data. Given points (x,y) with x in R^{2} and y in {0,1}, the perceptron learning algorithm searches for the best line that separates the data points according to the difference classes defined in y. Input: xn : Data points, an Nx2 vector. yn : Classification of the previous data points, an Nx1 vector. MaxIter : Maximum number of iterations (optional). w : Initial vector of parameters (optional). Output: w : Parameters of the best line, y = ax+b, that linearly separates the data. Note: Convergence will be slower than expected, since this implementation picks points to update without a specific plan (randomly). This is enough for a demonstration, not so good for actual work. ''' N = xn.shape[0]; # Separating curve f = lambda x: np.sign(w[0]+w[1]*x[0]+w[2]*x[1]); for _ in xrange(MaxIter): i = nr.randint(N); if(yn[i] != f(xn[i,:])): # If not classified correctly, adjust the line to account for that point. w[0] = w[0] + yn[i]; w[1] = w[1] + yn[i]*xn[i,0]; w[2] = w[2] + yn[i]*xn[i,1]; return w; Now that I have a (working) implementation, here's a stab at our problem. Let's see how close it gets. w= perceptron(xn,yn) # Using weights w to compute a,b for a line y=a*x+b bnew = -w[0]/w[2]; anew = -w[1]/w[2]; y = lambda x: anew * x + bnew; # Computing the colors for the points sep_color = (yn+1)/2.0; pl.figure(); figa = pl.gca() pl.scatter(xn[:,0],xn[:,1],c=sep_color, s=30) pl.plot(x,y(x),'b--',label='Line from perceptron implementation.') pl.plot(x,f(x),'r',label='Original line.') pl.legend() pl.title('Comparison between the linear separator and the perceptron approximation.') figa.axes.get_xaxis().set_visible(False) figa.axes.get_yaxis().set_visible(False) Not bad, right? The algorithm should have managed to converge to a good approximation of the separating line. If it didn't, try running the last piece of code again. Remember that this implementation updates randomly picked points, so in some cases convergence will be worse. Also, note that the line that separates the points is not unique, given the dataset we have available. Would it be so if we had all of the possible information? My guess is that this depends on the data. In any case, it can be proven that this process works every time, given a sufficient number of steps. This assumes that the data is linearly separable, a fact that is quite powerful on its own. We may be good at finding patterns in $\mathbb{R}^2$ but what about $\mathbb{R}^d$? Is there a way to show that a collection of points can be separated by "inserting" planes between them? We take a look at that next. If the data is not separable by a line, then, in most cases, this process will not work perfectly. Some points will be classified correctly and some will not. Then, we can think about two more questions. We are not going to answer those here. Instead, I will just show you an example where the classification can fail, if the points are not separable by a line. Then, if you download this notebook, you can try with other curves and see what happens. Remember that, in our case, given a point $x=(x_1,x_2)$, classification is done according to $\text{sign}(f(x_1)-x_2)$, which can either be -1 or 1. # Change this function to select points with respect to a different curve. f = lambda x: x**2; x = np.linspace(0,1); # Generate some data points to play with. N = 100 xn = nr.rand(N,2) fig = pl.figure() figa = pl.gca(); # Plot classifier pl.plot(x,f(x),'r') # Classify based on f(x) yn = np.sign(f(xn[:,0])-xn[:,1]) colors = (yn+1)/2.0; pl.scatter(xn[:,0],xn[:,1],c=colors,s=30); pl.title('Classification based on f(x)') figa.axes.get_xaxis().set_visible(False) figa.axes.get_yaxis().set_visible(False) In this example, we can see that $x^2$ colours some points as black and others as white. Let us find a linear separator now. # Try percepton with that data. w = perceptron(xn,yn,MaxIter=1000) # Re-scale the weights to construct a new representation bnew = -w[0]/w[2]; anew = -w[1]/w[2]; y = lambda x: anew * x + bnew; figa = pl.gca() pl.scatter(xn[:,0],xn[:,1],c=colors,s=50); pl.title('Classification based on f(x)') pl.plot(x,f(x),'r',label='Separating curve.') pl.plot(x,y(x),'b--',label = 'Curve from perceptron algorithm.') pl.legend() figa.axes.get_xaxis().set_visible(False) figa.axes.get_yaxis().set_visible(False) In this case, our classifier cannot get all the cases right (white points should be above the blue line, black points below). This situation will probably become worse as we add more and more points.
https://nbviewer.jupyter.org/github/kgourgou/Linear-Perceptron/blob/master/Perceptron-Algorithm.ipynb
CC-MAIN-2020-40
refinedweb
1,206
59.9
Hello again. So far, my ventures have been productive, also thanks to some excellent support I got here. My thanks for that .. Now, however, I have a new problem >.<. Since I am planning on writing a rather huge program with several functions, which will be strung together at some point, I decided to split it up into individual, smaller programs first, to test if they all do what they are supposed to do. The first of these is the program with the code below this. It is designed to do the following (though the comment should give some hints :P): It accepts input for a name and stores it in a string, then it queries for a 'casting cost', again storing the input into a string. Now, casting cost is comprised of colorless (a simple number such as 1, 2, 3 or whatever) and the five main colors: White (W), Blue (U), Black (B), Red (R) and Green (G). Thus, a spell with a casting cost of 2 colorless and 2 green would be akin to 2GG. following a simple example program from the site, I used the program on the side that counts the number of times "cat" occurs in the input sentence. (Should be under the Lesson on Strings) I simply edited it to incorporate my variables instead of the variables used there. I compiled the code, got a few errors, quickly removed them (thank god, there were only some stupid errors like a forgotten semicolon or a forgotten " here and there :-D) and compiled again. It compiled! I was happy. Then I ran it. It asked me for a Spell Name. I was delighted, it worked. I entered a spell name, and it went on to ask me for Casting Cost! Woohoo! But as soon as I hit the enter/return key after entering a casting cost, the thing immediately shuts down . I thought I added all the proper instances of cin.ignore() and cin.get() to avoid this issue!. I thought I added all the proper instances of cin.ignore() and cin.get() to avoid this issue! Can anyone help me identify why my program immediately shuts down after I press the enter/return key after typing in the Casting Cost? Thank you so much! (lots of code...if anyone has any suggestions on how to make it more efficient while sticking to relatively easy code, I'd love to hear it, too.) Code:#include <cstdlib> #include <iostream> using namespace std; int main() { string SpellName = " "; // To ask for Spell Name cout<< "Spell Name: \n"; cin>> SpellName; cin.ignore(); string CastingCost = " "; // To ask for Mana Cost cout<< "Casting Cost: \n"; cin>> CastingCost; cin.ignore(); //Defining variables needed to find and recognise colors. int White_Counter = 0; int WhiteMana = 0; int Blue_Counter = 0; int BlueMana = 0; int Black_Counter = 0; int BlackMana = 0; int Red_Counter = 0; int RedMana = 0; int Green_Counter = 0; int GreenMana = 0; int ColorNumber = 0; string Colors = "Colorless.\n"; string Color1 = " "; string Color2 = " "; string Color3 = " "; string Color4 = " "; string Color5 = " "; // Series of 'for' statements with .find to find colored mana and count it. // ColorMana can be used for seeing if the spell is of a color AND the amount of mana. // Color_Counter is an indicator for the .find function to function properly. for(White_Counter = CastingCost.find("W", 0); White_Counter != string::npos; White_Counter = CastingCost.find("W", White_Counter)) { WhiteMana++; White_Counter++; // Move past the last discovered instance to avoid finding same string } for(Blue_Counter = CastingCost.find("U", 0); Blue_Counter != string::npos; Blue_Counter = CastingCost.find("U", Blue_Counter)) { BlueMana++; Blue_Counter++; // Move past the last discovered instance to avoid finding same string } for(Black_Counter = CastingCost.find("B", 0); Black_Counter != string::npos; Black_Counter = CastingCost.find("B", Black_Counter)) { BlackMana++; Black_Counter++; // Move past the last discovered instance to avoid finding same string } for(Red_Counter = CastingCost.find("R", 0); Red_Counter != string::npos; Red_Counter = CastingCost.find("R", Red_Counter)) { RedMana++; Red_Counter++; // Move past the last discovered instance to avoid finding same string } for(Green_Counter = CastingCost.find("G", 0); Green_Counter != string::npos; Green_Counter = CastingCost.find("G", Green_Counter)) { GreenMana++; Green_Counter++; // Move past the last discovered instance to avoid finding same string } // Series of 'if' statements to set color values to strings if (WhiteMana > 0) { Color1 = "White"; } if (BlueMana > 0) { Color2 = "Blue"; } if (BlackMana > 0) { Color3 = "Black"; } if (RedMana > 0) { Color4 = "Red"; } if (GreenMana > 0) { Color5 = "Green"; } // Set of 'if' statements that ouput the colors if the previous 'if' statements counted them if (Color1 == "White") { cout<<Color1; ColorNumber++; } if (Color2 == "Blue") { if (ColorNumber > 0) { cout<<" and "<<Color2<<""; ColorNumber++; } else { cout<<Color2; ColorNumber++; } if (Color3 == "Black") { if (ColorNumber > 0) { cout<<" and "<<Color3<<""; ColorNumber++; } else { cout<<Color3; ColorNumber++; } if (Color4 == "Red") { if (ColorNumber > 0) { cout<<" and "<<Color4<<""; ColorNumber++; } else { cout<<Color4; ColorNumber++; } if (Color5 == "Green") { if (ColorNumber > 0) { cout<<" and "<<Color5<<""; ColorNumber++; } else { cout<<Color5; ColorNumber++; } //Checking for correct reply to test if the program worked. int CorrectReply = 0; int ErrorMessage = 0; int Useless_Counter = 0; cout<< "Is this correct?\n Press 1 for yes, press 2 for no.\n"; cin>> CorrectReply; cin.ignore(); for (ErrorMessage = 0; ErrorMessage == 1; Useless_Counter++) { if (CorrectReply = 1) { cout<< "Thank you for using this program.\n"; ErrorMessage = 0; cin.get(); } else { if (CorrectReply = 2) { cout<< "Please return to your code editor and redo the code.\n"; ErrorMessage = 2; cin.get(); } else { cout<< "Error, wrong input. Please enter 1 for yes or 2 for no.\n"; ErrorMessage = 1; cin>> CorrectReply; cin.ignore(); } } } } }} }}
http://cboard.cprogramming.com/cplusplus-programming/88212-argh-*pulls-out-hairs*-please-help-me.html
CC-MAIN-2015-35
refinedweb
890
66.03
Bias-Variance Trade-off in DataScience and Calculating with Python The target of this blog post is to discuss the concept around and the Mathematics behind the below formulation of Bias-Variance Tradeoff. And in super simple term Total Prediction Error = Bias + Variance The goal of any supervised machine learning model is to best estimate the mapping function (f) for the output/dependent variable (Y) given the input/independent variable (X). The mapping function is often called the target function because it is the function that a given supervised machine learning algorithm aims to approximate. The Expected Prediction Error for any machine learning algorithm can be broken down into three parts: Bias Error Variance Error Irreducible Error Why at all we need for MSE (Mean Squared Error) for training and testing datasets separately Exploring these in detail is very important to understand the whole concepts around the Bias-Variance tradeoff. Training and testing datasets have different purposes. The training set trains the model how to predict the dependent variable values and we derive the Estimator equation from the training dataset. While, the testing datasets are there for testing the Estimator equation on how good an estimator they are really. Now lets examine this in depth. In the regression setting, the most commonly-used measure is the mean squared error (MSE), is given by where f ˆ (x i) is the prediction that f ˆ gives for the i-th observation. The MSE will be small if the predicted responses are very close to the true responses, and will be large if for some of the observations, the predicted and true responses differ substantially. The Test-MSE Equation is computed using the training data that was used to fit the model, and so should more accurately be referred to as the training MSE. But in general, we do not really care how well the method works training on the training data. Rather, we are interested in the accuracy of the predictions that we obtain when we apply our method to previously unseen test data. Why is this what we care about?. To state it more mathematically, suppose that we fit our statistical learn- ing method on our training observations {(x1 , y 1 ), (x2 , y2 ), . . . , (xn , yn)}, and we obtain the estimated f̂. We can then compute If these are approximately equal to y1, y2 , . . . , yn, then the training MSE given by is small. However, we are really not interested in whether Instead, we want to know whether fˆ(x0 ) (i.e. the estimated target value based on a test-data input) is approximately equal to y0, where (x0, y0 ) is a previously unseen test observation not used to train the statistical learning method. We want to choose the method that gives the lowest test MSE, as opposed to the lowest training MSE. In other words, if we had a large number of test observations, we could compute the average squared prediction error for these test observations (x0 , y0 ). And then we’d just like to select the model for which the average of this quantity — the test MSE — is as small as possible. But what if no test observations are available? In that case, one might imagine simply selecting a statistical learning method that minimizes the training MSE. Unfortunately, this strategy does not work. There is no guarantee that the method with the lowest training MSE will also have the lowest test MSE. The below figure-A illustrates this phenomenon on a simple example. In the lefthand panel of Figure A, we have generated observations from true f given by the black curve. The orange, blue and green curves illus- trate three possible estimates for f obtained using methods with increasing levels of flexibility. The orange line is the linear regression fit, which is relatively inflexible. The blue and green curves were produced using smoothing splines. It is clear that as the level of flexibility increases, the curves fit the observed data more closely. We now move on to the right-hand panel of Figure-A. The grey curve displays the average training MSE as a function of flexibility, or more formally the degrees of freedom, for a number of smoothing splines. The degrees of freedom is a quantity that summarizes the flexibility of a curve. The test MSE is displayed using the red curve in the right-hand panel of Figure A. As with the training MSE, the test MSE initially declines as the level of flexibility increases. However, at some point the test MSE levels off and then starts to increase again. Consequently, the orange and green curves both have high test MSE. The blue curve minimizes the test MSE, which should not be surprising given that visually it appears to estimate f the best in the lefthand panel of Figure-A In the right-hand panel of Figure-A,. And when a given method yields a small training MSE but a large test MSE, we are said to be overfitting the data. This happens because our statistical learning procedure is working too hard to find patterns in the training data, and maybe picking up some patterns that are just caused by random chance rather than by true properties of the unknown function f. However, regardless of whether or not overfitting has occurred, we almost always expect the training MSE to be smaller than the test MSE because most statistical learning methods either directly or indirectly seek to minimize the training MSE. So now the final point which is The Bias-Variance Trade-Off The U-shape observed in the test MSE curves in Figure-A above turns out to be the result of two competing properties of statistical learning methods. It is possible to show that the expected test MSE (or sometimes also called Expected Prediction Error ), for a given value x0, can always be decomposed into the sum of three fundamental quantities: the variance of estimated f(x0 ), the squared bias of estimated f(x0 ) and the variance of the error terms. The left-hand side of the above equation defines the expected test MSE and refers to the average test MSE that we would obtain if we repeatedly estimated f using a large number of training sets, and tested each at x0. The overall expected test MSE can be computed by averaging over all possible values of x0 in the test set Definition of Variance The variance of the model is the amount the performance of the model changes or the amount by which the estimated f would change, when it is fit on different training data sets. It captures the impact of the specifics the data has on the model. Since the training data are used to fit the statistical learning method, different training data sets will result in a different estimated-f . But ideally, the estimate for f should not vary too much between training sets. However, if a method has high variance then small changes in the training data can result in large changes in estimated-f . In general, more flexible statistical methods have higher variance. Variance informally means how far your data is spread out. Overfitting is you memorizing 10 questions for your exam and on the next day exam, only one question (our of that 10 memorized) has been asked in the question paper. Now you will answer that one question correctly (based on training), but you have no idea what the remaining questions are(Question are HIGHLY VARIED from what you read). In overfitting, the model will memorize the entire train data such that it will give high accuracy on the training-dataset but will fail in test. For high variance models an alternative is feature reduction (e.g. pruning in Decision Tree, we will cover this in more detail further down in this article), but including more training data is also a viable option. This means when I repeat the entire model building process multiple times, the variance is HOW MUCH THE PREDICTIONS FOR A GIVEN POINT VARY, between different realizations of the model. Let θ̂ be a point estimator for a parameter θ. In another form, so you can take a look at the above formula in a slightly different way — the expression of the Variance will be Where L=100 data sets each with each with N=25 Now take note of an important Mathematical Identity on Variance which is below And below is the formal proof Definition of Bias bias refers to the error that is introduced by approximating a real-life problem, which may be extremely complicated, by a much simpler model. For example, linear regression assumes that there is a linear relationship between Y and X1, X2, . . . , Xp . It is unlikely that any real-life problem truly has such a simple linear relationship, and so performing linear regression will undoubtedly result in some bias in the estimate of the f. In the above figure, the true f is substantially non-linear, so no matter how many training observations we are given, it will not be possible to produce an accurate estimate using linear regression. In other words, linear regression results in high bias in this example. So, the bias is a measure of how close the model can capture the mapping function between inputs and outputs. When a model has a high bias it means that it is very simple and that adding more features should improve it. Bias does not depend on data So, the error due to bias is taken as the difference between the expected (or average) prediction value from my model and the correct value which I am trying to predict. Now the basic question is I am only taking one model so how the concept of expected or average prediction values comes here. To understand that, imagine repeating the whole model building process more than once: each time I gather new data and run a new analysis creating a new model. Due to randomness in the underlying data sets, the resulting models will have a range of predictions. So now, the Bias measures how far off these models’ predictions are from the correct value. So, let θ̂ be a point estimator for a parameter θ. Then θ̂ is an unbiased estimator if E(θ̂ ) = θ, else θ̂ is said to be biased. The bias of a point estimator θ̂ is given by If the bias is larger than zero, we also say that the estimator is positively biased, if the bias is smaller than zero, the estimator is negatively biased, and if the bias is exactly zero, the estimator is unbiased. In another form, for you to take a look at the above Bias formula in a slightly different way — the expression of the Bias will be Where, just like the alternate expression of Variance, L=100 data sets each with each with N=25 Actual Calculation of Bias To find the bias of a model . High Bias The two main reasons for high bias are insufficient model capacity and underfitting because the training phase wasn’t complete. For example, if you have a very complex problem to solve (e.g. image recognition) and you use a model of low capacity (e.g. linear regression) this model would have a high bias as a result of the model not being able to grasp the complexity of the problem. What is an estimator An estimator is a rule, often expressed as a formula, that tells how to calculate the value of an estimate based on the measurements contained in a sample. For example, the sample mean is one possible point estimator of the population mean μ. Clearly, the expression for ȳ is both a rule and a formula. It tells us to sum the sample observations and divide by the sample size n. (source). Now lets see the process of calculating Estimates Suppose that we wish to specify a point estimate for a population parameter that we will call θ . The estimator of θ will be indicated by the symbol θ̂, read as “θ hat.” The “hat” indicates that we are estimating the parameter immediately beneath it. We can say that it is highly desirable for the distribution of estimates — or, more properly, the sampling distribution (where Learning Samples are randomly drawn) of the estimator — to cluster about the target parameter as shown in Figure-A. In other words, we would like the mean or expected value of the distribution of estimates to equal the parameter estimated; that is, E(θ̂) = θ. Point estimators that satisfy this property are said to be unbiased. The sampling distribution for a positively biased point estimator, one for which E(θ̂) > θ , is shown in Figure-B. Figure-C below shows two possible sampling distributions for unbiased point estimators for a target parameter θ. We would prefer that our estimator have the type of distribution indicated in Figure C-(b) because the smaller variance guarantees that in repeated sampling a higher fraction of values of θ̂ 2 will be “close” to θ. Thus, in addition to preferring unbiasedness, we want the variance of the distribution of the estimator V (θ̂ ) to be as small as possible. Given two unbiased estimators of a parameter θ, and all other things being equal, we would select the estimator with the smaller variance. Now for the statistical calculation of this, rather than using the bias and variance of a point estimator to characterize its goodness, we want to employ E[(θ̂ − θ)²], the average of the square of the distance between the estimator and its target parameter. The mean square error of a point estimator θ̂ is MSE(θ̂) = E[(θ̂ − θ)² ]. Pictorially Below a very popular graph, you will see in many pieces of literature describing the relationship between Bias and Variance. Some Interpretations from the above Graph Looking at the above plot, some observations we can see, that the bias tends to decrease faster than the variance increases. So when tuning our model, this portion of the curve, is like the low-hanging fruit that we can easily get — so an incremental improvement on the red curve above gives a big decrease in bias (increase in performance). However, when we continue further on this path, with each increment in model complexity, you get a lower increase in performance; i.e. diminishing returns sets in. Furthermore, as you begin to overfit, the model becomes less able to generalize and so exhibits larger errors on unseen data i.e . Variance is creeping in. The key Equation of Variance and Bias The mean square error of an estimator θ̂ , MSE(θ̂), is a function of both its variance and its bias. If B(θ̂ ) denotes the bias of the estimator θ̂ the relation between them can be expressed as (we will go through the proof of this below) MSE(θ̂) = V(θ̂) + [B(θ̂)]² Which more generally will be below Bias Variance Tradeoff There is no escape from the relationship between bias and variance in machine learning which in general is - Increasing the bias will decrease the variance. - Increasing the variance will decrease the bias. In short, the bias is the model’s inability to learn enough about the relationship between the model’s features and labels, while the variance captures the model’s inability to generalize on new, unseen examples. A model with high bias oversimplifies the relationship and is said to be underfit. A model with high variance has learned too much about the training data and is said to be overfit. Of course, the goal of any ML model is to have low bias and low variance but, in practice, it is hard to achieve both. For example, increasing model complexity decreases bias but increases variance, while decreasing model complexity decreases variance but introduces more bias. However, recent work suggests that when using modern machine learning techniques such as large neural networks with high capacity, this behavior is valid only up to a point. In observed experiments, there is an “interpolation threshold” beyond which very high capacity models are able to achieve zero training error as well as low error on unseen data. Of course, you need much larger datasets in order to avoid overfitting on high capacity models. The Tradeoff in a Nutshell - A model with low variance and low bias is the ideal model. - A model with low bias and high variance is a model with overfitting. Generally speaking, overfitting means bad generalization, memorization of the training set rather than learning a generic concepts behind the data. - A model with high bias and low variance is usually an underfitting model. - A model with high bias and high variance is the worst case scenario, as it is a model that produces the greatest possible prediction error. Mathematical Derivation of the Bias-Variance Equation First some Mathematical notation for Expected value calculations for Mean, Variance etc for a sample of data. Taking inspiration from the book The Elements of Statistical Learning If we assume that Y=f(X)+ϵ and E[ϵ]=0 and Var(ϵ)=σ², then we we can derive the expression for the expected prediction error of a regression fit using squared error loss For notational simplicity let And recount the below identity that So now lets Algebraically expand the Expression for Expected Prediction Error Note in the 4-th line above I have used an Similarly, expand the second component of the above derivation. Combining from the above two derivations we get the final relation between Expected Prediction Error on the LHS and the Bias and Variance of the estimator as below. Now a simple Python Implementation to calculate Bias and Variance The API of the bias_variance_decomp() function APIbias_variance_decomp(estimator, X_train, y_train, X_test, y_test, loss='0-1_loss', num_rounds=200, random_seed=None)estimator (or model in our case ) : object A classifier or regressor object or class implementing a fit predict method similar to the scikit-learn API.X_train : array-like, shape=(num_examples, num_features)A training dataset for drawing the bootstrap samples to carry out the bias-variance decomposition.y_train : array-like, shape=(num_examples)Targets (class labels, continuous values in case of regression) associated with the X_train examples.X_test : array-like, shape=(num_examples, num_features)The test dataset for computing the average loss, bias, and variance.y_test : array-like, shape=(num_examples)Targets (class labels, continuous values in case of regression) associated with the X_test examples.loss : str (default='0-1_loss')Loss function for performing the bias-variance decomposition. Currently allowed values are '0-1_loss' and 'mse'.num_rounds : int (default=200)Number of bootstrap rounds for performing the bias-variance decomposition.random_seed : int (default=None)Random seed for the bootstrap sampling used for the bias-variance decomposition. Ways to mitigate this bias-variance tradeoff on small- and medium- scale problems Ensemble methods to the rescue, which are meta-algorithms which combine several machine learning models as a technique to decrease the bias and/or variance and improve model performance.. By building several models, with different inductive biases, and aggregating their outputs, we hope to get a model with better performance. Below, we’ll discuss some commonly used Ensemble methods, including bagging, boosting, and stacking. BAGGING Bagging (short for bootstrap aggregating) is a type of parallel ensembling method and it is used to address high-variance in machine learning models. The bootstrap part of bagging refers to the datasets used for training the ensemble members. Specifically, if there are k sub-model then there are k separate datasets used for training each sub-model of the ensemble. Each dataset is constructed by randomly sampling (with replacement) from the original training dataset. This means there is a high probability that any of the k datasets will be missing some training examples, but also any dataset will likely have repeated training examples. The aggregation takes place on the output of the multiple ensemble model members, either an average in the case of a regression task or a majority vote in the case of classification. A good example of a bagging Ensemble method is the Random Forest: multiple decision trees are trained on randomly sampled subsets of the entire training data, then the tree predictions are aggregated to produce a prediction, as shown in below Figure. Most recognized machine learning libraries have implementations of bagging methods. For example, to implement a Random Forest regression in scikit-learn from sklearn.ensemble import RandomForestRegressor # Create the model with 50 trees RF_model = RandomForestRegressor(n_estimators=50, max_features='sqrt', n_jobs=-1, verbose = 1) # Fit on training data RF_model.fit(X_train, Y_train) Model averaging as seen in bagging is a powerful and reliable method for reducing model variance. Different Ensemble methods combine multiple sub-models in different ways, sometimes using different models, different algorithms, or even different objective functions. With bagging, the model and algorithms are the same. For example, with Random Forest, the submodels are all short Decision Trees. The next Ensemble technique is BOOSTING Unlike bagging, boosting ultimately constructs an ensemble model with more capacity than the individual member models. For this reason, boosting provides a more effective means of reducing bias than variance. The idea behind boosting is to iteratively build an Ensemble of models where each successive model focuses on learning the examples the previous model got wrong. In short, boosting iteratively improves upon a sequence of weak learners taking a weighted average to ultimately yield a strong learner. The next Ensemble technique is STACKING Stacking is an Ensemble method which combines the outputs of a collection of models to make a prediction. The initial models, which are typically of different model types, are trained to completion on the full training dataset. Then, a secondary meta-model is trained using the initial model outputs as features. This second meta-model learns how to best combine the outcomes of the initial models to decrease the training error and can be any type of machine learning model. An example of reducing Variance of a Decision Tree Decision trees are powerful classifiers. Algorithms such as Bagging try to use powerful classifiers in order to achieve ensemble learning for finding a classifier that does not have high variance. But Decision trees are prone to overfitting. A model has high variance if it is very sensitive to (small) changes in the training data. Models that exhibit overfitting are usually non-linear and have low bias and variance . Decision trees are non-linear. A decision tree has high variance because, if you imagine a very large tree, it can basically adjust its predictions to every single input. Consider you wanted to predict the outcome of a Cricket game. A decision tree could make decisions like: IF 1. player X is on the field AND 2. team A has a won the toss AND 3. the weather is sunny AND 4. the number of attending fans >= 26000 AND 5. it is past 3pm THEN team A wins. If the tree is very deep, it will get very specific and you may only have one such game in your training data. It probably would not be reasonable to base your predictions on just one example. Now, if you make a small change e.g. set the number of attending fans to 25999, a decision tree might give you a completely different answer (because the game now doesn’t meet the 4th condition). Linear regression, for example, would not be so sensitive to a small change because it is limited (or “biased” ) to linear relationships and cannot represent sudden changes from 25999 to 26000 fans. That’s why it is important to not make decision trees arbitrary large/deep. This limits its variance. This is why we usually use pruning for avoiding the trees to get overfitted to the training data. Pruning reduces the size of decision trees by removing parts of the tree that do not provide power to classify instances. One way can be ignoring some features and using others. Pruning is computationally inexpensive, reduces complexity significantly, and variance to some extent, but also increases bias. Let's implement the above with a quick numerical example with Scikit-learn to see how Variance Reduction is achieved by Pruning a Decision Tree but with the cost of Increased Bias. In the above example, we saw after Pruning Variance is reduced by -54.32% but Bias is increased by 71.06% Thank you for reading :)
https://medium.com/analytics-vidhya/bias-variance-trade-off-in-datascience-and-calculating-with-python-766158812c46?source=post_internal_links---------4----------------------------
CC-MAIN-2021-04
refinedweb
4,067
50.16
I got the code to work after some trial and error. However, is there a simpler/more efficient way to run the code? I changed i = x to i = ** (0.5) after reading a discussion thread about how it would be redundant to test numbers above the square root as they would be divisible by the reverse of what they were before ( Is_prime error ). This makes it more efficient, and while its irrelevant on small-scale tests like these, it matters as the scale grows. So, are there other things I should be looking to do as good practice moving forward? def is_prime(x): i = x ** (0.5) if x < 2: print "%d is not prime" % (x) return False elif x == 2: return True else: while i >1: for y in range(2,x): if x%y == 0: print "%d is not prime" % (x) return False else: #print "%d hit the else" % (y) i -= 1 else: return True
https://discuss.codecademy.com/t/15-6-is-prime/268058
CC-MAIN-2018-51
refinedweb
158
86.23
Dinos in Space - pre-release logic-puzzle game harry (potter) if you're really clever, collect all the snax... there's an in-game tutorial that shows you all the controls as you go. there's an in-game editor as well so you can create your own puzzles! Links - - Windows - Releases Dinos in Space d1 — 19 Jul, 2011 Dinos in Space final release (windows + mac) — 16 May, 2012 Dinos in Space pre-release — 9 Apr, 2012 Dinos in Space final release — 5 May, 2012 Pygame.org account Comments Me 2012-04-15 03:45:10 I get a pygame.error: No available video device. I'm on a machine on which, for some reason, you have to add: os.environ['SDL_VIDEODRIVER']='windib' For that error not to show up, you might want to add a try, except (except what?...) in your program's initialisation :) OR, pygame's faq suggests the following lines: import os import platform if platform.system() == 'Windows': os.environ['SDL_VIDEODRIVER'] = 'windib' John Saba 2012-04-15 21:05:23 Hi Dominic, Thanks for letting me know the error. I've got a few questions: Are you running windows? If so which version? For the os.environ line, do you mean that you have to set that for any pygame program to run on your machine? I'll try adding those lines in and posting an update. Me 2012-04-16 04:18:43 My version of windows is Windows XP sp3 and my directx is 9.0c, the latest. I have no idea what causes this error but the machine I have at home (also win xp sp3 directx 9.0c) works without these lines added. And yes, I need these lines to run any pygame program that opens a window.
http://www.pygame.org/project-Dinos+in+Space-1936-3890.html
CC-MAIN-2018-05
refinedweb
295
75.91
Opened 3 years ago Closed 3 years ago #22756 closed New feature (fixed) Technical 404 could say which view was run, if any. Description Given a view: def myview(request): raise Http404('test') which is mounted at, say, /a/b/c/, where a and b may be url namespaces themselves (ie: urlconfs pulled together via include('x.y')) it is laborious to actually establish the callable that was executed, without using django-debug-toolbar; you have to manually traverse from the ROOT_URLCONF to wherever the urlpatterns which mount the myview are (or use something like django-extensions show_urls; etc etc) Coming on board to an existing project could be thus made easier, if, when a 404 is thrown by a view (rather than the absence of a view) information was expressed about where to look to alter or fix that. In DEBUG, when the TECHNICAL_404_TEMPLATE is used, it ought to be possible to attempt to resolve the request.path to a named callable in many circumstances by adding a new value to the technical_404_response's Context, using something like the tests debug-toolbar does, which I reproduce here (changed for brevity/structure) in case they change over time: name = _("<no view>") try: obj = resolve(request.path) except Resolver404: # not what debug-toolbar catches; don't know why. pass else: if hasattr(obj, '__name__'): name = obj.__name__ elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): name = obj.__class__.__name__ if hasattr(obj, '__module__'): module = obj.__module__ name = '%s.%s' % (module, name) Change History (9) comment:1 Changed 3 years ago by comment:2 Changed 3 years ago by comment:3 Changed 3 years ago by comment:4 Changed 3 years ago by comment:5 Changed 3 years ago by I left comments for improvement on PR. Please uncheck "Patch needs improvement" when you update it, thanks. comment:6 Changed 3 years ago by I updated the patch, but I didn't add a test to make sure the view path is displayed instead of the view name. I tried adding one, but the view path was coming out automatically in the testing setup before I made this change. comment:7 Changed 3 years ago by Looks good. I noted how you can update the test so that it will fail with the old version of the code and also suggested one more test so that all code paths are tested. comment:8 Changed 3 years ago by The test meant to fail on the old version still didn't work for me, so I left it out. I made a pull request:
https://code.djangoproject.com/ticket/22756
CC-MAIN-2017-22
refinedweb
433
67.28
I am working on a problem, and i am having some difficulty starting it. If anyone has time , it would be greatly appreciated if they had a quick look at my code, and what i need to do. Here is what im trying to do: a simulator program for a robot designed to move packages around in a warehouse environment. The input to your program (from standard input) will contain a map of the environment in its original state, followed by a blank line, followed by a sequence of instructions to be performed by the robot. The map specifies the size, shape and initial positions of all the packages in the environment, as well as the positions of the walls, and the initial position and orientation of the robot. The walls will be represented by the "star" character *. The robot will be represented by the characters ^, v, < or >, depending on which direction it is facing. There will be at most 26 "packages" in the environment, labeled with the letters A,B,C, etc. (note that packages may vary in size and shape). The robot is capable of four basic operations, as follows: L turn left R turn right F (try to) move forward P print the state of the environment The instructions for the robot will consist of an ordered sequence of these four basic instructions L,R,F,P enclosed in parentheses. When it executes an L or R instruction, the robot remains in the same location and only its orientation changes. When it executes the F instruction, the robot attempts to move a single step in whichever direction it is facing. If there is a package immediately in front of the robot when it tries to move forward, the package will move with the robot (in the same direction). If there are one or more packages immediately in front of that package, they will also move, as well the packages immediately in front of them, and so on. We assume the robot is strong enough to push any number of packages in front of it. Since the walls are immovable, however, there will be some situations where the robot tries to move forward but fails. This will happen if there is a wall immediately in front of the robot, or if there is a wall immediately in front of a package being pushed by the robot (either directly or indirectly). In these cases, the F instruction has no effect on the environment, and the robot continues to the next instruction. (Part of the challenge of the project is to determine which packages are being pushed, and whether or not a wall is being pushed.) When a P instruction is executed, the current state of the environment should be printed, followed by a blank line. The robot leaves a trail behind it wherever it goes. So, when the environment is printed, places where there is no package or wall should be indicated by: a dot '.' if the robot has been there at some time during its path, and a blank space ' ' otherwise. Attached is an exampleAttachment 6806 The environment might not be rectangular, but you may assume that it is entirely surrounded by walls, so there is no danger of the robot falling off the edge of the environment. Packages may have any shape, but you can assume that all characters belonging to a single package are contiguous (i.e. connected to each other). You may assume the environment is no larger than 80 x 80 (including walls) and that each package consists of no more than 128 characters. (Note: the program can be written to handle environments and packages of arbitrary size, but we do not force you to do so.) Here is what i have done and where i need help: Thanks alot for your help.Thanks alot for your help.Code: #include <stdio.h> #define ROBOT 26 #define WALL 27 #define NONE -1 #define MAX_ROWS 80 #define MAX_COLS 80 #define EAST 0 #define NORTH 1 #define WEST 2 #define SOUTH 3 void scan_state( int *pnrows, int ncols[MAX_ROWS], int object[MAX_ROWS][MAX_COLS], int *pdirection ); void print_state( int nrows, int ncols[MAX_ROWS], int object[MAX_ROWS][MAX_COLS], int direction ); int main( void ) { int nrows; // number of rows in environment int ncols[MAX_ROWS]; // number of columns in each row int object[MAX_ROWS][MAX_COLS]; // object at each location int direction; // which way the robot is facing void scan_state( int *pnrows, int ncols[MAX_ROWS], int object[MAX_ROWS][MAX_COLS], int *pdirection ) { int ch; int r,c; r = 0; c = -1; while (( ch = getchar() ) != '(' ) { c++; if ( ch == '\n' ) { ncols[r++] = c; c = -1; } // else if { ... // ... Not sure what goes in here ... // } } *pnrows = r; } void print_state( int nrows, int ncols[MAX_ROWS], int object[MAX_ROWS][MAX_COLS], int direction ) { // need help here too plz }
https://cboard.cprogramming.com/c-programming/83393-help-moving-robot-maze-printable-thread.html
CC-MAIN-2017-22
refinedweb
798
57.5
Right so I'll try to describe my status as quickly as I can. I'm CGI artist - photographer - mainly visual work. I started about 1 year ago learning python to help me with my work. Since then I can not stop using it. It decreased my working time by hours. Now most of the code I write is only for me as it stays in code - which is very non user friendly and FIX- meaning I cant change variables. Now I would like to be able to have UI. I have been fighting with UI's for about 6 months. Most of them I managed to solve however recent UI chellenge just break my head and I end up whining like baby. Just cant get through it. Basically in the past I was controlling single things. Click > Do > Done. Now I want to set up rules and then based on those rules I want to execute final action - this just don't fit in my head. Anyway I'll start from basics: What IDE ?! In past I used Maya now I need a standalone IDE that I could test scripts in and use. I looked around I got for example trial of JetBrains PyCharm but I cant execute script no matter what I do - made my cry hard for past few hours. for QT I use QT Editor I think I'm fairly happy with it so far. so next question is what really is xml with QT? One of my apps can only take UI using this format and xml is quite wide subject to research. Could any1 point me to a more compressed readable for new users definition please. And lastly. Here is the basic script I'm working on. - Code: Select all ActionA = "False" AvtionB = "False" def checkboxA(tick): if tick == True: ActionA = "True" print ActionA print " checkboxA Enabled" else: print " checkboxA Disabled" def checkboxB(tick): if tick == True: ActionB = "True" print " checkboxB Enabled" else: print " checkboxB Disabled" Now what I'm trying to do is to have few checkboxes. Than depending on their True/False value will cause button to execute certain commands. For some reason this script is crashing. Now I have no idea if its Python or QT or the software itself is buggy... reason I think I need standalone IDE to test it. Later on I want to add input lines and other stuff but thats not on my head right now. So how do I go about creating settings in python and then executing them. Is my approach the right one? Thanks, bye.
http://www.python-forum.org/viewtopic.php?p=7191
CC-MAIN-2015-06
refinedweb
432
82.14
II. Data Preprocessing using Pandas: From part 1 of this series,, we focused on web scrapping with selenium and fie handling. We managed to store the scrapped data in ‘pigiame.csv’ file. In this part of the series, we will have to first load the CSV file into jupyter’s Integrated development environment(ide), clean it and do some Exploratory Data Analysis(EDA) on it. In case you are new to jupyter you can learn more on it at The first step before running any code is loading the necessary libraries. import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter - Pandas will be used for data frame manipulation. - Seaborn and matpoltlib’s sub-library pyplot will be used for visualization. - Numpy will be used for its mathematical capabilities. - PercentFormatter module in matpoltlib’s sub-library ticker will be used to convert axis values into percentages. Loading the dataset is possible with the help of the code below: # Importing dataset tvs = pd.read_csv('pigiame.csv', header=None) tvs.head() The output shows a glimpse of the dataset after loading: After loading our scrapped dataset, we need to clean it before we use it for analysis. The series of code below is well commented to show the cleaning process that is unique to every dataset. - Duplicate values have to be dropped because some online retailers posted more than once therefore the data frame has replicated rows. After which you will notice the loss of a chunk of data. tvs.drop_duplicates(inplace=True) - Renaming columns with logical names. tvs.columns = ['Product', 'Condition', 'Brand', 'Location', 'Description', 'Price'] tvs.head(2) The output confirms that the columns have been renamed: From the above image, we can see that the last column(price) is a string. However, that column is more useful to us in numerical form. Through feature engineering, this can be attained. - Splitting currency(KSh) from price values(00,000): To obtain two columns: currency and price. tvs[['Currency','Price']] = tvs['Price'].str.split(' ' , expand=True) - Dropping currency column because the column is of a uniform distribution hence offering no value to this analysis. tvs.drop(['Currency'], axis=1, inplace=True) - Removing the comma in the ‘price’ column by splitting price values at the thousandth place value into two columns ‘price1’ and ‘price2’ and rejoining them to as Price without the comma. tvs[['Price1', 'Price2']] = tvs['Price'].str.split(',' , expand=True) tvs['Price'] = tvs['Price1'] + tvs['Price2'] - Dropping ‘Price1’ and ‘Price2’ columns because we have a clean column from the previous code-named ‘price’. tvs.drop(['Price1', 'Price2'], axis=1, inplace=True) tvs.head() The output is a glimpse of our new columns Price: - Null values are not good for analysis. Therefore the should be dealt with either through deletion or imputation. In our case, missing values were brought about after generating a cleaner price column. # Printing out sum of null values print('Missing values after feature engineering are: '+ str(tvs['Price'].isnull().sum())) # Dropping null values tvs.dropna(inplace=True) # Printing out the sum of null values after dropping. print('Missing values after dropping null values are: '+ str(tvs['Price'].isnull().sum())) Output: - Input from the user comes in form of a string. Therefore, we need to change the price column data type to integer. Followed by confirming data types. # Confirming data types print('Column data types before \n:'+ str(tvs.dtypes) + '\n') # Changing Price column data type to integer tvs['Price'] = tvs['Price'].astype(int) # Confirming data types print('Column data types after \n:'+ str(tvs.dtypes)) The output shows that we have converted the column Price to its appropriate data type: Descriptive statistics is important as it presents large datasets in a summarized and meaningful way for simpler interpretation. However, it does not explain everything in our data. The code below brings the output to our descriptive statistics on the pigiame dataset. tvs.describe(include='all') The output shows the following: Count, unique, top and freq are statistical interpretations of categorical columns. In this case product, condition, brand, location and description. - Count is the number of non-empty cells per column or feature. - Unique if the number of factors per column. - Top is the most frequent factor in a column while freq is its frequency. Mean, std, min, 25%, 50%, 75% and max are all statistical interpretations of numerical columns. In this case price. - mean is the average. - std is the standard deviation. - 25%, 50% and 75% are percentiles to show the distribution of data. - min and max are the minimum and maximum values respectively. Exploratory Data Analysis is one of the most important steps in data science. The main reason for its use is to get to understand the data in-depth. That is to say the size, attributes and patterns in or between one or more features in a dataset. When accuracy is at it’s best, data exploration can be used to improve it. Through exploration, feature engineering and selection are also possible. The exploration process can be made easier through data visualization. Data exploration processes include: - Univariate analysis: Analysis of one feature. - Bivariate analysis: Between two variables to determine their relationship. - Multivariate analysis: Between multiple dependent features. - Principal Component Analysis: Correlation patterns of features to reduce their number. In our case, it will not be necessary because we have no correlated features. Univariate analysis. - Looking into the number of distinct tv-brands on pigiame. print('The number of unique tv brands are: '+ str(len(tvs['Brand'].unique()))) Output: The code below helps visualize by count brands by their popularity in pigiame database. tv_brands = pd.DataFrame(tvs['Brand'].value_counts()) tv_brands.reset_index(inplace=True) tv_brands.columns = ['Brand', 'Count'] plt.figure(figsize=(10,6)) chart = sns.barplot(x='Brand', y='Count', data=tv_brands) chart.set_xticklabels(chart.get_xticklabels(), rotation=45) print(chart) Output: Tv-Brands. From the above figure, it is clear that Hisense is the most popular brand followed by Samsung, TCL and Sony. Tv brands in other categories less LG and Skyworth follow. - Location feature has different unique entries but will later be summarised into Nairobi in general. The code and output can be seen below. # Get the unique entries bu count of location column in TVs data frame. tvs['Location'].value_counts() The few entries that are not in Nairobi can either be deleted or converted to Nairobi since they are too few to make a change. # Change all entries in Location column into 'Nairobi' tvs['Location'] = 'Nairobi' tvs['Location'].value_counts() Output: The feature Product has soo many unique values and from an analytical point of view, this might not be very useful. However, from the code and output below, notice that the product column has inch measurement in it. This is a very powerful tool especially in predicting the price of a TV. Therefore, through feature engineering, we can extract and create a new column ‘Screen Size’. # Code to view the product column in tvs dataframe. tvs.head(10)['Product'] First 10 values of product column. # Extract the inches from Product column and store in sizes variable. tvs['Screen Size'] = tvs['Product'].str.extract('(\d\d)', expand=True) # Checking the number of rows. print(len(tvs['Screen Size'])) # Removing missing values from the data. tvs = tvs[pd.notnull(tvs['Screen Size'])] # Checking the number of rows after removing missing values print(len(tvs['Screen Size'])) # View the first 10 entries for changes. tvs.head(10) The output below shows that the extraction of inches from Product to the last column screen size has been successful. The most popular screen size in pigiame can be visualized with the help of the code below. # Create a dataframe from the value counts of all the unique Screen sizes. tv_sizes = pd.DataFrame(tvs['Screen Size'].value_counts()) tv_sizes.reset_index(inplace=True) # Rename the columns into Size and Count tv_sizes.columns = ['Size', 'Count'] # Create a cumpercentage column using the count column and getting the cummulative percentage. tv_sizes["cumpercentage"] = tv_sizes["Count"].cumsum()/tv_sizes["Count"].sum()*100 # creating a figure size. plot = plt.figure(figsize=(15,6)) ax = plot.subplots() # Creating the first plot with size on the x-axis and count on the y-axis. ax.bar(tv_sizes["Size"], tv_sizes["Count"], color="C0") # Enables axis sharing on the x-axis by creating a twin. ax2 = ax.twinx() # Plots the size on the x-axis and cumpercentage on the y-axis. ax2.plot(tv_sizes["Size"], tv_sizes["cumpercentage"], color="C1", marker="o", ms=4) # formats the cumulative values on the right y-axis into percentage form. ax2.yaxis.set_major_formatter(PercentFormatter()) #Visualize the plot. plot.show() From the output below, we can say that the most popular screen sizes are 32, 43, 55, 40, 49, 65, 50, 24, and 75. The code below helps view the Tv_sizes data frame created earlier. The data frame shows 32 to 75 inch in the figure above, covers up to 97.9% as per the data in the data frame. tv_sizes The code below shows the most expensive and the most economical brands. plt.figure(figsize=(10,10)) sns.relplot(x='Price', y='Brand', hue='Screen Size', data=tvs) The output shows that LG, Samsung and sony have the most expensive TVs on average. We can also spot an outlier in Skyworth. Cleaning the screen size column is important. Some rows have some minor issues. For instance, screen sizes of 2 or ‘4o’ do not make sense. Visualizing these rows one after another would be proof and necessary changes can be made through filtering out and changing cell values. Making such changes can be done with the following steps Step I: Extract and visualize rows by value. This step can be used for clarity. Example: Extracts all columns from TVs data frame with the string equal to 4k in the Screen Size column. This is because 4k is not screen size. Therefore we need to handle this issue. # If the column Screen Size is a string, apostrophes are required. The vice versa is true. filter = tvs['Screen Size'] == '4k' # filter variable has some boolean values. Therefore the code below shows rows satisfying the above requirement(their boolean values are true). tvs[filter] The output shows that there are wrong placements of inches the screen size column. Therefore correction for cleaner data is mandatory. Step II: Change the values of a cell. You can do this step if the cells you need to change are not many. If that is not the case, you might want to use a different approach. For instance, deleting the cells in question. # iloc is a function that takes integer arguments of a row and column number, therefore, identifying the specific cell and assigning the new value. # tvs.iloc(row_number, column_number) = new_value_to_replace_with A good example from our previous image is that at the first row(584) and the product column, the row has a tv of size 55 inches rather than 4k. Therefore to change the corresponding cell in column screen size, we would use the code below. tvs.iloc(6, 584) = '55' The screen size column is 6 and the row is 584. Followed by assigning a string value of ’55’ since the column is of type object. Step III: Deleting/dropping of a cell. We have seen how to drop a column before. The same code holds for dropping rows with minor changes. The code blueprint below guides on how to do just that. tvs.drop([a], axis=0, inplace=True) - The first argument a takes row number or numbers separated by commas. - The second argument takes axis of 0 meaning row. In this case, we are dropping a row. An axis of 1 means column. - The third argument in place is set to true meaning the changes will be saved back in the original data frame. The vice versa is true. Using the three steps above, the figure below gives a hint on what screen sizes need cleaning. Some errors may not be seen and corrected since the data frame is large. For this reason, a general approach is needed for correction to avoid compromise on accuracy. To do this in a few lines of code, removing outliers would help. To go about this, step VI of the article would be of great assistance. The final step after all the necessary cleaning is to store the clean data in another CSV. The code below does just that. tvs.to_csv(r'Path\pigiame-cleaned.csv', index = False, header=True) - Replace the ‘path’ in the code above with the actual path you wish to store the clean data. Most preferably in the same path as this script. After all, is done, the next and last article in this series () will cement your understanding of data science by teaching you machine learning using linear regression models.
https://developers.decoded.africa/index.php/2020/10/13/data-science-project-part-2/
CC-MAIN-2021-10
refinedweb
2,131
58.69
Python ORM style interface to Amazon (AWS) DynamoDB using Schematics or Marshmallow for Schema validation Project description DynamoDB + Marshmallow == Dynamallow This package is a work in progress – Feedback / Suggestions / Etc welcomed! Two awesome things, better together! Dynamallow is a Python library that provides integration between the Boto v3 DynamoDB API and Marshmallow. Together they provide a simple, ORM inspired, interface to the DynamoDB service with a fully defined, strongly typed schema. from dynamallow import MarshModel from marshmallow import fields class Book(MarshModel): class Table: name = 'prod-books' hash_key = 'isbn' read = 25 write = 5 class Schema: isbn = fields.String(validate=validate_isbn) title = fields.String() author = fields.String() publisher = fields.String() year = fields.Number() # Store new documents directly from dictionaries Book.put({ "isbn": "12345678910", "title": "Foo", "author": "Mr. Bar", "publisher": "Publishorama" }) # Work with the classes as objects # You can pass attributes from the schema to the constructor foo = Book(isbn="12345678910", title="Foo", author="Mr. Bar", publisher="Publishorama") foo.save() # Or assign attributes foo = Book() foo.isbn = "12345678910" foo.title = "Foo" foo.author = "Mr. Bar" foo.publisher = "Publishorama" foo.save() # In all cases they go through Schema validation, calls to # .put or .save can result in ValidationError being raised. # You can then fetch, query and scan your tables. # Get on the hash key, and/or range key Book.get(isbn="12345678910") # Query based on the keys Book.query(isbn__begins_with="12345") # Scan based on attributes Book.scan(author="Mr. Bar") Book.scan(author__ne="Mr. Bar") Documentation Full documentation can be found online at: TODO - Indexes – Currently there is no support for indexes. - Schema Migrations - Partial updates on save() Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/dynamallow/
CC-MAIN-2018-22
refinedweb
292
52.97
If you’re new to Kafka Streams, here’s a Kafka Streams Tutorial with Scala tutorial which may help jumpstart your efforts. My plan is to keep updating the sample project, so let me know if you would like to see anything in particular with Kafka Streams with Scala. In this example, the intention is to 1) provide an SBT project you can pull, build and run 2) describe the interesting lines in the source code. The project is available to clone at Kafka Streams Assumptions This example assumes you’ve already downloaded Open Source or Confluent Kafka. It’s run on a Mac in a bash shell, so translate as necessary. The screencast below also assumes some familiarity with IntelliJ. Kafka Streams Tutorial with Scala Quick Start Let’s run the example first and then describe it in a bit more detail. 1. Start up Zookeeper <KAFKA_HOME>/bin/zookeeper-server-start ./etc/kafka/zookeeper.properties For example ~/dev/confluent-5.0.0/bin/zookeeper-server-start ./etc/kafka/zookeeper.properties 2. Start Kafka <KAFKA_HOME>/bin/kafka-server-start ./etc/kafka/server.properties 3. Create a topic <KAFKA_HOME>/bin/kafka-topics --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic text_lines 4. Create some sample content echo -e "doo dooey do dodah\ndoo dooey do dodah\ndoo dooey do dodah" > words.txt 5. Send the content to a Kafka topic cat words.txt | ./bin/kafka-console-producer --broker-list localhost:9092 --topic text_lines 6. Run it like you mean it. I mean put some real effort into it now. In screencast (below), I run it from IntelliJ, but no one tells you what to do. You do it the way you want to… in SBT or via `kafka-run-class` 7. Verify the output like you just don’t care. Yeah. bin/kafka-console-consumer --bootstrap-server localhost:9092 \ --topic word_count_results \ - Kafka Streams ScreenCast If the steps above left you feeling somewhat unsatisfied and putting you in a wanting-more kind of groove, a screencast is next. Let’s run through the steps above in the following Kafka Streams Scala with IntelliJ example. Prepare yourself. Kafka Streams So, why Kafka Streams? My first thought was it looks like Apache Spark. The code itself doesn’t really offer me any compelling reason to switch. But it is cool that Kafka Streams apps can be packaged, deployed, etc. without a need for a separate processing cluster. Also, it was nice to be able to simply run in a debugger without any setup ceremony required when running cluster based code like Spark. I’m intrigued by the idea of being able to scale out by adding more instances of the app. In other words, this example could horizontally scale out by simply running more than one instance of `WordCount`. Maybe I’ll explore that in a later post. Kafka Streams Tutorial with Scala Source Code Breakout When I started exploring Kafka Streams, there were two areas of the Scala code that stood out: the SerDes import and the use of KTable vs KStreams. Kafka SerDes with Scala This sample utilizes implicit parameter support in Scala. This makes the code easier to read and more concise. As shown in the above screencast, the ramifications of not importing are shown. This is part of the Scala library which we set as a dependency in the SBT build.sbt file. Serdes._ will bring `Grouped`, `Produced`, `Consumed` and `Joined` instances into scope. import Serdes._ KTable and KStreams The second portion of the Scala Kafka Streams code that stood out was the use of KTable and KStream. I wondered what’s the difference between KStreams vs KTable? Why would I use one vs the other? KStreams are useful when you wish to consume records as independent, append-only inserts. Think of records such as page views or in this case, individual words in text. Each word, regardless of past or future, can be thought of as an insert. KStreams has operators that should look familiar to functional combinators in Apache Spark Transformations such as map, filter, etc. KTable, on the other hand, represents each data record as an update rather than an insert. In our example, we want an update on the count of words. If a word has been previously counted to 2 and it appears again, we want to update the count to 3. KTable operators will look familiar to SQL constructs… groupBy various Joins, etc. ——- References For all Kafka tutorials or for more on Kafka Streams, in particular, check out more Kafka Streams tutorials Kafka Streams with Scala post image credit
https://supergloo.com/kafka-streams/kafka-streams-scala-example/
CC-MAIN-2019-30
refinedweb
769
65.01
I can see how this makes sense for future compatibility with distributed systems across a variety of RDBMS, although I'm not convinced it's more efficient for single nodes (e.g., auto-incrementing fields do not require round trips). Thanks for the reply! Just wanted to know while porting a bulk importer for 584. Advertising - Blake On Tue, Feb 13, 2018 at 12:15 PM, Sebastian Schaffert < sebastian.schaff...@gmail.com> wrote: > Hi Blake, > > Auto-increment requires querying the database for the next sequence number > (or the last given ID, depending on the database you use), and that's > adding another database roundtrip. Snowflake is purely in code, very fast > to compute, and safe even in distributed setups. > > Is it causing problems? > > Sebastian > > Blake Regalia <blake.rega...@gmail.com> schrieb am Di., 13. Feb. 2018, > 21:11: > >> What was the justification for using the 'snowflake' bigint type for the >> id fields on nodes, triples and namespaces? >> >> >> - Blake >> >
https://www.mail-archive.com/users@marmotta.apache.org/msg00660.html
CC-MAIN-2018-22
refinedweb
158
66.64
Convolutional Neural Networks Explained: Using PyTorch to Understand CNNs In the present era, machines have successfully achieved 99% accuracy in understanding and identifying features and objects in images. We see this daily — smartphones recognizing faces in the camera; the ability to search particular photos with Google Images; scanning text from barcodes or book. All of this is possible thanks to the convolutional neural network (CNN), a specific type of neural network also known as convnet. If you are a deep learning enthusiast, you've probably already heard about convolutional neural networks, maybe you've even developed a few image classifiers yourself. Modern deep-learning frameworks like Tensorflow and PyTorch make it easy to teach machines about images, however, there are still questions: How does data pass through artificial layers of a neural network? How can a computer learn from it? One way to better explain a convolutional neural network is to use PyTorch. So let's deep dive into CNNs by visualizing an image through every layer. CONVOLUTIONAL NEURAL NETWORKS Explained What Is a Convolutional Neural Network? Before getting started with convolutional neural networks, it's important to understand the workings of a neural network. Neural networks imitate how the human brain solves complex problems and finds patterns in a given set of data. Over the past few years, neural networks have engulfed many machine learning and computer vision algorithms. The basic model of a neural network consists of neurons organized in different layers. Every neural network has an input and an output layer, with many hidden layers augmented to it based on the complexity of the problem. Once the data is passed through these layers, the neurons learn and identify patterns. This representation of a neural network is called a model. Once the model is trained, we ask the network to make predictions based on the test data. If you are new to neural networks, this article on deep learning with Python is a great place to start. CNN, on the other hand, is a special type of neural network which works exceptionally well on images. Proposed by Yan LeCun in 1998, convolutional neural networks can identify the number present in a given input image. Other applications using CNNs include speech recognition, image segmentation and text processing. Before convolutional neural networks, multilayer perceptrons (MLP) were used in building image classifiers. Image classification refers to the task of extracting information classes from a multi-band raster image. Multilayer perceptrons take more time and space for finding information in pictures as every input feature needs to be connected with every neuron in the next layer. CNNs overtook MLPs by using a concept called local connectivity, which involves connecting each neuron to only a local region of the input volume. This minimizes the number of parameters by allowing different parts of the network to specialize in high-level features like a texture or a repeating pattern. Getting confused? No worries. Let’s compare how the images are sent through multilayer perceptrons and convolutional neural networks for a better understanding. COMPARING MLPS AND CNNS Considering an MNIST dataset, the total number of entries to the input layer for a multilayer perceptron will be 784 as the input image is of size 28x28=784. The network should be able to predict the number in the given input image, which means the output might belong to any of the following classes ranging from 0–9 (1, 2, 3, 4, 5, 6, 7, 8, 9). In the output layer, we return the class scores, say if the given input is an image having the number “3," then in the output layer the corresponding neuron “3” has a higher class score in comparison to the other neurons. But how many hidden layers do we need to include and how many neurons should be there in each one? Here is an example of a coded MLP: The above code snippet is implemented using a framework called Keras (ignore the syntax for now). It tells us there are 512 neurons in the first hidden layer, which are connected to the input layer of shape 784. The hidden layer is followed by a dropout layer which overcomes the problem of overfitting. The 0.2 indicates there is a 20% probability of not considering the neurons right after the first hidden layer. Again, we added the second hidden layer with the same number of neurons as in the first hidden layer (512), followed by another dropout layer. Finally, we end this set of layers with an output layer comprising 10 classes. This class which has the highest value would be the number predicted by the model. This is how the multilayer network looks like after all the layers are defined. One disadvantage with this multilayer perceptron is that the connections are complete (fully connected) for the network to learn, which takes more time and space. MLP’s only accept vectors as inputs. Convolutions don’t use fully connected layers, but sparsely connected layers, that is, they accept matrices as inputs, an advantage over MLPs. The input features are connected to local coded nodes. In MLP, every node is responsible for gaining an understanding of the complete picture. In CNNs, we disintegrate the image into regions (small local areas of pixels). Each hidden node has to report to the output layer, where the output layer combines the received data to find patterns. The image below shows how the layers are connected locally. Before we can understand how CNNs find information in the pictures, we need to understand how the features are extracted. Convolutional neural networks use different layers and each layer saves the features in the image. For example, consider a picture of a dog. Whenever the network needs to classify a dog, it should identify all the features — eyes, ears, tongue, legs, etc. — and these features are broken down and recognized in the local layers of the network using filters and kernels. HOW DO COMPUTERS LOOK AT YOUR IMAGE? Unlike human beings, who understand images by taking snapshots with the eye, computers use a set of pixel values between 0 to 255 to understand a picture. A computer looks at these pixel values and comprehends them. At first glance, it doesn’t know the objects or the colors, it just recognizes pixel values, which is all the image is for a computer. After analyzing the pixel values, the computer slowly begins to understand if the image is grayscale or color. It knows the difference because grayscale images have only one channel since each pixel represents the intensity of one color. Zero indicates black, and 255 means white, the other variations of black and white, i.e., gray lies in between. Color images, on the other hand, have three channels — red, green and blue. These represent the intensities of three colors (a 3D matrix), and when the values are simultaneously varied, it produces a gives a big set of colors! After figuring out the color properties, a computer recognizes the curves and contours of objects in an image. This proces can be explored in a convolutional neural network using PyTorch to load the dataset and apply filters to images. Below is the code snippet. (Find the code on GitHub here) # Load the libraries import torch import numpy as np from torchvision import datasets import torchvision.transforms as transforms # Set the parameters num_workers = 0 batch_size = 20 # Converting the Images to tensors using Transforms transform = transforms.ToTensor() train_data = datasets.MNIST(root='data', train=True, download=True, transform=transform) test_data = datasets.MNIST(root='data', train=False, download=True, transform=transform) # Loading the Data train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers) test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers) import matplotlib.pyplot as plt %matplotlib inline dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() # Peeking into dataset fig = plt.figure(figsize=(25, 4)) for image in np.arange(20): ax = fig.add_subplot(2, 20/2, image+1, xticks=[], yticks=[]) ax.imshow(np.squeeze(images[image]), cmap='gray') ax.set_title(str(labels[image].item())) Now let’s see how a single image is fed into the neural network. (Find the code on GitHub here) img = np.squeeze(images[7]) fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(img, cmap='gray') width, height = img.shape thresh = img.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if img[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), color='white' if img[x][y]<thresh else 'black') This is how the number "3" is broken down into pixels. Out of a set of hand-written digits, "3" is randomly chosen wherein the pixel values are shown. In here, ToTensor() normalizes the actual pixel values (0–255) and restricts them to range from 0 to 1. Why? Because, it makes the computations in the later sections easier, either in interpreting the images or finding the common patterns existing in them. BUILDING YOUR OWN FILTER In convolutional neural networks, the pixel information in an image is filtered. Why do we need a filter at all? Much like a child, a computer needs to go through the learning process of understanding images. Thankfully, this doesn't take years to do! A computer does this by learning from scratch and then proceeding its way to the whole. Therefore, a network must initially know all the crude parts in an image like the edges, the contours, and the other low-level features. Once these are detected, the computer can then tackle more complex functions. In a nutshell, low-level features must first be extracted, then the middle-level features, followed by the high-level ones. Filters provide a way of extracting that information. The low-level features can be extracted with a particular filter, which is also a set of pixel values, similar to an image. It can be understood as the weights which connect layers in a CNN. These weights or filters are multiplied with the inputs to arrive at the intermediate images, which depict the partial understanding of the image by a computer. Later, these byproducts are then multiplied with a few more filters to expand the view. This process, along with the detection of features, continues until the computer understands what it's looking at. There are a lot of filters you can use depending on what you need to do. You might want to blur, sharpen, darken, do edge detection, etc. — all are filters. Let’s look at a few code snippets to understand the functionalities of filters. This is how the image looks once the filter is applied. In this case, we’ve used a Sobel filter. THE COMPLETE CNNS So far we've seen how filters are used to extract features from images, but to complete the entire convolutional neural network we need to understand the layers we use to design it. The layers used in CNNs are called: - Convolutional layer - Pooling layer - Fully connected layer Using these three layers, a convolutional image classifier looks like this: Now let’s see what each layer does: Convolutional Layer — The convolution layer (CONV) uses filters that perform convolution operations while scanning the input image with respect to its dimensions. Its hyperparameters include the filter size, which can be 2x2, 3x3, 4x4, 5x5 (but not restricted to these alone), and stride (S). The resulting output (O) is called the feature map or activation map and has all the features computed using the input layers and filters. The image below depicts the generation of feature maps when convolution is applied: Pooling Layer — The pooling layer (POOL) is used for downsampling of the features and is typically applied after a convolution layer. The two types of pooling operations are called max and average pooling, where the maximum and average value of features is taken, respectively. Below, depicts the working of pooling operations: Fully Connected Layers — The fully connected layer (FC) operates on a flattened input where each input is connected to all the neurons. These are usually used at the end of the network to connect the hidden layers to the output layer, which helps in optimizing the class scores. VISUALIZING CNNS IN PYTORCH Now that we have a better understanding of how CNNs function, let’s now implement one using Facebook’s PyTorch framework. Step 1: Load an input image that should be sent through the network. We'll use Numpy and OpenCV. (Find the code on GitHub here) import cv2 import matplotlib.pyplot as plt %matplotlib inline img_path = 'dog.jpg' bgr_img = cv2.imread(img_path) gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY) # Normalise gray_img = gray_img.astype("float32")/255 plt.imshow(gray_img, cmap='gray') plt.show() Step 2: Visualize the filters to get a better picture of which ones we will be using. (View the code on GitHub here) import numpy as np filter_vals = np.array([ [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1] ]) print('Filter shape: ', filter_vals.shape) # Defining the Filters filter_1 = filter_vals filter_2 = -filter_1 filter_3 = filter_1.T filter_4 = -filter_3 filters = np.array([filter_1, filter_2, filter_3, filter_4]) # Check the Filters fig = plt.figure(figsize=(10, 5)) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) width, height = filters[i].shape for x in range(width): for y in range(height): ax.annotate(str(filters[i][x][y]), xy=(y,x), color='white' if filters[i][x][y]<0 else 'black') Step 3: Define the CNN. This CNN has a convolutional layer and a max pool layer, and the weights are initialized using the filters depicted above: (View the code on GitHub here) import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self, weight): super(Net, self).__init__() # initializes the weights of the convolutional layer to be the weights of the 4 defined filters k_height, k_width = weight.shape[2:] # assumes there are 4 grayscale filters self.conv = nn.Conv2d(1, 4, kernel_size=(k_height, k_width), bias=False) # initializes the weights of the convolutional layer self.conv.weight = torch.nn.Parameter(weight) # define a pooling layer self.pool = nn.MaxPool2d(2, 2) def forward(self, x): # calculates the output of a convolutional layer # pre- and post-activation conv_x = self.conv(x) activated_x = F.relu(conv_x) # applies pooling layer pooled_x = self.pool(activated_x) # returns all layers return conv_x, activated_x, pooled_x # instantiate the model and set the weights weight = torch.from_numpy(filters).unsqueeze(1).type(torch.FloatTensor) model = Net(weight) # print out the layer in the network print(model) Net( (conv): Conv2d(1, 4, kernel_size=(4, 4), stride=(1, 1), bias=False) (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) ) Step 4: Visualize the filters. Here is a quick glance at the filters being used. (View the code on GitHub here) def viz_layer(layer, n_filters= 4): fig = plt.figure(figsize=(20, 20)) for i in range(n_filters): ax = fig.add_subplot(1, n_filters, i+1) ax.imshow(np.squeeze(layer[0,i].data.numpy()), cmap='gray') ax.set_title('Output %s' % str(i+1)) fig = plt.figure(figsize=(12, 6)) fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05) for i in range(4): ax = fig.add_subplot(1, 4, i+1, xticks=[], yticks=[]) ax.imshow(filters[i], cmap='gray') ax.set_title('Filter %s' % str(i+1)) gray_img_tensor = torch.from_numpy(gray_img).unsqueeze(0).unsqueeze(1) Filters: Step 5: Filter outputs across the layers. Images that are outputted in the CONV and POOL layer are shown below. viz_layer(activated_layer) viz_layer(pooled_layer) Conv Layers Pooling Layers References : CS230 CNNs. Find the code used for this article here.
https://builtin.com/data-science/convolutional-neural-networks-explained
CC-MAIN-2021-04
refinedweb
2,637
57.27
Theodore Ts'o wrote:>metadata changes.> >Do you mean like it does with every file create?> >>>index on is semi-structed data.>No, my assumption is that structured data is a special case of semi-structured data, and should be modeled that way.>>In addition, even for text-based files, in the future, files will very>likely not be straight ASCII, but some kind of rich text based format>with formatting, unicode, etc.>Formatting does not make text table structured.> And even general, unstructured>text-based indexing is hard enough that putting that into the kernel>is just as bad as putting an SQL optimizer into the kernel.>Well, since I don't think that SQL belongs in the filesystem, and I think that text indexing should be done by users choosing how to index their text, including choosing whether to use an automatic indexer or do it by hand, and I think that the automatic indexer probably belongs in user space (I could be wrong, but I would at least choose to do version 1 of such a thing in user space, perhaps using a language other than C), I have to say that we are agreeing here. Surely it is an accident, but oh well.;-)> That I>would claim would have to be done in userspace, as part of the>overhead when OpenOffice saves the file. (Note that some of the>Linux-based office suites store files as gzip'ed XML files, which>again argues that putting it in the kernel is insane --- why should we>compress the file, only to have the kernel uncompress it and then>re-parse the XML just so they can index it? Much better to have>OpenOffice do the indexing while it has the uncompressed, parsed out>text tree in memory. And if the indexes need to be updated in>userspace, then life is much, much, much simpler if the lookups are>also done in userspace --- especially when complex SQL query>optimizations may be required.)> >Well I agree.You are missing my argument. I am saying that the indexes and name space belong in the kernel, not that the auto-indexer belongs in the kernel.> >>>which requires that it be in the kernel. Given that indexing happens>rarely (i.e., only when a file is saved), the same arguments simply>don't apply. If you consider how often a user is going to ask the>question, "Give me a list of all photographs taken between June 10,>1993 and July 24, 1996 which contains Mary Schmidt as a subject and>whose resolution is at least 150 dpi",>uh, all the time, if there is a namespace that lets him. How often do you use google? How often do you memorize the primary key of an object in a relational database, and use only that versus how often do you do a richer query?> it definitely demonstrates why>this doesn't need to be in the kernel.>>If you consider the amount of data that needs to be shovelled back and>forth between the kernel's network device driver to a userspace>networking stack and then back down into the kernel to the socket>layer when processing a TCP connection over a 10 gigabyte Ethernet>link, it's clear why it has to be in the kernel. >> When you consider>how much data needs to be referenced when doing indexing, and in fact>that it may exist in uncompressed form only in the userspace>application, you'll see why it indeed it's better to do it in userspace.>>The bottom line is that if a case can be made that some portion of the>functionality required by WinFS needs to be in the kernel, and in the>filesystem layer specifically, I'm all in favor of it. But it has to>be justified. To date, I haven't seen a justification for why the>database processing aspect of things needs to be in the kernel.>> - Ted>>> >In general, arguments over whether functionality belongs in the kernel or a userspace library are not as easy as you tend to suggest. I think you are a bit inclined to assume that what Unix does today is the right thing for 2006. The kernel is going to grow at probably roughly the same rate that computer horsepower grows, and the 30 year trend of putting more and more into the kernel will continue.Most filesystem namespace functionality belongs in the kernel because subnames tend to invoke the functionality of other subnames when one creates a richly compounding filesystem name space. There are however exceptions to this. I would put directory lookup in the kernel. I would put vicinity set intersection in the kernel. I would put set difference in the kernel. I would put set union in the kernel. I would put inheritance in the kernel. I would generally continue to put namei in the kernel. Maybe macro expansion belongs in user space libraries, I haven't thought enough about it to say. Probably the main reason I don't want the auto-indexer in the kernel is irrational: I don't want to design it, I want to see a lot of experiments, and I think the psychological barriers to entry are lower for user space experiments. Other valid reasons might be that string processing tools are richer in user space, and sys_reiser4() will provide efficient batch operations that will overcome most of the pain of context switches to the kernel for each index update.-- Hans-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2003/10/30/123
CC-MAIN-2017-43
refinedweb
950
59.64
Atoms and calculators¶ ASE allows atomistic calculations to be scripted with different computational codes. In this introductory exercise, we go through the basic concepts and workflow of ASE and will eventually calculate the binding curve of N2. These tutorials often use the electronic structure code GPAW. They can be completed just as well using other supported codes, subject to minor adjustments. Python¶ In ASE, calculations are performed by writing and running Python scripts. A very short primer on Python can be found in the ASE documentation. If you are new to Python it would be wise to look through this to understand the basic syntax, datatypes, and things like imports. Or you can just wing it — we won’t judge. Atoms¶ Let’s set up a molecule and run a DFT calculation. We can create simple molecules by manually typing the chemical symbols and a guess for the atomic positions in Ångström. For example N2: from ase import Atoms atoms = Atoms('N2', positions=[[0, 0, -1], [0, 0, 1]]) Just in case we made a mistake, we should visualize our molecule using the ASE GUI: from ase.visualize import view view(atoms) Equivalently we can save the atoms in some format, often ASE’s own trajectory format: from ase.io import write write('myatoms.traj', atoms) Then run the GUI from a terminal: $ ase gui myatoms.traj ASE supports quite a few different formats. For the full list, run: $ ase info --formats Although we won’t be using all the ASE commands any time soon, feel free to get an overview: $ ase --help Exercise Write a script which sets up and saves an N2 molecule, then visualize it. Calculators¶ Next let us perform an electronic structure calculation. ASE uses calculators to perform calculations. Calculators are abstract interfaces to different backends which do the actual computation. Normally, calculators work by calling an external electronic structure code or force field code. To run a calculation, we must first create a calculator and then attach it to the Atoms object. Here we use GPAW and set a few calculation parameters as well: from gpaw import GPAW calc = GPAW(mode='lcao', basis='dzp', txt='gpaw.txt', xc='LDA') atoms.calc = calc Different electronic structure codes have different input parameters. GPAW can use real-space grids ( mode='fd'), planewaves ( mode='pw'), or localized atomic orbitals ( mode='lcao') to represent the wavefunctions. Here we have asked for the faster but less accurate LCAO mode, together with the standard double-zeta polarized basis set ( 'dzp'). GPAW and many other codes require a unit cell (or simulation box) as well. Hence we center the atoms within a box, leaving 3 Å of empty space around each atom: atoms.center(vacuum=3.0) print(atoms) The printout will show the simulation box (or cell) coordinates, and the box can also be seen in the GUI. Once the Atoms have a calculator with appropriate parameters, we can do things like calculating energies and forces: e = atoms.get_potential_energy() print('Energy', e) f = atoms.get_forces() print('Forces') print(f) This will give us the energy in eV and the forces in eV/Å. (ASE also provides atoms.get_kinetic_energy(), referring to the kinetic energy of the nuclei if they are moving. In DFT calculations, we normally just want the Kohn–Sham ground state energy which is the “potential” energy as provided by the calculator.) Calling get_potential_energy() or get_forces() triggers a selfconsistent calculation and gives us a lot of output text. Inspect the gpaw.txt file. You can review the text file to see what computational parameters were chosen. Note how the get_forces() call did not actually trigger a new calculation — the forces were evaluated from the ground state that was already calculated, so we only ran one calculation. Binding curve¶ The strong point of ASE is that things are scriptable. atoms.positions is a numpy array with the atomic positions: print(atoms.positions) We can move the atoms by adding or assigning other values into some of the array elements. Then we can trigger a new calculation by calling atoms.get_potential_energy() or atoms.get_forces() again. Exercise Move one of the atoms so you trigger two calculations in one script. This way we can implement any series of calculations. When running multiple calculations, we often want to write them into a file. We can use the standard trajectory format to write multiple calculations (atoms and energy) like this: from ase.io.trajectory import Trajectory traj = Trajectory('mytrajectory.traj', 'w') ... traj.write(atoms) Exercise Write a loop, displacing one of the atoms in small steps to trace out a binding energy curve \(E(d)\) around the equilibrium distance. Save each step to a trajectory and visualize. What is the equilibrium distance? Be careful that the atoms don’t move too close to the edge of the simulation box (or the electrons will squeeze against the box, increasing energy and/or crashing the calculation). Note The binding will be much too strong because our calculations are spin-paired, and the atoms would polarise as they move apart. In case we forgot to write the trajectory, we can also run ASE GUI on the gpaw.txt file although its printed precision is limited. Although the GUI will plot the energy curve for us, publication quality plots usually require some manual tinkering. ASE provides two functions to read trajectories or other files: - ase.io.read()reads and returns the last image, or possibly a list of images if the indexkeyword is also specified. - ase.io.iread()reads multiple images, one at a time. Use ase.io.iread() to read the images back in, e.g.: for atoms in iread('mytrajectory.traj'): print(atoms) Exercise Plot the binding curve (energy as a function of distance) with matplotlib. You will need to collect the energies and the distances when looping over the trajectory. The atoms already have the energy. Hence, calling atoms.get_potential_energy() will simply retrieve the energy without calculating anything. Optional exercise To get a more correct binding energy, set up an isolated N atom and calculate its energy. Then calculate the molecular atomisation energy \(E_{\mathrm{atomisation}} = E[\mathrm N_2] - 2 E[\mathrm N]\) of the N2 molecule. You can use atoms.set_initial_magnetic_moments([3]) before triggering the calculation to tell GPAW that your atom is spin polarized. Solutions¶ from ase import Atoms from ase.io import Trajectory from gpaw import GPAW atoms = Atoms('N2', positions=[[0, 0, -1], [0, 0, 1]]) atoms.center(vacuum=3.0) calc = GPAW(mode='lcao', basis='dzp', txt='gpaw.txt') atoms.calc = calc traj = Trajectory('binding_curve.traj', 'w') step = 0.05 nsteps = int(3 / step) for i in range(nsteps): d = 0.5 + i * step atoms.positions[1, 2] = atoms.positions[0, 2] + d atoms.center(vacuum=3.0) e = atoms.get_potential_energy() f = atoms.get_forces() print('distance, energy', d, e) print('force', f) traj.write(atoms) import matplotlib.pyplot as plt from ase.io import iread energies = [] distances = [] for atoms in iread('binding_curve.traj'): energies.append(atoms.get_potential_energy()) distances.append(atoms.positions[1, 2] - atoms.positions[0, 2]) ax = plt.gca() ax.plot(distances, energies) ax.set_xlabel('Distance [Å]') ax.set_ylabel('Total energy [eV]') plt.show() from ase import Atoms from gpaw import GPAW atoms = Atoms('N') atoms.center(vacuum=3.0) atoms.set_initial_magnetic_moments([3]) calc = GPAW(mode='lcao', basis='dzp') atoms.calc = calc atoms.get_potential_energy()
https://wiki.fysik.dtu.dk/ase/gettingstarted/tut01_molecule/molecule.html
CC-MAIN-2020-16
refinedweb
1,223
51.34
Getting Started with Dropwizard – CRUD Operations Table of Contents Dropwizard is a Java framework for building RESTful web services. In essence, it is a glue framework which bundles together popular and battle-tested Java libraries and frameworks to make it easier to start building new RESTful web services. This post explores how to implement create, read, update, delete operations (CRUD) on a resource. Last time we set out on a journey to build a simple RESTful web service with Dropwizard. The goal was to build a back-end for a hypothetical events application that would allow you to search for events based on your search criteria. It should be able to provide a list of events, add new events and modify existing ones. Make sure you read the previous post because we will be continuing were we left off. If you wish to follow along, clone the GitHub repository and check out the register-resource tag. Quick recap In the previous article we created a new Dropwizard project, added custom configuration, created a representation and a very basic resource. Because we didn’t have a data store in place, clients were only able to make a GET request to /events and receive hard-coded data. In this follow-up tutorial we’re going to expand the feature set of the application to meet the requirements we initially set. Introducing a data store This tutorial is going to cover how to implement CRUD functionality for our application. To keep things simple and not bog you down in database specifics, I’m not going to set one up. Instead we’re going to implement a very basic in-memory database backed by java.util.List. To achieve better code reuse, it’s better to depend on abstractions, which in Java terms means not depending on concrete types. We will hence declare the public API of our in-memory data store in an interface. Create a new interface in the com.mycompany.core package called EventRepository. public interface EventRepository { } We will expand this interface throughout the rest of the article, adding methods as we need them. Implementing EventRepository We have created an interface that defines the public API of EventRepository. Now we need to come up with an implementation. Note that the following class is by no means a solution that you’d deploy to production. For starters, because we’re going to store events in a list, we’re going to run into concurrency issues. The list is a shared resource which means it has to be thread safe. Since concurrency is not the topic of this article, pretend that you are the only user. The idea is not to worry about the storage of data but rather how to create methods in EventResource so we could meet the requirements we initially set. Create a new class called DummyEventRepository in com.mycompany.core package and make it implement the EventRepository interface. public class DummyEventRepository implements EventRepository { private static final String DATA_SOURCE = "dummy_data.json"; private List<Event> events; public DummyEventRepository() { try { initData(); } catch (IOException e) { throw new RuntimeException( DATA_SOURCE + " missing or is unreadable", e); } } private void initData() throws IOException { URL url = Resources.getResource(DATA_SOURCE); String json = Resources.toString(url, Charsets.UTF_8); ObjectMapper mapper = new ObjectMapper(); CollectionType type = mapper .getTypeFactory() .constructCollectionType(List.class, Event.class); events = mapper.readValue(json, type); } } When DummyEventRepository is instantiated, initData is called. This method reads a JSON file containing dummy data which will be used to populate our in-memory data store. The JSON file is read with Guava’s Resource class and is parsed with Jackson’s ObjectMapper class. Create a new JSON document called dummy_data.json and place it in src/main/resources. The following is the data I will be using. [ { "id": 1, "name": "Czech National Symphony Orchestra - I. Concert", "description": "PERFORMERS: Libor Pešek - conductor, Natalie Clein - violoncello", "location": "náměstí Republiky 5, Praha 1 - Staré Město, 110 00", "date": "2016-10-25T19:30+0200" }, { "id": 2, "name": "Salsa Festival", "description": "World class shows & performances by some of the best artists in the world.", "location": "Copenhagen", "date": "2017-05-05T17:00+0200" }, { "id": 3, "name": "National Restaurant Day", "description": "As autumn arrives the National Restaurant Day kicks off, awaiting the lovers of gastronomy for the 11th time.", "location": "Budapest, Hungary", "date": "2016-10-16T12:00+0200" }, { "id": 4, "name": "UEFA Europa League: Austria Vienna vs. Roma", "description": "Don't miss this spectacular game and get tickets to see Austria Vienna v Roma now, before they run out.", "location": "Ernst-Happel Stadion, Vienna, Austria", "date": "2016-11-03T19:00+0200" } ] EventResource, EventRepository and DummyEventRepository In the following diagram you can see the three types in action. EventResource is responsible for for handling HTTP requests. When it needs to access or modify data, it delegates this concern to an instance of EventRepository. DummyEventRepository is an implementation of EventRepository and it will act as an in-memory data store. EventResource needs a reference to an implementation of EventRepository to do its job. I don’t want to instantiate DummyEventRepository in the EventResource class directly. This would be a violation of the dependency inversion principle. The less it knows about concrete implementations of other classes the better. Therefore I added a constructor parameter to the EventResource class which can be used to inject a concrete implementation of EventRepository. private EventRepository repository; public EventResource(EventRepository repository) { this.repository = repository; } Finally, we need to wire together our object graph. In our application’s run method, get a reference to an instance of DummyEventRepository and pass it to EventResource. @Override public void run(EventsConfiguration configuration, Environment environment) { //irrelevant code not shown EventRepository repository = new DummyEventRepository(); EventResource eventResource = new EventResource(repository); environment.jersey().register(eventResource); } Retrieving all events We can start using our newly created EventRepository by refactoring the allEvents method in EventResource class. At the moment it returns a list of events which are created on the fly. But it would make more sense if it returned all events from the in-memory data store. So let’s make the required modifications to make that happen. Modify the EventRepository interface and declare a method for finding all events as well. List<Event> findAll(); Create an implementation of the method declared in the interface in the DummyEventRepository class. Returning the list of events is all you need to do for now. @Override public List<Event> findAll() { return events; } Now modify EventResource to delegate the search of all events to an implementation of EventRepository. @GET public List<Event> allEvents() { return repository.findAll(); } When running the application, instead of getting hard-coded data as we did in the previous post, you should see a list of events that are retrieved from EventRepository when visiting. In reality, you don’t want to get all the data at once. There could be thousands of records and retrieving all of them would create unnecessary overhead. In the front-end, it is reasonable to show only a small selection of events. For example, when you do a Google search, you’ll get results that are distributed among multiple pages. This act is called pagination. Although an important feature, we’re going to cover it in a future article. Retrieving a single event In a RESTful API, retrieving a single resource is usually done via its ID. For example, if we’re interested in reading the state of an event with an ID of 123, we should make a GET request to /events/123. But how can we easily access the ID without doing complex string manipulation? The solution is the @PathParam annotation. Let’s have look at how to use it in code. Add the following method to EventResource. @GET @Path("{id}") public Event event(@PathParam("id") LongParam id) { //method body shown later } First we declare that this method should respond to GET requests that include an ID in the HTTP path. Remember that at the beginning of the EventResource class we used @Path("events") to indicate that the path of the resource starts with /events. Annotating a method with the @Path annotation adds another segment to the resource path. The curly braces around the id indicate that this should be treated as a path parameter. Using the LongParam type ensures that the value of the id read from the path must be of type Long. Otherwise Dropwizard will return an HTTP 400 response. Finding an event by ID is relatively easy. Add another method to EventRepository interface. Optional<Event> findById(Long id); The method returns an Optional of type Event. I’m using Optionals to handle the possible case where the event with the given ID might not exist. The following is the implementation of this method in DummyEventRepository. @Override public Optional<Event> findById(Long id) { return events.stream().filter(e -> e.getId() == id).findFirst(); } Now let’s get back to finishing the event method in the EventResource class. Since there is a possibility that the requested event does not exist, we should be ready to return an appropriate result to the client. @GET @Path("{id}") public Event event(@PathParam("id") LongParam id) { return repository.findById(id.get()) .orElseThrow(() -> new WebApplicationException("Event not found", 404)); } Using Optionals makes it really easy and concise to handle the case where the retrieved object might be null. In this example, if the event exists, it is returned to the client. Otherwise a new WebApplicationException, a run-time exception from JavaEE, is thrown. Dropwizard takes care of handling the exception and returns an error message to the client. Creating a new Event Creating a new event is done using the HTTP POST verb. To get things rolling, let’s first write the required code to add a new event to our data store. Because we currently store records in a list, the addition of a new event is straightforward. Add a new method called save to the EventRepository interface. The repository will assign an ID to the event being saved and we want to communicate it back to the client. Therefore the return type should be set to Event. Event save(Event event); The following is an implementation of the save method which you should place in the DummyEventRepository class. @Override public Event save(Event event) { Optional<Long> maxId = events.stream() .map(Event::getId) .max(Long::compare); long nextId = maxId.map(x -> x + 1).orElse(1L); event.setId(nextId); events.add(event); return event; } As we’re trying to avoid using an actual database for demonstration purposes, we have to do some of the work ourselves that the database would otherwise do for us. For instance, when creating a new event, we don’t know it’s ID beforehand. Therefore I’m using the Streams API to find the current maximum ID value, increment it by one to get the next ID and assign it to the new event object. When there’s no events stored, a new event will get an ID of 1. Of course, databases do a much better job at generating the next value for an ID but since this little demo application is probably never going to see large amounts of data, it should be fine. Once we’re done with the saving of a new event, let’s do the required modifications in the EventRepository class. Add the following method. @POST public Event create(Event event) { return repository.save(event); } To enable Jersey to receive an HTTP POST request, all we need to do is annotate a method with @POST in our resource class. Reading the request entity is done for you as well. Adding an argument of type Event to the method declaration informs Jersey to parse the body of the request and map it to an instance of Event. Keep in mind that no validation is performed. If none of the fields in the request body match the fields in the Event class, a new instance of Event will still be created but all of its instance fields will be null (except for id which is 0L since it is a primitive type). For testing I’m going to use the curl command line utility. curl -X POST \ -d '{"name": "My Birthday", "description": "Time to celebrate!", "location": "My place", "date": "2016-10-27T19:00+0200"}' \ -H "Content-Type: application/json" The response to that command should be the following. { "id":5, "name":"My Birthday", "description":"Time to celebrate!", "location":"My place", "date":"2016-10-27T20:00+0300" } The HTTP POST method is not idempotent. This means that if you execute the same request multiple times, you’re going to create new state on the server with each request. Modifying an existing event To update an existing event, we’re going to use the HTTP PUT method. PUT is an idempotent method which means that executing the same request multiple times does not create additional state on the server. As with retrieving a single event, we’re going to need to read the event’s ID from the path using the @PathParam annotation. Before we’re going to make the required modifications in our resource class, let’s implement the event update logic. Declare an update method in EventRepository interface. Optional<Event> update(Long id, Event event); We should also communicate the updated entity back to the client. There is a possibility that the event with the given ID does not exist. Therefore I’m using Optional of type Event as the return type. To make updating an event easier, I created a new method updateExceptId that updates the name, description, location, and date of the event that it is called on to those of the one that was given to the method. The following is the resulting implementation of the update method which you should place in DummyEventRepository. @Override public Optional<Event> update(Long id, Event event) { Optional<Event> existingEvent = findById(id); existingEvent.ifPresent(e -> e.updateExceptId(event)); return existingEvent; } Next, you’ll see how to implement the method that should receive the PUT request in the EventResource class. @PUT @Path("{id}") public Event update(@PathParam("id") LongParam id, Event event) { return repository.update(id.get(), event) .orElseThrow(() -> new WebApplicationException("Event not found", 404)); } Technically there should be nothing new for you by now. When we were looking at how to retrieve a single event, we looked at how to read the ID from the path using the @PathParam annotation. Later, when we implemented the addition of a new event, you saw how Jersey is able to map the JSON body into the Event entity. Deleting an event Although we did not set it as a goal in the initial requirements, let’s look at how to delete an event. The HTTP specification defines the DELETE method which is used to delete a resource. It is an idempotent operation. First of all, I’m going to implement the deletion logic. Our repository interface is going to need an additional method. void delete(Long id); Next, we need to implement it in DummyEventRepository. @Override public void delete(Long id) { events.removeIf(e -> e.getId() == id); } Now let’s move on to implementing a REST endpoint for deleting an event. Add the following method to EventResource class. @DELETE @Path("{id}") public Response delete(@PathParam("id") LongParam id) { repository.delete(id.get()); return Response.ok().build(); } Just like with reading a single event, we’re using the @PathParam annotation to get the ID of the event from the HTTP path. But what’s different now is the return type. Since there’s no event to return, the method has a return type of Response. This way we can send back an HTTP 200 OK response with no content. Summary Congratulations! Now you should have a good understanding of what Dropwizard is about. In the previous article, we looked at how to create a new Dropwizard application and configure it. Also a quick overview of the application structure was given. In this article you learned how to implement a simple RESTful API which enables you to create, read, update, and delete events. We have almost reached our goal. With the exception of search, we have implemented all the features we initially set out to accomplish. I encourage you to play with this application and implement a feature you think is missing. Dropwizard has more advanced features we were not able to cover. For instance, every Dropwizard application has an admin interface which allows you to monitor your application using health checks. Additionally, a very important part of application development is testing. We’re going to have a look at these and much more in a future article. Learn the basics of programming with the web's most popular language - JavaScript A practical guide to leading radical innovation and growth.
https://www.sitepoint.com/tutorial-getting-started-dropwizard-crud/
CC-MAIN-2021-43
refinedweb
2,789
55.95
Shell Links A Shell link is a data object that contains information used to access another object in the Shell's namespace—that is, any object visible through Windows Explorer. The types of objects that can be accessed through Shell links include files, folders, disk drives, and printers. A Shell link allows a user or an application to access an object from anywhere in the namespace. The user or application does not need to know the current name and location of the object. - About Shell Links - Using Shell Links About Shell Links The user creates a Shell link by choosing the Create Shortcut command from an object's shortcut menu. The system automatically creates an icon for the Shell link by combining the object's icon with a small arrow (known as the system-defined link overlay icon) that appears in the lower left corner of the icon. A Shell link that has an icon is called a shortcut; however, the terms Shell link and shortcut are often used interchangeably. Typically, the user creates shortcuts to gain quick access to objects stored in subfolders or in shared folders on other computers. For example, a user can create a shortcut to a Microsoft Word document that is located in a subfolder and place the shortcut icon on the desktop. The user can then open the document by double-clicking the shortcut icon. If the document is moved or renamed after the shortcut is created, the system will attempt to update the shortcut the next time the user selects it. Applications can also create and use Shell links and shortcuts. For example, a word processing application might create a Shell link to implement a list of the most recently used documents. An application creates a Shell link by using the IShellLink interface to create a Shell link object. The application uses the IPersistFile or IPersistStream interface to store the object in a file or stream. Note You cannot use IShellLink to create a link to a URL. This overview describes the IShellLink interface and explains how to use it to create and resolve Shell links from within a Microsoft Win32-based application. Because the design of Shell links is based on the OLE Component Object Model (COM), you should be familiar with the basic concepts of COM and OLE programming before reading this overview. Link Resolution If a user creates a shortcut to an object and the name or location of the object is later changed, the system automatically takes steps to update, or resolve, the shortcut the next time the user selects it. However, if an application creates a Shell link and stores it in a stream, the system does not automatically attempt to resolve the link. The application must resolve the link by calling the IShellLink::Resolve method. When a Shell link is created, the system saves information about the link. When resolving a link—either automatically or with an IShellLink::Resolve call—the system first retrieves the path associated with the Shell link by using a pointer to the Shell link's identifier list. For more information about the identifier list, see Item Identifiers and Identifier Lists. The system searches for the associated object in that path and, if it finds the object, resolves the link. If the system cannot find the object, it calls on the Distributed Link Tracking and Object Identifiers (DLT) service, if available, to locate the object. If the DLT service is not available or cannot find the object, the system looks in the same directory for an object with the same file creation time and attributes but with a different name. This type of search resolves a link to an object that has been renamed. If the system still cannot find the object, it searches the directories, the desktop, and local volumes, looking recursively though the directory tree for an object with either the same name or creation time. If the system still does not find a match, it displays a dialog box prompting the user for a location. An application can suppress the dialog box by specifying the SLR_NO_UI value in a call to IShellLink::Resolve. Initialization of the Component Object Library Before an application can create and resolve shortcuts, it must initialize the component object library by calling the CoInitialize function. Each call to CoInitialize requires a corresponding call to the CoUninitialize function, which an application should call when it terminates. The call to CoUninitialize ensures that the application does not terminate until it has received all of its pending messages. Location-Independent Names The system provides location-independent names for Shell links to objects stored in shared folders. If the object is stored locally, the system provides the local path and file name for the object. If the object is stored remotely, the system provides a Universal Naming Convention (UNC) network resource name for the object. Because the system provides location-independent names, a Shell link can serve as a universal name for a file that can be transferred to other computers. Link Files When the user creates a shortcut to an object by choosing the Create Shortcut command from the object's shortcut menu, Windows stores the information it needs to access the object in a link file—a binary file that has the .lnk file name extension. A link file contains the following information: - The location (path) of the object referenced by the shortcut (called the corresponding object). - The working directory of the corresponding object. - The list of arguments that the system passes to the corresponding object when the IContextMenu::InvokeCommand method is activated for the shortcut. - The show command used to set the initial show state of the corresponding object. This is one of the SW_ values described in ShowWindow. - The location (path and index) of the shortcut's icon. - The shortcut's description string. - The keyboard shortcut for the shortcut. When a link file is deleted, the corresponding object is not affected. If you create a shortcut to another shortcut, the system simply copies the link file rather than creating a new link file. In this case, the shortcuts will not be independent of each other. An application can register a file name extension as a shortcut file type. If a file has a file name extension that has been registered as a shortcut file type, the system automatically adds the system-defined link overlay icon (a small arrow) to the file's icon. To register a file name extension as a shortcut file type, you must add the IsShortcut value to the registry description of the file name extension, as shown in the example below. Note that the Shell must be restarted for the overlay icon to take effect. IsShortcut has no data value. HKEY_CLASSES_ROOT .xyz (Default) = XYZApp XYZApp IsShortcut Shortcut names The shortcut's name, which is a string that appears below the Shell link icon, is actually the file name of the shortcut itself. The user can edit the description string by selecting it and entering a new string. Location of shortcuts in the namespace A shortcut can exist on the desktop or anywhere in the Shell's namespace. Similarly, the object that is associated with the shortcut can also exist anywhere in the Shell's namespace. An application can use the IShellLink::SetPath method to set the path and file name for the associated object, and the IShellLink::GetPath method to retrieve the current path and file name for the object. Shortcut working directory The working directory is the directory where the corresponding object of a shortcut loads or stores files when the user does not identify a specific directory. A link file contains the name of the working directory for the corresponding object. An application can set the name of the working directory for the corresponding object by using the IShellLink::SetWorkingDirectory method and can retrieve the name of the current working directory for the corresponding object by using the IShellLink::GetWorkingDirectory method. Shortcut command-line arguments A link file contains command-line arguments that the Shell passes to the corresponding object when the user selects the link. An application can set the command-line arguments for a shortcut by using the IShellLink::SetArguments method. It is useful to set command-line arguments when the corresponding application, such as a linker or compiler, takes special flags as arguments. An application can retrieve the command-line arguments from a shortcut by using the IShellLink::GetArguments method. Shortcut show commands When the user double-clicks a shortcut, the system starts the application associated with the corresponding object and sets the initial show state of the application based on the show command specified by the shortcut. The show command can be any of the SW_ values included in the description of the ShowWindow function. An application can set the show command for a shortcut by using the IShellLink::SetShowCmd method and can retrieve the current show command by using the IShellLink::GetShowCmd method. Shortcut icons Like other Shell objects, a shortcut has an icon. The user accesses the object associated with a shortcut by double-clicking the shortcut's icon. When the system creates an icon for a shortcut, it uses the bitmap of the corresponding object and adds the system-defined link overlay icon (a small arrow) to the lower left corner. An application can set the location (path and index) of a shortcut's icon by using the IShellLink::SetIconLocation method. An application can retrieve this location by using the IShellLink::GetIconLocation method. Shortcut descriptions Shortcuts have descriptions, but the user never sees them. An application can use a description to store any text information. Descriptions are set using the IShellLink::SetDescription method and retrieved using the IShellLink::GetDescription method. Shortcut Keyboard Shortcuts A shortcut object can have a keyboard shortcut associated with it. Keyboard shortcuts allow a user to press a combination of keys to activate a shortcut. An application can set the keyboard shortcut for a shortcut by using the IShellLink::SetHotkey method and can retrieve the current keyboard shortcut by using the IShellLink::GetHotkey method. Item Identifiers and Identifier Lists The Shell uses object identifiers within the Shell's namespace. All objects visible in the Shell (files, directories, servers, workgroups, and so on) have unique identifiers among the objects within their parent folder. These identifiers are called item identifiers, and they have the SHITEMID data type as defined in the Shtypes.h header file. An item identifier is a variable-length byte stream that contains information that identifies an object within a folder. Only the creator of an item identifier knows the content and format of the identifier. The only part of an item identifier that the Shell uses is the first two bytes, which specify the size of the identifier. Each parent folder has its own item identifier that identifies it within its own parent folder. Thus, any Shell object can be uniquely identified by a list of item identifiers. A parent folder keeps a list of identifiers for the items it contains. The list has the ITEMIDLIST data type. Item identifier lists are allocated by the Shell and may be passed across Shell interfaces, such as IShellFolder. It is important to remember that each identifier in an item identifier list is only meaningful within the context of its parent folder. An application can set a shortcut's item identifier list by using the IShellLink::SetIDList method. This method is useful when setting a shortcut to an object that is not a file, such as a printer or disk drive. An application can retrieve a shortcut's item identifier list by using the IShellLink::GetIDList method. Using Shell Links This section contains examples that demonstrate how to create and resolve shortcuts from within a Win32-based application. This section assumes you are familiar with Win32, C++, and OLE COM programming. Creating a Shortcut and a Folder Shortcut to a File The CreateLink sample function in the following example creates a shortcut. The parameters include a pointer to the name of the file to link to, a pointer to the name of the shortcut that you are creating, and a pointer to the description of the link. The description consists of the string, "Shortcut to file name," where file name is the name of the file to link to. To create a folder shortcut using the CreateLink sample function, call CoCreateInstance using CLSID_FolderShortcut, instead of CLSID_ShellLink (CLSID_FolderShortcut supports IShellLink). All other code remains the same. Because CreateLink calls the CoCreateInstance function, it is assumed that the CoInitialize function has already been called. CreateLink uses the IPersistFile interface to save the shortcut and the IShellLink interface to store the file name and description. // CreateLink - Uses the Shell's IShellLink and IPersistFile interfaces // to create and store a shortcut to the specified object. // // Returns the result of calling the member functions of the interfaces. // // Parameters: // lpszPathObj - Address of a buffer that contains the path of the object, // including the file name. // lpszPathLink - Address of a buffer that contains the path where the // Shell link is to be stored, including the file name. // lpszDesc - Address of a buffer that contains a description of the // Shell link, stored in the Comment field of the link // properties. #include "stdafx.h" #include "windows.h" #include "winnls.h" #include "shobjidl.h" #include "objbase.h" #include "objidl.h" #include "shlguid.h" HRESULT CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc) { HRESULT hres; IShellLink* psl; //; // Set the path to the shortcut target and add the description. psl->SetPath(lpszPathObj); psl->SetDescription(lpszDesc); // Query IShellLink for the IPersistFile interface, used for saving the // shortcut in persistent storage. hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); if (SUCCEEDED(hres)) { WCHAR wsz[MAX_PATH]; // Ensure that the string is Unicode. MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH); // Add code here to check return value from MultiByteWideChar // for success. // Save the link by calling IPersistFile::Save. hres = ppf->Save(wsz, TRUE); ppf->Release(); } psl->Release(); } return hres; Resolving a Shortcut An application may need to access and manipulate a shortcut that was previously created. This operation is referred to as resolving the shortcut. The application-defined ResolveIt function in the following example resolves a shortcut. Its parameters include a window handle, a pointer to the path of the shortcut, and the address of a buffer that receives the new path to the object. The window handle identifies the parent window for any message boxes that the Shell may need to display. For example, the Shell can display a message box if the link is on unshared media, if network problems occur, if the user needs to insert a floppy disk, and so on. The ResolveIt function calls the CoCreateInstance function and assumes that the CoInitialize function has already been called. Note that ResolveIt needs to use the IPersistFile interface to store the link information. IPersistFile is implemented by the IShellLink object. The link information must be loaded before the path information is retrieved, which is shown later in the example. Failing to load the link information causes the calls to the IShellLink::GetPath and IShellLink::GetDescription member functions to fail. // ResolveIt - Uses the Shell's IShellLink and IPersistFile interfaces // to retrieve the path and description from an existing shortcut. // // Returns the result of calling the member functions of the interfaces. // // Parameters: // hwnd - A handle to the parent window. The Shell uses this window to // display a dialog box if it needs to prompt the user for more // information while resolving the link. // lpszLinkFile - Address of a buffer that contains the path of the link, // including the file name. // lpszPath - Address of a buffer that receives the path of the link target, including the file name. // lpszDesc - Address of a buffer that receives the description of the // Shell link, stored in the Comment field of the link // properties. #include "stdafx.h" #include "windows.h" #include "shobjidl.h" #include "shlguid.h" #include "strsafe.h" HRESULT ResolveIt(HWND hwnd, LPCSTR lpszLinkFile, LPWSTR lpszPath, int iPathBufferSize) { HRESULT hres; IShellLink* psl; WCHAR szGotPath[MAX_PATH]; WCHAR szDescription[MAX_PATH]; WIN32_FIND_DATA wfd; *lpszPath = 0; // Assume failure //; // Get a pointer to the IPersistFile interface. hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf); if (SUCCEEDED(hres)) { WCHAR wsz[MAX_PATH]; // Ensure that the string is Unicode. MultiByteToWideChar(CP_ACP, 0, lpszLinkFile, -1, wsz, MAX_PATH); // Add code here to check return value from MultiByteWideChar // for success. // Load the shortcut. hres = ppf->Load(wsz, STGM_READ); if (SUCCEEDED(hres)) { // Resolve the link. hres = psl->Resolve(hwnd, 0); if (SUCCEEDED(hres)) { // Get the path to the link target. hres = psl->GetPath(szGotPath, MAX_PATH, (WIN32_FIND_DATA*)&wfd, SLGP_SHORTPATH); if (SUCCEEDED(hres)) { // Get the description of the target. hres = psl->GetDescription(szDescription, MAX_PATH); if (SUCCEEDED(hres)) { hres = StringCbCopy(lpszPath, iPathBufferSize, szGotPath); if (SUCCEEDED(hres)) { // Handle success } else { // Handle the error } } } } } // Release the pointer to the IPersistFile interface. ppf->Release(); } // Release the pointer to the IShellLink interface. psl->Release(); } return hres; } Creating a Shortcut to a Nonfile Object Creating a shortcut to a nonfile object, such as a printer, is similar to creating a shortcut to a file except that rather than setting the path to the file, you must set the identifier list to the printer. To set the identifier list, call the IShellLink::SetIDList method, specifying the address of an identifier list. Each object within the Shell's namespace has an item identifier. The Shell often concatenates item identifiers into null-terminated lists consisting of any number of item identifiers. For more information about item identifiers, see Item Identifiers and Identifier Lists. In general, if you need to set a shortcut to an item that does not have a file name, such as a printer, you will already have a pointer to the object's IShellFolder interface. IShellFolder is used to create namespace extensions. Once you have the class identifier for IShellFolder, you can call the CoCreateInstance function to retrieve the address of the interface. Then you can call the interface to enumerate the objects in the folder and retrieve the address of the item identifier for the object that you are searching for. Finally, you can use the address in a call to the IShellLink::SetIDList member function to create a shortcut to the object.
http://msdn.microsoft.com/en-us/library/windows/desktop/bb776891(v=vs.85)
CC-MAIN-2014-15
refinedweb
3,029
53.51
Hey, My company uses Aspose.Total (specifically Words, Cells, Slides, Pdf, Pdf.Kit, Network) in our software. We will be upgrading to VS2010 and .NET 4.0 soon. When will .NET 4.0 compatible versions of the above software be certified and released. Thanks in advance, Adam Hey, Hello Adam, Thanks for using our products. I am a representative from Aspose.Pdf for .NET team. I have tried using Aspose.Pdf for .NET with Visual Studio 2010 and .NET Framework 4.0 and I am sorry to inform you that its currently not supported over it. For the sake of correction, I have logged it in our issue tracking system as PDFNET-16387. We will investigate this issue in details and will keep you updated on the status of a correction. <?xml:namespace prefix = o We apologize for your inconvenience. Hi Adam, Hi Adam, I represent Aspose.Pdf.Kit for .NET and I would like to share that we need to test it with .NET Framework 4.0. The issue is logged as PDFKITNET-15844 in our issue tracking system. We’ll test it at our end and update you accordingly. We’re sorry for the inconvenience. Regards, Hi, I will reply on the behalf of Aspose.Cells for .NET product. Aspose.Cells for .NET does support .NET Framework 4.0 / VS.NET 2010 as we have already tested it and it works fine. So, you may use the product on your underlying framework. For reference, see the document: If you still find any issue using Aspose.Cells for .NET on .NET Framework 4.0, let us know. We will be happy to sort it out. Thank you. Hello, We are also looking into upgrading to VS 2010 and .Net 4.0. We use the following Aspose Components: PDF PDF.Ket Barcodes Words It looks like PDF and PDF Kit need some work before they are supported. What about Barcodes and Words? Thanks! Don Tompkins Databound Solutions Hi Don, We are working on Aspose.BarCode for .NET to make it work with VS 2010 and .NET framework 4.0. I will update you as soon as it is supported. Hi Adam, I am representative of Aspose.Slides. I have verified the working of Aspose.Slides for .NET 4.1.1 with Visual Studio 2010 with .NET framework 4.0 and found the product compatible the said development environment. Please feel free to share your issues. Thanks and Regards, Hi, Thanks for using our products. We just have released an updated version of Aspose.Pdf for .NET which is compatible with Visual Studio 2010 (supports .NET Framework 4.0 and .NET Framework 4.0 Client profile). You can access this version from here. Please try using it and in case you still face any problem or you have any further query, please feel free to contact. Thanks for your time and cooperation. Hi Adam, Please find attached the hot fix which can be used with Visual Studio 2010 and .NET Framework 4.0. Please try it at your end and see if it works well. This fix will be included in our upcoming version due at the end of this month. If you have any further questions, please do let us know. Regards, The issues you have found earlier (filed as 16387) have been fixed in this update. This message was posted using Notification2Forum from Downloads module by aspose.notifier. (2)
https://forum.aspose.com/t/visual-studio-2010-net-4-0-support-across-aspose-total/34847
CC-MAIN-2020-40
refinedweb
570
79.16
I'm trying to get a dice roller happening and I'm having some difficulty adding a loop somewhere so the program doesn't quit after one roll. I want to ask the user if they want to roll and it rolls by saying "y." I want to end the program by asking the user the same question but it ends with "n" /* Natasha Shorrock Assignmnt A6 11/07/16 */ package diceroller; import java.util.Random; import java.util.Scanner; public class DiceRoller { public static void main(String []args) { System.out.println(" Do you want to roll the dice? "); Random dice = new Random(); Scanner input = new Scanner(System.in); int faces; int result; System.out.println("Dice Roller\n"); System.out.println("How many faces does the dice have?"); faces = input.nextInt(); result = dice.nextInt(faces) + 1; System.out.println("\nThe dice rolled a " + result ); }//Dice Roller }//class DiceRoller You nedd to read the answer after the System.out.println(" Do you want to roll the dice? "); with a input.nextLine(); and loop while the input is "y" the while(condition) loop is excuted while the condition is true The while statement continually executes a block of statements while a particular condition is true. The while and do-while Statements for your exemple you can try this code : public static void main(String[] args) { Random dice = new Random(); Scanner input = new Scanner(System.in); System.out.println("Do you want to roll the dice? (y: yes / q: to quit)"); String answer = input.nextLine(); // reading the input // we check if the answer is equals to "y" to execute the loop, // if the answer is not equals to "y" the loop is not executed while ("y".equals(answer)) { System.out.println("Dice Roller"); System.out.println("How many faces does the dice have?"); int faces = input.nextInt(); int result = dice.nextInt(faces) + 1; input.nextLine(); // to read the newline character (*) System.out.println("The dice rolled a " + result); System.out.println("Do you want to roll the dice? (y: yes / q: to quit)"); answer = input.nextLine(); } } for more about the while and do-while, please visit this toturial (*) to understand the use of nextLine() after a call to nextInt() please visit Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
https://codedump.io/share/NWwTCjTwUl4n/1/i39m-trying-to-add-a-loop-into-my-dice-roller-program
CC-MAIN-2017-13
refinedweb
381
69.07
How do I select specific range of lines in Notepad++ quickly? I have a text file that has over 1M of lines and I need to delete some fragments from it, but selecting lines manually just takes too much time. For example: I need to select lines from 2000 to 12000, how to make it quick? I got a better answer. You could record a macro ( deleting for example 10 lines ) . Then run it several times . 10 1) Go to Macro > Start recording Macro > Start recording 2) hold Shift and tap Down to mark for example 10 lines . And delete them. 3) Go to Macro > Stop Recording Macro > Stop Recording Now your macro is recorded, you can save it for using in the future . 4) Go to Macro > Save Current Recording Macro... . And save it with a name . Macro > Save Current Recording Macro... 5) Move cursor to line that you want to delete lines after that.Then go to Macro > Run A Macro Multiple Times... . And select your macro and run it N times that you want. Macro > Run A Macro Multiple Times... N Just Left Click once in line 2000 .then go to line 12000 , hold Shift and Left Click again . 2000 12000 1) Left Click in line 2000 2) Go to line 12000 3) Shift + Left Click in line 12000 I had just responded with this in this similar question, but it looks like a more fitting answer for here, and I'm guessing that this Question Title would get more hits... so, I'm posting here and hoping it isn't some kind of faux pas... (perhaps it should just be a link to the other?) # File:: selectGOTO.py # A N++ Python Script to enhance line selection speed compared to mouse, cursor, page controls. # Selects text from the [ start|end ] of current line to [ end|start ] of GOTO line. # Install using:: Plugins -> Plugin Manager -> Python Script # Create script using:: Plugins -> Python Script -> New Script -> "selectGoto.py" # Add to menu:: Plugins -> Python Script -> Configuration -> [select script] [ add ] # Create shortcut:: [Restart N++] # Settings -> Shortcut Mapper -> Plugin Commands -> selectGOTO -> [modify] [ctrl]+[shift]+[g] # Simple usage: # [ctrl]+[shift]+[g] line# # Do your operation... (ie: del) from Npp import * class startAnchor: pos = 0 def selectGOTO( args ): endPos = editor.getCurrentPos() if( endPos > startAnchor.pos ): startAnchor.pos = editor.positionFromLine( editor.lineFromPosition( startAnchor.pos ) ) else: tmp = startAnchor.pos startAnchor.pos = endPos endPos = tmp endPos = editor.getLineEndPosition( editor.lineFromPosition( endPos ) ) editor.setSel( startAnchor.pos, endPos ) editor.clearCallbacks() def main(): startAnchor.pos = editor.getCurrentPos() editor.callback( selectGOTO, [SCINTILLANOTIFICATION.UPDATEUI] ) notepad.menuCommand( MENUCOMMAND.SEARCH_GOTOLINE ) main() By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 17513 times active 2 years ago
http://superuser.com/questions/405522/selecting-range-of-lines-in-notepad
CC-MAIN-2016-18
refinedweb
452
67.76
Most of ServiceStack's features are also available on .NET Core, where it's all maintained within a single code-base enabling excellent source-code compatibility to maximize existing knowledge and code-reuse and reducing portability efforts, and released within the same suite of NuGet packages, all without breaking changes to existing .NET 4.5 Customers. .NET Core - the future of .NET on Linux .NET Core enables an exciting era of .NET Web and Server App development -. .NET Core You can checkout our Deploy .NET Core with Docker to AWS ECS Guide for the details on how we've deployed the .NET Core Live Demos, but. Exceptional Code reuse Thanks to ServiceStack's high-level host agnostic API and our approach to decouple from concrete HTTP abstractions behind lightweight IRequest interfaces, ServiceStack projects enjoy near perfect code reuse, which allows the same ServiceStack Services to be able to run on ASP.NET, HttpListener SelfHosts, SOAP Endpoints, multiple MQ Hosts and .NET Core Apps. The HelloMobile Server Hosts shows an example of this where the same AppHost Configuration and WebServices implementation is used in all: - .NET 6.0 Server - ASP.NET Core running on .NET Framework - ASP.NET Web App (.NET Framework) - HttpListener Self-Host (.NET Framework) 6 6.0 Project Templates There are 11 .NET 6.0 project templates for each of ServiceStack's most popular starting templates. Each .NET 6.0 template has an equivalent .NET Framework template except for ServiceStack Sharp Apps which is itself a pre-built .NET 6.0 App that lets you develop Web Applications and HTTP APIs on-the-fly without any compilation. All .NET 6 x new command-line utility, installable from npm with: dotnet tool install --global x This makes the x .NET Core tool globally available which can be run without arguments to view all templates available: Usage That can be used to create new projects with: x new <template-name> <project-name> Example of creating a new Vue SPA project called Acme: x. : Multi-stage Docker Builds The .NET Core Apps deployed using Docker use ASP.NET Team's recommended multi-stage Docker Builds where the App is built inside an aspnetcore-build Docker container with its published output copied inside a new aspnetcore runtime Docker container: FROM mcr.microsoft.com/dotnet/core/sdk:3.1 FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS. .NET Core Web Apps .NET 6.0 is also used to enable Sharp Apps which is a new approach to dramatically simplify .NET Wep App development and provide the most productive development experience possible whilst maximizing reuse and component sharing. Web Apps let you develop dynamic websites without needing to write any C# code or perform any app builds which dramatically reduces the cognitive overhead and conceptual knowledge required for development where the only thing front-end Web developers need to know is ServiceStack #Script Syntax and what scripts are available to call. Because of #Script's high-fidelity with JavaScript, developing a Website with Templates will be instantly familiar to JavaScript devs despite calling and binding directly to .NET APIs behind the scenes. Web App Examples To illustrate the various features available we've developed a number of Web Apps examples to showcase the different kind of Apps that can easily be developed. The source code for each app is available from github.com/NetCoreWebApps. Each app runs the same unmodified Web App Binary that's also used in the Bare Web App project above. You can quickly get started by creating a Web App from the project template: dotnet-new bare-app ProjectName Run ASP.NET Core Apps on the .NET Framework A primary use-case prevented from having unified NuGet packages containing both .NET Standard and .NET Framework builds is being able to run ASP.NET Core Apps on the .NET Framework which stems from: support running ASP.NET Core Apps on the .NET Framework you can use the .Core NuGet packages which contains only the .NET Standard 2.0 builds in order to force .NET Framework projects to use .NET Standard 2.0 builds. Currently the complete list of .Core packages which contains only WARNING Ultimately support for whether a .NET Standard 2.0 library will run on the .NET Framework depends on whether external dependencies also support this scenario which as it's a more niche use-case, will be a less tested scenario Other issues from being a less popular scenario is not being able to reference the Microsoft.AspNetCore.All meta package which only supports .NET Core 2.1 projects, instead ASP.NET .NET Standard packages will need to be referenced individually. To make it as easy as possible to get started you can use the NetFrameworkCoreTemplates This will let you create an ASP.NET Core App running on the .NET Framework v4.7 with the dotnet tool: dotnet tool install --global x Then create a new project with: x new web-corefx AcmeNetFx Which can then be opened in your preferred VS.NET or Project Rider C# IDE. package and can be seen in action in the Razor Rockstars .NET Core demo. AppSelfHostBase Source-compatible Self-Host The ServiceStack.Kestrel NuGet package encapsulates .NET Core's Kestrel HTTP Server dependency behind a source-compatible AppSelfHostBase which can be used to create source-compatible Self Hosted Apps and is what enables the exact same .NET Framework Template's Integration Tests to be used in .NET Core Template's Integration Tests..UseServiceStack(new AppHost { AppSettings = new NetCoreAppSettings(Configuration) // Use **appsettings.json** and config sources });: // Create your ServiceStack Web Service with a singleton AppHost public class AppHost : AppHostBase { // Initializes your AppHost Instance, with the Service Name and assembly containing the Services public AppHost() : base("Backbone.js TODO", typeof(TodoService).Assembly) { } // location below: - - Linux / Docker / nginx / .NET Core" }); } } Scoped Dependencies In .NET Core ServiceStack is pre-configured to use a NetCoreContainerAdapter where it will also resolve any dependencies declared in your .NET Core Startup using app.ApplicationServices. One side-effect of this is that when resolving Scoped dependencies it resolves them in a Singleton scope instead of the Request Scope had they instead been resolved from context.RequestServices.GetService<T>().."); } } Register ASP.NET Core dependencies in AppHost Any dependencies registered .NET Core Startup are also available to ServiceStack but dependencies registered in ServiceStack's IOC are only visible to ServiceStack. This is due to the limitation of ASP.NET Core requiring all dependencies needing to be registered in ConfigureServices() before any App Modules are loaded and why dependencies registered in ServiceStack's AppHost Configure() are only accessible from ServiceStack and not the rest of ASP.NET Core. But in Modular Startup Apps you can override ASP.NET Core's builder.ConfigureServices(IServiceCollection) method in your AppHost Configure(IWebHostBuilder builder) to register IOC dependencies where they'll now be accessible to both ServiceStack and the rest of your ASP.NET Core App,, }); } } The IWebHostBuilder can also be used to hook into the Configure(IApplicationBuilder) to inject ASP.NET Core middleware, including ServiceStack and the AppHost itself. INFO Reason for only conditionally registering ServiceStack with if (!HasInit) is to allow other plugins (like Auth) the opportunity to precisely control where ServiceStack is registered within its preferred ASP .NET Core's pipeline This will let you drop-in your custom AppHost into a ModularStartup enabled ASP.NET Core App to enable the same "no-touch" auto-registration. "] } convenience extension methods for resolving dependencies, e.g: var foo = container.GetService<IFoo>(); ServiceStack.Logging Adapters The default. .NET Standard 2.0 Logging Providers Whilst our recommendation is to use .NET Core's Logging Abstraction, if you prefer you can avoid this abstraction and configure logging with ServiceStack directly with the logging providers below which maintains .NET Standard 2.0 versions: - ServiceStack.Logging.Serilog - ServiceStack.Logging.Slack"); Hosting ASP.NET Core Apps on Custom Path Use the PathBase property on AppHost for hosting a ServiceStack .NET Core App at a custom path, e.g:.UseServiceStack(new AppHost()); the MVC Smart Razor Pages support
https://docs.servicestack.net/netcore
CC-MAIN-2022-21
refinedweb
1,337
51.55
problems I see right off the top of my head (hey, it's early and I haven't had coffee yet!). But, you "write (to_child [1],...)" but I see nowhere where you set a value for to_child [1]. But, the biggie is this: strcat (result, &c); strcat() works with STRINGS, which in C is defined as "a byte array that ends with a binary 0". Since you don't know what is physically behind the variable "c" in memory, this is at best undefined behavior. Here's one way to do it: char *tmpP = result; // point to result string area while (read(to_child[0], &c, 1) == 1) { putchar(c); *tmp++ = c; // stuff it in "result" } *tmp = '\0'; // terminate the C string result return (result); -Keith Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial while (read(to_child[0], &c, 1) == 1) { putchar(c); strcat(result, &c); } I only see the command (cmd) I pass to execl(), and not the out put after execl() done.
https://www.experts-exchange.com/questions/21202637/C-program-for-unix-shell-forking.html
CC-MAIN-2018-30
refinedweb
192
76.66
Post Tweets With Your Raspberry Pi Raspberry Pi is famous for its great computing strength and ability to run the Linux operating system. In today’s tutorial, you’ll learn how to make your Raspberry Pi tweet. You can add extra features to this project to post tweets autonomously if any specific event occurs. Let’s get started. Required Parts You’ll need following parts to make this project. - Raspberry Pi running Raspbian OS (Any model) - USB Mouse - USB Keyboard - HDMI Compatible Monitor - HDMI Cable - USB power supply for Raspberry (5V 2A) - Working Internet Connection Create App In Twitter You need to create an app in Twitter so that Raspberry Pi can use to make tweets on your behalf. Go here to make a twitter app. The Raspberry Pi will require following parameters to make tweets: - Consumer Key (API Key) - Consumer Secret (API Secret) - Access Token - Access Token Secret You can find all these details from your app. Store Keys In Raspberry Pi In this step, you need to create a python file in your Raspberry Pi and store all the Keys and Tokens there. Create a file named keys.py in your working folder with all information in it.>IMAGE_1<< Now, save the file and go the nex step of this tutorial. Install Twython Well, what is Twython actually? Twython is the premier Python library providing an easy way to access the Twitter data. It’s been tested by companies, educational institutions and individuals alike. This amazing library will make our job a lot easier and the code much shorter. To install the Twython library, follow the given steps: sudo apt-get update sudo apt-get upgrade sudo apt-get install python-setuptools sudo easy_install pip sudo pip install twython sudo pip install requests sudo pip install requests-oauthlib pip is required to install Twython, so it’s installed in 3rd step. But if you already have pip installed, just ignore that step. Write The Python Script & Run It Open a file in your working directory in your Raspberry Pi and rename it to twitter.py. Make sure that it is in the same directory wit previously created keys.py file. Now, copy-paste the following code using any editor or IDE: import sys from twython import Twython from keys import ( consumer_key, consumer_secret, access_token, access_token_secret ) twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret ) message = "My first tweet using Rapberry Pi! Yeh!" twitter.update_status(status=message) print("Raspberry Pi successfully tweeted: %s " % message) Pretty simple, isn’t it? Actually, the Twython library performs lots of tasks behind the screen keeping the code surprisingly small. Now, save the file and open terminal in your raspberry pi. Write the following command and hit the Enter key to run this Python script: python twitter.py That’s all. Now you can see that is your Raspberry Pi is tweeting successfully.
http://www.electronics-lab.com/post-tweets-with-raspberry-pi/
CC-MAIN-2017-47
refinedweb
475
54.52
std::basic_ios::eof Returns true if the associated stream has reached end-of-file. Specifically, returns true if eofbit is set in rdstate(). Parameters (none) Return value true if an end-of-file has occurred, false otherwise. Notes This function only reports the stream state as set by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a get(), which returned the last byte of a file, eof() returns false. The next get() fails to read anything and sets the eofbit. Only then eof() returns true. In typical usage, input stream processing stops on any error; eof() and fail() are then used to distinguish between different error conditions. Example #include <iostream> #include <fstream> #include <cstdlib> int main() { std::ifstream file("test.txt"); if(!file) // operator! is used here { std::cout << "File opening failed\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for(int n; file >> n; ) { std::cout << n << ' '; } std::cout << '\n'; if (file.bad()) std::cout << "I/O error while reading\n"; else if (file.eof()) std::cout << "End of file reached successfully\n"; else if (file.fail()) std::cout << "Non-integer data encountered\n"; } See also The following table shows the value of basic_ios accessors (good(), fail(), etc.) for all possible combinations of ios_base::iostate flags:
http://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ios/eof&oldid=57604
CC-MAIN-2015-14
refinedweb
241
56.25
proj4-hs-bindings Haskell bindings for the Proj4 C dynamic library. This package is not currently in any snapshots. If you're interested in using it, we recommend adding it to Stackage Nightly. Doing so will make builds more reliable, and allow stackage.org to host generated Haddocks. Haskell bindings for the Proj.4 map projection C library. You need to have Proj.4 already installed as a shared library. Example transformations (from): import Geo.Proj4 lon0 = 22.350 * pi / 180 -- Test longitude in radians. lat0 = 40.084 * pi / 180 -- Test latitude in radians. alt0 = 2843 -- Test altitude in meters. -- | Test projection: pj = newProjection "+proj=utm +zone=34" -- | Another test (null, e.g. cylindrical) projction: pj0 = newProjection "+proj=latlong +ellps=clrk66" -- | A projection of our test longitude & latitude, using @pj: (x, y) = pjFwd pj (lon0, lat0) -- | An inverse projection from (x, y) to (longitude, latitude): (lon, lat) = pjInv pj (x, y) -- | Convert our test position from one projection to another (pj0 -> pj): (x2, y2, z2) = pjTransformPt pj0 pj (lon0, lat0, alt0) main :: IO () main = do putStrLn $ "(x, y): " ++ (show (x, y)) putStrLn $ "(lon, lat): " ++ (show (lon * 180 / pi, lat * 180 / pi)) putStrLn $ "(x, y, z): " ++ (show $ (x2, y2, z2)) return () You should see the following when you compile and run the above: (x, y): (615096.1096381239,4437953.6592040695) (lon, lat): (22.350000000000662,40.083999999999584) (x, y, z): (615096.1096381239,4437953.6592040695,2843.0)
https://www.stackage.org/package/proj4-hs-bindings
CC-MAIN-2018-22
refinedweb
233
68.16
<rant>CPAN modules failing to check for write errors</rant> kicked off a quest to see if I could apply the stuff I learned in Hacking The Op Tree For Fun And.... The following code is the result of a two weeks of hacking at perl to automatically either report ( the default - a safe choice ) or fix your code that doesn't check the result of system calls. The following snippet will automatically fix your entire program so that there are no unchecked io, file, or directory calls. It even gets into print() and printf() which are both normally impossible to override. I am posting this code because it may be a while before I release another, better version. Along the way I found that it would be easy to abstract the `compiled_program() =~ s///`-like portions of the module off and so I expect to create a Devel::Macro later so I can rewrite this as a proper perl-macro using the impending macro system. In the interim I'm thinking I may just end up really busy with other, more important stuff and instead of just letting this sit around, collecting dust I thought I'd share it and let you all at least try it out. All the user-configurable code is handled via the import() call so where the documentation isn't clear read that bit of source. See also the %CHECK_DICT for a categorized list of opcodes that can be matched. By default the module looks for everything appropriate from io, sockets, file, directory, eval, and miscellaneous categories. I had to submit a patch to B::Utils and to B::Generate to get this to work. I have included both patches as responses to this node (mostly so the code I actually want to post isn't cluttered up with these related patches). use Devel::UncheckedOps ( fix => 1, functions => [ map @$_, @Devel::UncheckedOps::CHECK_DICT{ qw( io file dir +ectory ) } ] ); print "Hello world!\n"; # Becomes # print "Hello world!\n" or die $!; [download] package Devel::UncheckedOps; use strict; use warnings FATAL => 'all'; use B qw( OPf_WANT_VOID class ); use B::Utils qw( walkallops_filtered opgrep ); use vars qw( $REPORT_CALLBACK %CHECK_DICT @CHECK_OPS @TERMINAL_OPS $VE +RSION $OPCODE_NAME $FIX_OPCODES $O_PM @QUEUED_FIXES_TO_APPLY $D +EBUG ); # %ALLOPS %OPMAP use Carp qw( carp ); $VERSION = '0.01'; # This is a largish list of stuff I think can be validated by this mod +ule. # The default list of opcodes that will be checked is defined in @CHEC +K_OPS # immediately following and normal users specify the list of ops to va +lidate # by passing in a reference to an array to the 'check' parameter of th +e use() # call. %CHECK_DICT = ( # 'write' would be a nice op to add but I do not yet kn +ow how # it works in code. io => [ qw[open close binmode dbmclose dbmopen fcntl flock ge +tc ioctl pipe_op tie read print prtf seek send sysopen sysr +ead sysseek syswrite recv tell truncate ] ], sockets => [ qw[accept bind connect listen shutdown sockpair ] ], file => [ qw[ chdir chmod chown chroot link mkdir readlink rena +me rmdir symlink unlink utime rmdir ] ], directory => [ qw[ closedir open_dir readdir rewinddir seekdir telld +ir ] ], # process => # TODO: # Check backtick # die $?, not $! # [ qw[ exec fork kill system ] ], # I do not know how to validate the semaphore, shared m +emory, # or message passing code. Thi shared_memory => [ qw[ shmctl shmget shmread shmwrite ] ], message_passing => [ qw[ msgctl msgget msgrcv msgsnd ] ], semaphores => [ qw[ semctl semget semop ] ], eval => [ qw[ dofile ] ], miscellaneous => [ qw[ syscall ] ] ); @CHECK_OPS = ( map @$_, @CHECK_DICT{ qw( io sockets file directory eval miscellaneous ) } ); # I started with just nextstate and leavesub but while reading opcode. +pl # went "eh, what the heck. Why not?" and just included the raft of rel +ated # opcodes. @TERMINAL_OPS = ( qw[ method entersub leavesub leavesublv caller reset lineseq nextstate dbstate unstack enter leave scope enteriter iter enterloop leaveloop return redo dump goto exit ] ); $REPORT_CALLBACK = \ &default_report; CHECK { check(); } # Create an alias so that when fixing, a person can say fix() instead. + This # might only be interesting when the normal CHECK call wasn't called. *fix = \✓ sub check { if ( $FIX_OPCODES ) { walkallops_filtered( \ &find_unchecked_system_call, \ &queue_fix_opcode ); fix_opcode( $_ ) for @QUEUED_FIXES_TO_APPLY; } else { walkallops_filtered( \ &find_unchecked_system_call, $REPORT_CALLBACK ); } if ( $O_PM ) { eval "use O '$O_PM'"; } return 1; } sub import { my $class = shift; my %p = @_; # Ethier take a callback from the user via # use Devel::UncheckedOps ( callback => sub { ... } ); # or supply a default. $REPORT_CALLBACK = $p{'report_callback'} if $p{'report'}; # Allow both `use Devel::UncheckedOps( check => 'print' )` or # `use Devel::UncheckedOps( check => [ 'print' ] )`. This is the # parameter I most expect people to specify. if ( $p{'function'} ) { @CHECK_OPS = $p{'function'}; } elsif ( $p{'functions'} ) { @CHECK_OPS = @{$p{'functions'}}; } # This is a boolean value. $FIX_OPCODES = !! $p{'fix'}; if ( $FIX_OPCODES ) { eval q[ use B::Generate (); use Internals (); 1; ] or carp( $@ ); } # This is a boolean value. Various guts will be displayed if you p +ass # in a true value. The guts that are displayed are entirely up to +my # most recent needs. $DEBUG = !! $p{'debug'}; # This is passed to `use O '$O_PM'` so the user of this module can + say # `use Devel::UncheckedOps( O => 'Deparse' )` to see what the # code looks like after deparsing. The parameter is any module in +the B:: # namespace that has already been designed to be called by O.pm in + this # way. This includes Bblock, Bytecode, C, CC, Concise, Debug, Depa +rse, # Showlex, Stackobj, Stash, Terse, Xref or any other module you mi +ght # get from CPAN like B::Deobfuscate. $O_PM = $p{'O'}; # I seriously doubt that anyone is going to need to specify these. + I # include this solely for debugging purposes and perhaps the event +ual # need for it. @TERMINAL_OPS = @{$p{'terminal_ops'}} if $p{'terminals'}; return 1; } sub find_unchecked_system_call { # This is used by B::Utils::*_filtered to grep for opcodes that ne +ed to # be reported or fixed. my $op = shift; # I am going to fix/report this in another function immediately fo +llowing. $OPCODE_NAME = $op->oldname; # if ( $FIX_OPCODES ) # { # my $addr = $$op; # for my $m ( qw( sibling # first # { # my $to = eval { ${ $op->$m } }; # next unless $to; # push @{$OPMAP{ $to }}, [ $op, $m ]; # } # } # B::Utils::opgrep test to decide if this opcode is one that is de +sirable. return ( opgrep( { name => \ @CHECK_OPS, flags => OPf_WANT_VOID }, $op ) or opgrep( { name => \ @CHECK_OPS, next => { name => \ @TERMINAL_OPS } }, $op ) ); } sub default_report { # This is the default callback for reporting that something has go +ne awry. # It may be overriden by saying # use Devel::UncheckedOps( report => \ &other_sub ); carp( "Unchecked $OPCODE_NAME" . " call at $B::Utils::file line $B::Utils::line" ); } sub queue_fix_opcode { # This function puts fixes into a to-do list so that they are only # altered when the tree is not being currently walked. my $op = shift; push @QUEUED_FIXES_TO_APPLY, { op => $op, file => $B::Utils::file, line => $B::Utils::line }; return 1; } sub fix_opcode { # This function accepts a 'fix' as previously queued by queue_fix_ +opcode(). my $fix = shift; my $op = $fix->{'op'}; my $file = $fix->{'file'}; my $line = $fix->{'line'}; printf( __PACKAGE__ . " FIXING %s at %s line %s\n", op_to_text( $op ), $file, $line ) if $DEBUG; # This is the in-memory address of the opcode. It is used my $orig_next = $op->next; my $orig_sibling = $op->sibling; printf( __PACKAGE__ . " SIBLING %s\n", op_to_text( $orig_sibling ) ) if $DEBUG; my $orig_parent = $op->parent; printf( __PACKAGE__ . " PARENT %s\n", op_to_text( $orig_parent ) ) if $DEBUG; my $orig_reverse_first; $orig_reverse_first = $orig_parent if ${$orig_parent->first} == $$op; printf( __PACKAGE__ . " PARENT->FIRST %s\n", op_to_text( $orig_parent->first ) ) if $DEBUG; my $orig_reverse_last; $orig_reverse_last = $orig_parent if ${$orig_parent->last} == $$op; printf( __PACKAGE__ . " PARENT->LAST %s\n", op_to_text( $orig_parent->last ) ) if $DEBUG; # Maybe find the opcode that thinks this opcode is its sibling by +going # to this opcode's parent and walking over the list of siblings un +til this # one is reached. The previously visited opcode is the one we're a +fter. my @siblings = $orig_parent->kids; my $orig_reverse_sibling = ( grep ${$siblings[$_]->sibling} == $$o +p, 0 .. $#siblings - 1 )[0]; $orig_reverse_sibling = $siblings[ $orig_reverse_sibling ] if defined $orig_reverse_sibling; printf( __PACKAGE__ . " REVERSE SIBLING %s\n", op_to_text( $orig_reverse_sibling ) ) if ( $DEBUG and $orig_reverse_sibling and ${$orig_reverse_sibling->sibling} == $$op ); # Construct the new program fragment in reverse order so parent no +des # can point to child nodes. This alters the original node so it is # now inside the new fragment. # or # ORIGINAL # die # pushmark # gvsv use Devel::Peek; my $gvsv = B::SVOP->new( 'gvsv' => 2, '$!' ); # Now inflate the reference count for *! because this is a sneaky +way # to take a reference that doesn't inform the variable's refcnt. Internals::SetRefCount( \*!, 1 + Internals::GetRefCount( \*! ) ); my $pushmark = B::OP->new( 'pushmark' => 2 ); my $die = B::LISTOP->new( 'die' => 5, $pushmark, $gvsv ); $die->targ( 1 ); $die->private( 1 ); my $or_root = B::LOGOP->new( 'or' => 2, $op, $die ); my $or_op = $or_root->first; $or_op->private( 1 ); # Insert this fragment into the appropriate place in the tree. Eve +ry place # that the ORIGINAL node was, this new node has to replace it. # PARENT # ->first( ORIGINAL ) # ->last( ORIGINAL ) $orig_reverse_first->first( $or_root ) if $orig_reverse_first; $orig_reverse_last->last( $or_root ) if $orig_reverse_last; # PARENT # KID # ->sibling( ORIGINAL ) $orig_reverse_sibling->sibling( $or_root ) if $orig_reverse_siblin +g; # PARENT # ORIGINAL # ->sibling( KID ) $or_root->sibling( $orig_sibling ) if $orig_sibling; # Now thread the execution order. # EXT -> $op # -> OR # -> $orig_next # ... # -> $pushmark # -> gvsv # -> die # Insert the OR into the execution $op->next( $or_op ); # Continue as normal if $or succeeds $or_op->next( $orig_next ); # Otherwise detour and then reroute back to the normal place $or_op->other( $pushmark ); $pushmark->next( $gvsv ); $gvsv->next( $die ); $die->next( $orig_next ); 1; } sub op_to_text { my $op = shift; return 'undef' if not defined $op; my $class = class $op; my $name; eval { $name = $op->oldname; 1; } or do { $name = ''; }; my $addr = sprintf '(0x%07x)', $$op ; join( '=', grep length(), $class, $name, $addr ); } 1; __END__ =head1 NAME Devel::UncheckedOps - Perl extension to warp your mind =head1 SYNOPSIS use Devel::UncheckedOps ( functions => [ 'print', 'prtf' ], fix => 1 ); =head1 DESCRIPTION This module examines the compiled perl program and either reports or f +ixes unchecked system calls. =head1 USE PARAMETERS =over4 =item function => NAME This parameter specifies a single function name to search for. Do reme +mber to document %CHECK_DICT which has a big, categorized list of op codes. use Devel::UncheckedOps ( function => 'print' ); =item functions => \ @NAMES This parameter specifies a list of function names to search for. Do re +member to document %CHECK_DICT which has a big, categorized list of op codes. =item report => \ &CALLBACK If the program is not fixing then it is reporting. This allows the use +r to specify and alternate reporting function. It is passed the opcode that + is in error. =item fix => BOOLEAN A boolean value that triggers all the really cool guts so even non-ove +rridable stuff like print and printf are fixed up. =item debug => BOOLEAN A boolean to get some additional information. Generally this is useful + when debugging the operation of the fixing code. =item O => B:: backend name Put stuff like 'Deparse', 'Concise', 'Terse', 'Debug', etc. here. This + just arranges to have the program passed to the appropriate B:: backend aft +er it has been altered. It is like saying -MO=Deparse to a command-line scri +pt. =item terminal_ops => \ @NAMES Go read the source. =back =head1 MOD_PERL? Mention that everything can be called directly from check() though eve +rything normally happens during the normal CHECK routine. This may not even be + valid to bring up. =head1 SEE ALSO See... what? That request that wished for this? =head1 AUTHOR Me. =head1 COPYRIGHT AND LICENSE Same as perl, etc,. =cut [download] This is a patch to B::Utils 0.04 so that the ->parent call works correctly. This is a patch to B::Generate 1.07 so that the instantiation of the various B::SPECIAL objects don't trigger segfaults (B got it right - B::Generate just forgot to include this). Just a quick question for you diotalevi. What is the reasoning behind altering every print or printf statement and not just those associated with a filehandle other than STDOUT? This question popped into my head when I saw: print "Hello world!\n"; # Becomes # print "Hello world!\n" or die $!; [download] I have an idea as to why you did that. Rather than show ignorance and spout off some possibly totally stupid idea (I am still a novice perlguts/B spelunker after all), I think I'll just wait for a response. :) I still wonder if that would error if the buffer weren't flushed though. It at least makes it more likely especially as the default also puts an `or die $!` on the close() op. There isn't anything to be done about implicit closes though. An update. It has been suggested that I patch perl so that failures during implicit closes throw warnings, probably in the 'io'.
http://www.perlmonks.org/?node_id=367478
CC-MAIN-2017-47
refinedweb
2,066
61.06
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <rtl.h> BOOL smtp_connect ( U8* ipadr, /* IP address of the SMTP server. */ U16 port, /* Port number of SMTP server. */ void (*cbfunc)(U8 event) ); /* Function to call when the SMTP session ends. */ The smtp_connect function starts the SMTP client on the TCPnet system. This causes the SMTP client to then start an SMTP session by connecting to an SMTP server on the TCP port specified in the function argument. The argument ipadr points to an array of 4 bytes containing the dotted-decimal notation of the IP address of the SMTP server to connect to. The argument cbfunc points to a function that the SMTP client running on TCPnet calls when the SMTP session ends. The cbfunc is an event callback function that uses the event argument of the cbfunc function to signal one of the following SMTP events: The smtp_connect function is in the RL-TCPnet library. The prototype is defined in rtl.h. note The smtp_connect function returns __TRUE if the SMTP client has been successfully started. Otherwise it returns __FALSE. smtp_cbfunc static void smtp_cback (U8 event); void send_email (void) { U8 smtpip[4] = {192,168,2,253}; if (smtp_connect (smtpip, 25, smtp_cback) == 0) { printf("E-mail not sent, SMTP Client not ready.\n"); } else { printf("SMTP Client started.\n"); } } static void smtp_cback (U8 event) { switch (event) { case SMTP_EVT_SUCCESS: printf ("Email successfully sent\n"); break; case SMTP_EVT_TIMEOUT: /* Timeout, try again. */ printf ("Mail Server timeout.\n"); break; case SMTP_EVT_ERROR: /* Error, try again. */ printf ("Error sending.
https://www.keil.com/support/man/docs/rlarm/rlarm_smtp_connect.htm
CC-MAIN-2020-34
refinedweb
257
66.54
[ ] Nicolas Lalevée commented on IVYDE-98: -------------------------------------- Could it be related to IVYDE-52 ? In the ivy console, does ivy complains about failing to load that file ? If it does, which file path it tries to load ? And can you test that IVYDE-52 is the bottom of the issue please: start eclipse while your are in the directory where your settings belongs, so the "current dir" will be the ivy settings one, and probably Ivy will then be able to find your files. > Inclusion of ivysettings files in a main ivysettings.xml does not work. > ----------------------------------------------------------------------- > > Key: IVYDE-98 > URL: > Project: IvyDE > Issue Type: Bug > Affects Versions: 2.0.0.alpha1 > Reporter: Erik-Berndt Scheper > Fix For: 2.0 > > > Inclusion of ivy settings file in IVYDE does not work (using a file or http reference). > Note: inclusion of properties does work, but apparently only when using a URL. > E.g. when I include my namespaces as follows: > {code:xml} > <ivysettings> > <properties file="" /> > <include file="./ivy.settings.namespaces.xml"/> > </ivysettings> > {code} > this works fine in batch mode (using ant), but fails in IVYDE. > Console message: > : problems summary :: > :::: WARNINGS > namespace not found for joda-time#joda-time;1.5.2: maven2.repo1.maven.org > namespace not found for org.junit#junit;4.4: maven2.repo1.maven.org -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/ant-notifications/200808.mbox/%3C2122906322.1220007767318.JavaMail.jira@brutus%3E
CC-MAIN-2015-18
refinedweb
235
67.04
This is the mail archive of the cygwin-patches mailing list for the Cygwin project. I tracked down the problem reported in <>. The crash was occuring in pthread_mutex_lock, but that's a bit of a red herring. The real problem is that both newlib and Cygwin provide a include/sys/stdio.h file, however they were out of sync with regard to the _flockfile definition. This comes about because vsnprintf() is implemented by creating a struct FILE that represents the string buffer and then this is passed to the standard vfprintf(). The 'flags' member of this FILE has the __SSTR flag set to indicate that this is just a string buffer, and consequently no locking should or can be performed; the lock member isn't even initialized. The newlib/libc/include/sys/stdio.h therefore has this: #if !defined(_flockfile) #ifndef __SINGLE_THREAD__ # define _flockfile(fp) (((fp)->_flags & __SSTR) ? 0 : __lock_acquire_recursive((fp)->_lock)) #else # define _flockfile(fp) #endif #endif #if !defined(_funlockfile) #ifndef __SINGLE_THREAD__ # define _funlockfile(fp) (((fp)->_flags & __SSTR) ? 0 : __lock_release_recursive((fp)->_lock)) #else # define _funlockfile(fp) #endif #endif However, the Cygwin version of this header with the same name gets preference and doesn't know to check the flags like this, and thus unconditionally tries to lock the stream. This leads ultimately to a crash in pthread_mutex_lock because the lock member is just uninitialized junk. The attached patch fixes Cygwin's copy of the header and makes the poster's testcase function as expected. This only would appear in a multithreaded program because the __cygwin_lock_* functions expand to no-op in the case where there's only one thread. Since this is used in a C++ file (syscalls.cc) I couldn't do the "test ? 0 : func()" idiom where void is the return type as that generates a compiler error, so I use an 'if'. Brian 2007-09-06 Brian Dessent <brian@dessent.net> * include/sys/stdio.h (_flockfile): Don't try to lock a FILE that has the __SSTR flag set. (_ftrylockfile): Likewise. (_funlockfile): Likewise. Index: include/sys/stdio.h =================================================================== RCS file: /cvs/src/src/winsup/cygwin/include/sys/stdio.h,v retrieving revision 1.6 diff -u -p -r1.6 stdio.h --- include/sys/stdio.h 5 Feb 2006 20:30:24 -0000 1.6 +++ include/sys/stdio.h 6 Sep 2007 18:27:33 -0000 @@ -16,13 +16,16 @@ details. */ #if !defined(__SINGLE_THREAD__) # if !defined(_flockfile) -# define _flockfile(fp) __cygwin_lock_lock ((_LOCK_T *)&(fp)->_lock) +# define _flockfile(fp) ({ if (!((fp)->_flags & __SSTR)) \ + __cygwin_lock_lock ((_LOCK_T *)&(fp)->_lock); }) # endif # if !defined(_ftrylockfile) -# define _ftrylockfile(fp) __cygwin_lock_trylock ((_LOCK_T *)&(fp)->_lock) +# define _ftrylockfile(fp) (((fp)->_flags & __SSTR) ? 0 : \ + __cygwin_lock_trylock ((_LOCK_T *)&(fp)->_lock)) # endif # if !defined(_funlockfile) -# define _funlockfile(fp) __cygwin_lock_unlock ((_LOCK_T *)&(fp)->_lock) +# define _funlockfile(fp) ({ if (!((fp)->_flags & __SSTR)) \ + __cygwin_lock_unlock ((_LOCK_T *)&(fp)->_lock); }) # endif #endif
http://cygwin.com/ml/cygwin-patches/2007-q3/msg00013.html
crawl-002
refinedweb
464
59.09
96 comments: This is one heck of a useful tool. I tried it out and managed to deploy my MOSS site from one server to another without any issue. I do have a question, though. When will the tool be able to only deploy 'changes' done to a certain site instead of a complete site deployment? Hi Albert, Thanks for the feedback. In terms of deploying incremental changes, this is something I'd definitely like to add - it's useful to hear other people would find this useful. There are some tidy-up bits ahead of this in the queue, but I'll add it to the list of things to consider. Afraid I can't make any promise on the date though, realistically it could be a month or two. Thanks, Chris. Great post, and it looks like a useful tool. One question: If the tool is used to do initial deployment (to a new production site for example), can a SP content deployment job still be used to schedule subsequent deployments? Hi Maina, Yes this will be absolutely fine as the same underlying API is used. The one stipulation is that in the Wizard, you check the box marked "Retain object IDs and locations" when deploying. This ensures objects in your site have the same IDs in both the source and target - content deployment jobs expect this to be the case. See "Mixing deployments with and without retaining object identity" on Stefan's content migration API 'common problems' post for more background on this. Cheers, Chris. Hey Chris, We would like to be able to deploy multiple copies of the same master site to several site collections on the same web application. Currently when attempting to do this, we receive a message indicating there are duplicate object ID in the database. Thank you and I hope to hear back from you soon. Hey Albert, Yes, SharePoint will not let you store two objects with the same ID in one database. I'm wondering if you are selecting the 'Retain object IDs and locations' checkbox when importing - in this scenario, I think you should NOT be. HTH, Chris. Hi Chris, I'm trying to import a complete site collection, however I'm getting an obscure error on import. The import fails with: FatalError: The element 'Field' in namespace 'urn:deployment-manifest-schema' cannot contain text. From looking in the log it appears that the element its failing on is WorkflowTasks/NewForm.aspx I'm trying to migrate a PublishingSite, and I read somewhere that I need to create a blank site as the initial template to deploy into, but that doesn't seem to help. Any ideas? Thanks, Justin Hi Justin, Hmm that is pretty obscure, not heard that one before. However you're correct in what you say - content deployment does require the target site to be created with the blank site definition. Since it also requires that both the source/target site are based on the same definition, this means you should select blank when creating the site in development too. This is a bit of a gotcha with content deployment in SharePoint which I probably should have been more explicit in reminding people about. In short, I'd probably expect things to fail in your scenario, but with a different error message (indicating what I've just said). It could be that this is actually your problem though. I think I once saw some tips on how to move off one site definition to another - suggest searching for this. HTH, Chris. Hi Chris! Thanks for this useful tool. It would be good if it could Export folders from a particular document library, and import these files to a document library with a different name nudge nudge wink wink. Hi Zarek, Interesting. I'm due to look at enhancing the reparenting options pretty soon so this might not be too far away. Thanks for the feedback. Chris. I have been able to export a site (dev2) collection successfully. When I import it like so: site url: import web url It completes with no errors or warnings but when I browse to ../sites/dev/dev2 there is nothing there. Any suggestions? Hi Chris, the tool looks extremely helpful. Thank you for spending so much of your spare time building it and explaining how it works. As somebody who is new to Sharepoint, but is looking to build an accelerator for clients (essentially create a template for a certain type of company for them to deploy and fill with content), I'm looking for any gotchas. Presently, I am planning to make heavy use of site columns, programmatic events and content types, and will possibly walk into a client site with some of their data pre-loaded. From what you've said, I should start with a blank slate and deploy a to a clean site collection on their side. Incremental updates should be less of a challenge although I can imagine a scenario where I go in, deploy to dev >> build content >> deploy staging >> deploy to production. Any thoughts / things to research before I dive in would be appreciated. Haven't coded since VS 2003, so using the content deployment api is a bit daunting. If possible I'd be keen to avoid it. Cheers Neil Hi Juha, I suspect that since you exported the site collection, this will have imported to /sites/dev2. If this is the case, it could be possible that if you could just select the root web of the site collection, you would be able to move the web in the hierarchy but at present, when selecting the root in the treeview you are selecting the site collection. Site collections cannot be reparented (location in hierarchy changed) in the same way webs can. A way to work around this would be to do a 2nd export from /sites/dev2, and then on the import, enter the import web URL for the real location you want. You can then delete the site at /sites/dev2. Hopefully this should work fine. I'd also suggest checking the import log file to see if the site actually just didn't import for some other reason. HTH, Chris. Hi Neil, Thanks for the feedback. I'd expect you should be able to use the tool fine for this scenario. In most cases though, I see the tool being used in combination with Solutions/Features to deploy reasonably complex sites. The content migration API (and hence the Wizard) is not capable of deploying all components of a SharePoint site, so filesystem assets such as assemblies/files which go into the 12 folder etc. should be deployed with Solutions/Features. You'll generally need to deploy these first before importing content, since otherwise the import will fail and report that something (e.g. a Feature) from the source site is not present on the destination. Suggest having a look at some my 2007 articles for info on Solutions/Features. HTH, Chris. This tool is great thank you! I spent 1.5 days messing around with random stsadm import/export issues compared to the 1 hr from finding your tool to having my site moved from Dev to Test Environment. Thank you. My findings: - I added a new column and content to the Test Server and then redployed a site from Dev. The column and content on the Test Server remained after the site was redeployed. A few questions: 1) What's happening with the databases? For example if I have a content database for a site collection on the Target Server but only import a subsite from the Source Server will a new content database be created for the imported subsite on the Target Server? Or will content be added to the existing Target Server's content database? Or something else? Garth, Thanks for taking the time to feed back. Your experience with STSADM export was basically what prompted me to write the tool ;-) And yes, because the Wizard allows selective deployment of items, no content on the target environment should be overwritten accidentally. In terms of databases, content will be added to your target site's existing content database. HTH, Chris. Hey Chris, Loving the concept, but I CANNOT get it to work. I think maybe I am just understanding SharePoint bits wrong as I am a newbie. I am trying to move a few lists from a site on one server to a site on another. I export the lists, including dependents..no worries. this is with Beta 2 Then, I move the cmp file to a share that is accessed by the new server. Original URL is: I have created a new website on server 2 under: When I import, I select the cmp file and put the Site URL as: and run it....it fails with "The file Lists/Issues cannot be imported because its parent web /EPM Reporting does not exist" - I have tried as many combinations of this, using both site URL and Import Site URL, and also the retain ID option....basically it always fails with some version of the error message above...Can you tell me what I am doing wrong? Many thanks in advance Hi Ross, That's an interesting error, as it's suggesting that the reparenting instruction isn't quite right (since it's trying to import to "/EPM Reporting" rather than "/PWA/Reporting"). The set of parameters you need are: - do NOT check 'retain object IDs and locations' - enter the 'import web URL' of the web if you are not importing to the root web on the target However, I actually think the main cause is because you are on beta 2. The Content Migration API had some big known issues at this time - I'd be surprised if you didn't get errors. Is there a specific reason why you're still using this release 1 year+ after RTM? Chris. Sorry...I should have been clearer. The Beta referred to the codeplex, not the project server install....DOH! Thanks for responding though. Will try what you say and get back to you....server itself is playing games at the moment, so may have something to do with it! Cheers R Ah right, beta 2 of the Wizard! Sorry, should have realized that's what you meant :-) Get back to me if you're still having issues.. Cheers, Chris. Hello Chris, I have the same problem as in the last post by Ross. This happens just on some specific website. Can this be due to a SharePoint bug ? @sh, It's possible this is caused by a SharePoint bug - especially if you don't have SP1 and the latest hotfixes for Content Deployment. However, I've only seen this particular message when the parent website genuinely isn't there. Are you sure the parent web is present on the destination? Also, have you performed any imports on the destination without retaining object IDs (perhaps by using STSADM import?) - this could result in the parent web being there but with a different GUID, which could confuse the issue. HTH, Chris. Hi Chris, I am using the content deployment API for a project. Is there any way we can increase the cab file size to be more than 25 mb. So API does not break the files ... Thanks Ajay @Ajay, You can use the SPExportSettings.FileMaxSize property for this. See for more details. HTH, Chris. I have a ques about feature activation. DO I need to activate features or as Stefan articles say PRIME automatically tales care of activating features. They only need to be installed. Couls you please clarify. @Tajeshwar, Stefan is correct - PRIME/content deployment will activate any Features which need to be active for the target environment to match the source, but they do need to be installed first. HTH, Chris. Hi I keep getting an unhandled exection error (access denied) even when logged onto box as local admin. I'm using v1.1 Any suggestions please? Steve Hi Steve, Do you mean the 1.1 version I uploaded to Codeplex today (22 Sept)? In any case, would you mind replying with your e-mail address (I won't publish to the blog) so I can work through this problem with you? Many thanks, Chris. I got an error when importing a site collection from dev to a blank site collection in production: [10/17/2008 9:11:03 AM]: FatalError: Could not load file or assembly 'ReservationEventHandler, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified..ContentTypeSerializer.UpdateEventReceivers(SPContentType contentType, String contentTypeXml, StreamingContext context, ISurrogateSelector selector)() Please help, PJ Hi Chris, great tool that got me out of a seriously hairy position this week. One question though; if you export a sub-site of a site collection can you import this as a root site collection on another box? All my attempts resulted in it being restored as a sub-site within the target site collection rather restoring AS the root site. Thanks, Troy. @PJ, Typically this error means exactly what it says - an assembly which was present on the source environment cannot be found on the target environment. In your case I see it seems to be referring to one of the SharePoint system assemblies - has anything been deleted from the GAC accidentally? On another angle, I do remember seeing an odd occasion where the assembly this error complained about genuinely was present, and without changing anything the error went away (and the import succeeded) after rebooting.. HTH, Chris. @troyhunt, Interesting one - I'm actually not sure it's possible to reparent an exported web so that it replaces the existing root web of a site collection. I've got a feeling it should be possible somehow though! You could try asking Stefan Gossner for the appropriate parameters to pass to the Content Deployment API for this. From there you might be able to either work out what to do in the Wizard, or you may need to tweak the Wizard code slightly to support this scenario. Sorry if that's not the simple answer you were looking for.. Chris. Hi Chris, wizard the best way (or even A way at all) to achieve this? Thanks! Carin, Yes, I think that you should be able to use the Wizard code (available at as a starting point for your tool. (N.B. I don't think you can use the Wizard as is since it doesn't yet support automation/scripting). If I've interpreted your requirements correctly, using the Content Deployment API in the same way the Wizard does should tick all your boxes. HTH, Chris. Hi, I'm working with WSS 3.0SP1 and am trying to export a list ()from a subsite and import it into a different site in the same Sharepoint parent site ().. Export seems to work fine, but when I import, I get .NET errors. I'm using for the Site URL and for the Import web URL. The error I get is System.ArgumentException: Value does not fall within the expected range... Any ideas to help me get through this... I'll save my praise comments after I get this to work :) Thanks!! Hi Elvis, Wise man ;-) Could it be that a Feature isn't present/activated in the web you are importing to? I've seen this error come up when Features aren't in sync (since Content Deployment expects them to be). Otherwise, assuming you're up-to-date with SP1 and other updates (which fixed some issues with Content Deployment), the only things I can suggest unfortunately are: - checking the SharePoint logs/Wizard log for more clues on where it's failing - searching for others who have also run into this error using Content Deployment Cheers, Chris. P.S. That was typo wasn't it - you're specifying as your import web URL right? P.P.S. And you're not ticking 'retain object IDs and locations' (since you can't retain IDs when reparenting an object)? Chris, Thanks for the fast response! I checked site features for both sites and they the features installed and active are the same. Could I create a 2nd list with a different name at the same location for testing? I think I might not have been clear in my original post. We have multiple subsites corresponding to business units that are all under our main portal page, would I consider those sites or subsites? If subsites, then.... source is and destination is thx! Elvis, In that case you should use '' as your import web URL if you're not already. This value always corresponds to the web you wish to import the object to - so whether it's a web or list you're importing, always specify the path to the direct parent web. HTH, Chris. Chris, The product worked like a CHARM!!! I'll gladly sing your praises now. If you are ever in the Hartford, Connecticut area let me know... drinks on me! Thanks again for your help! Elvis Elvis, Excellent, glad you got sorted :-) Chris. Hmmm, when I attempt to import a list from another subsite, I get the following once it starts importing Threaded.aspx.. I get Microsoft.Sharepoint.SPException: Error in the application.. at ....SPList.UpdateDirectoryManagementService(STring oldalias, String newalias)... any ideas? thx Hmm, I think it might have something to do with the fact that the Discussion lists all have the same web address (General discussion in the link).. anyone know how to customize this? I am exporting and importing a Discussion board using this tool, it completes fine, but when I check the site. It just doesn't have anything from the exported site! No errors! I am a local administrator on the server as well as Farm administrator, so no issues with the permissions.. Am I missing any steps? I am exporting and importing All and am not excluding anything, no retain identity flag ticked etc. I am bit lost here, any help will be much appriciated. Thanks Meera I got it squared away Chris.. Used Sharepoint Designer 2007 to change the actual list names, then your tool had no problems exporting/importing the lists... Awesome tool! @Meera, Hmm, sounds slightly suspicious. I wonder if you are perhaps expecting the imported content to be found in a certain location, but the import has actually put it somewhere else? Does the import log file have any errors/warnings? Thanks, Chris. @Elvis, Good sleuthing! Glad to hear you got sorted.. Chris. Chris: Great tool. Worked perfectly. Thanks for sharing it with us. Rob Hey Chris, I was trying to use the CDW to reparent a site, but for some misterious reason it doesn't do what I want it to do. I have a top-level site in site collection A (), which I want to move to a sub-site in site collection B (). So I export the whole site from A and select to import it a blank site in B. The import parameters I use are: Site URL: Import web URL: (where newloc is an empty site) Preserve Identity: no But when the import runs, I end up with content of siteA being copied to the root siteB, not under newloc. What am I doing wrong? Thanks and keep on your great work! Alex i'm trying to export a list and am getting an error. I was hoping you could help. Error: [3/27/2009 10:42:22 AM]: Progress: Starting to process objects of type ContentType. [3/27/2009 10:42:22 AM]: FatalError: Field type Tag is not installed properly. Go to the list settings page to delete this field. at Microsoft.SharePoint.SPFieldCollection.CreateSPField(Int32 index) at Microsoft.SharePoint.SPFieldCollection.EnsureSPField(Int32 index) at Microsoft.SharePoint.SPFieldCollection.get_Item(Int32 iIndex) at Microsoft.SharePoint.SPFieldCollection.ItemAtIndex(Int32 iIndex) at Microsoft.SharePoint.SPBaseCollection.SPEnumerator.System.Collections.IEnumerator.get_Current() at Microsoft.SharePoint.SPContentType.get_Fields() at Microsoft.SharePoint.Deployment.ContentTypeSerializer.GetDataFromDataSet() Thanks, Brandon @Alex, Sorry for the delay in getting to your comment, I've been completely snowed under. Hmm - I think there might be a limitation of the Wizard here that you've ran into - I don't think you're doing anything wrong with those parameters. What I think is happening is that when you select a top-level site, it's being taken with the 'Site' tag when in your case you want to take it with the 'Web' tag (since you effectively want to export the root web of that site collection, rather than the site collection itself). At the moment, the Wizard doesn't allow you to specify. I'll add this to my task list for enhancements to the Wizard. Unfortunately, my only suggestion for now is to modify the code if you (or someone you work with) has development skills. It would be a one-liner to change the code once the right place is found. If you go down this path and need any help from me, feel free to get in touch. Otherwise I hope to add this in to the current release over the next 2 weeks or so if you can wait that long! Sorry for the inconvenience.. Chris. @Brandon, Sorry for the delay in getting to your comment, I've been completely snowed under. Is 'Tag' a custom field type rather than a standard field? Typically this error occurs when something isn't quite right in the definition for a custom field (e.g. in your fldtypes*.xml file) HTH, Chris. Chris hi, let me start by thanking you very much for this useful tool. I've used it regularly for several purposes (lists, webs, collection) and i am very pleased by its performance. A quick question about the site collection deployment. We tried to deploy a site collection from one farm to another (retaining object ids). It worked like a charm :-) The thing is we want to use the Content Deployment feature of Moss for our future content deployment. Should we do a full deployment or will the quick deployment (incremental) do the trick?? If its the former is there a way (a token or something) so as to not fully deploy again the same content (8 Gbs is a lot)... Thanx again for your time, @Kostas, Glad you find the tool useful :-) If I understand the question properly, you're asking if you should use the incremental option with standard Content Deployment? In general, you should do the first deployment as a full, then subsequent deployments can be incremental. This would be the recommended approach. Also note that I'm hoping to add incremental deployment to my tool over the next month or so. HTH, Chris. Hi Chris, We are looking at deploying the items in Reusable Content, and some document libraries with pages that makes use of these reusable content from our development to the client's UAT environment. Is is possible to achieve this using your tool without having to create a blank site at the destination? Because there are existing subsites, lists etc that we do not wish to over-write. When I select just required items in the Reusable content list and do an import specifying the Import URL as "", I get a error like "object reference not found ...". Grateful if you can offer any advice on this, thanks. @BN, Yes, it is possible to import Reusable Content items into a site which already has data, done it many times. The mistake you're making is putting "" in the Import Web URL box - since the ReusableContent list is a list in the root web of a publishing site (not a subweb), you should not specify anything for the Import Web URL. HTH, Chris. Hi Chris, My organisation is starting to rebuild the company intranet using Sharepoint, and I've been given the joyful task of sorting out deployment processes. I love the look of this wizard, just one thing I wonder if you can answer for me. One of the things we always have to document is backout plans in the event of a deployment failing / users not happy (as if!) / whatever. What would be the backout method using the CDW? As I see it, the 2 options are: 1) backup prior to deployment then restore from that backup 2) use stsadm -retractsolution(though presumably this is only for .wsp solution deployments?) Is there anything I have missed? And does the CDW include an option to retract deployments? Many thanks, Nick @Nick, Unfortunately, deployments in SharePoint are not transactional, so you have to do some work with backups to ensure you have a good roll-back position. This is the case for both: - deployment of assets using WSPs - content deployment (e.g. with my Wizard or by configuring OOTB content deployment in Central Admin) I note that you seem to be confusing the two slightly. The Wizard does not do anything with wsps (i.e. deployment *or* retraction) - this is typically done separately with any deployment scripts you might have. This will take care of any filesystem assets you have (12 hive files, Features, SPWebConfigModifications etc.). THEN, as a subsequent step, content deployment is used to deploy the actual content (e.g. webs, lists, list items, pages etc.) from source to target. So I suggest backup of filesystem AND content database is used to establish your rollback position before deployments. Indeed the Wizard prompts you with a warning before doing an import as a reminder. Backup tools such as Data Protection Manager 2007 simplify this process if you're able to use them. HTH, Chris. Hi Chris, Thanks for the great tool! Regarding the tool, is there any way to export at the site level without having the content on the target destination be overwritten if it already exists? Basically, I want to update my home page of the target site with the home page of my development site without having to update anything else. Thanks in advance for any response. @Anonymous, Not currently - the tool does not yet support incremental deployment (i.e. only deploy changed content). However I'm hoping to build this into the tool over the next few weeks :-) Out of interest, is there any reason why you can't select your homepage only and deploy that? Or am I not understanding your scenario properly? Thanks, Chris. Chris, Is this tool useful when migrating a Sharepoint server that has its content database stored on a separate server? The content database will not be moving - it is staying on the same database server. The rest of Sharepoint needs to be moved to a new server though. Hi Chris, Thanks for the quick response. Maybe I am using the tool incorrectly? This is a structure of what I have: - - - subsite1 - DocumentLibrary1 - subsite1 - DocumentLibrary2 - When using your tool for export, I selected "" - "Exclude descendents" & "Exclude dependencies". When I imported the file, I selected "Retain object IDs and locations" with the version options of "Append". Doing this updated the homepage of as I needed but it also updated the contents in subsite1 - DocumentLibrary1 and subsite2 - DocumentLibrary2 which I did not want to do... I am not seeing where to select the homepage to update only just that? Btw, I am looking forward to your incorporation of the incremental deployment in the tool!! Thanks!! @Steven, Hmm, I'm not exactly sure what you mean by that. Do you mean that your changing the web server used in your SharePoint implementation? If so, then no - you'd only need to add your new box to the existing farm then remove the old one. This tool would not be used in that scenario. HTH, Chris. @Anonymous, Hmm interesting - I would have expected selecting 'Exclude dependencies' would have done what you're looking for. Notably if your site uses the MOSS publishing Feature you can just select the homepage in the Pages library and deploy that, but I'm guessing your site doesn't. It could be that you've found a bug. I'm starting the process of implementing incremental deployment this weekend, so will take a look when I'm in the code. Thanks, Chris. How is the incremental deployment going? This looks like just what we need. We are moving from QA to a Production server soon. Would like to use this tool and in the future for any upgrades we make. Good timing :) I'm in the last stages of dev/testing, should be up on Codeplex (along with a blog article here) in the next few days. As always, be interested to hear if you run into any problems, leave a comment here or on Codeplex and I'll try my best to help. Thanks, Chris. Hi, Will this work when exporting from 32 bit to a different server in a 64 bit environment ? @Tanga, Yes that should be absolutely fine, nothing in the deployment process would care about x86 or x64. HTH, Chris. Hi Chris, I'm having fun with the incremental export (using the 2.5 Beta). I select 'ExportChanges' from the drop down list, and it immediately comes up with a message box, "Unable to perform incremental export - the Wizard did not find a stored change token for the largest object you have selected to export. This could be because a full export for the site or web has not yest been performed using this version of the Wizard". What I did was performed an 'Export' on the site, passed the .cmp to our production guys to implement on the live server, then made changes to the site. I have checked the change log and there appear to be 'add' items corresponding to the number of items I added to the site, and the guid in the log matches the guid of the site. Any ideas what I may be doing wrong? Could there be something in the logging settings that is somehow affecting what is being picked up? This is not to detract from a great tool; this is not a major issue for us as the full export works ok; however, as the site grows, it will be good to be able to update with just the changes. Many thanks. @Sean, If I understand correctly, are you saying that you have performed a full export (using the 2.5 beta or later of the Wizard - this is important), and then subsequently see the message you quote when you try to do an incremental? What happens if you do another full export, make some changes and then try the incremental again? Thanks, Chris. I am trying to move a document library from one subsite to a different site. Is this possible? When importing what do I put in the urls? I am confused what goes where. Do I put the address I want it to go? Thanks for replying so promptly, Chris. Yes, I am using the 2.5 beta of the wizard. I have now tried doing another full export and making changes, and I'm getting the same again. Not helpful, am I!!! Thanks for your help.... Sean @Sean, Sorry for the delay, have been travelling back from the big SharePoint Conference. I can't seem to recreate this, but I'll keep trying - in the meantime, can you explain more about what environments you have/where you're doing the export/import etc? Thanks, Chris. @Archeious the Librarian, When importing, the values to use should be: - Site URL: the URL for the site collection e.g. - Import web URL: the URL for the site within the site collection e.g. Hope that makes sense. Chris. Chris - I am experiencing the same issue as Sean regarding the incremental export. A little more detail: I'm using version 2.7 of the wizard, exporting from a MOSS 2007 SP2 document workspace with several DWS subsites. The subsites are based on a saved template, permissions inheritence is broken, and there are event receivers on some of the libraries that are part of the saved template. Other than that there is not anything special about the sites. I have had success on this site doing full deploys. I have also tried making changes and then trying the incrememntal after a full, but the same same issue occurs. Hopefully that helps? Thanks, Dave @Sean, @David Perry, This is now a confirmed bug - apologies for the inconvenience. Not sure exactly when I'll be able to resolve it, but it definitely will happen sometime over the next few weeks. The Codeplex site will have the details. For now I can only suggest doing full exports. Thanks for the reports. Chris. Thank you very much Chris your tool is great and I copy lists from one site to another, and it works great with under any web application even if WAP uses host headers or not but I have one web application which using AAM with host headers and extended for external and custom, copy list process completes successfully, import and export logs completes successfully with no errors but when I open the destination site, list does not exist at the destination site. If I tried to copy same list under another site which does not use host header and not extended and it copies successfully. Anybody has same or similar problem or list what might be go wrong? Anybody has any idea where is the copied list at the destination? @Anonymous, I don't think AAM should have any effect on Content Deployment, so I'm not sure what to say. Have you checked everywhere in your site structure in case you used some options and weren't sure which destination you'd end up with? HTH, Chris. Hi Chris, I want to use the SPExportSettings.FileMaxSize property to set the maximum size of my exported package to 1 GB. I have tried it but that is no working. Even after setting this property, the package still be broken in two parts. I am not sure what is missing. Any help is highly appreciated. Thanks, Vijay @Vijay, I did some research and found your (answered) post at. So it seems you can use "1023" but not "1024" - good info, thanks. Chris. Hi Chris, Thanks for this great tool !! I've an issue of Importing Custom SQL Server Report Viewer Web Part. After Importing, this web part failed to view the report as it contains Export Server Name in its Report Server Path. I've gone through Manifest.xml but no such attribute found where I thought to replace the Export Server name with Import Server's. Another thing I've tried is Exporting a web part to .dwp file and then importing it. It also failed with same error. So, I just renamed the .dwp file to .xml and changed the ReportServerPath Attribute to point to Export Report Server. And it worked !! Is there a possible work-around for it ? Vishwajit Hi Chris, Great tool, Thanks. I did an export and disabled compression. Is there any documentation on the command-line to import? Garry @Garry, Yes I have documented this properly somewhere, but in my completely professional way I now can't find where. Let me try to explain here: - follow steps 6 and 7 of the process in Command-line support for Content Deployment Wizard - edit the generated XML file to ensure that the 'FileLocation' attribute points to the folder path where all the files are stored, there is no 'BaseFileName' attribute, and FileCompression is set to 'False' Feel free to reply again here if you run into problems. Thanks, Chris. Hello Chris, This is in continuation of my previous post about "Export / Import of Custom SSRS Report Viewer Web Part". We've came up with partial work around for this issue, details of which can be found at MSDN Forum : Your assistance would be much appreciated to make this "fully-working". Thanks, Vishwajit @vishwajitwalke, I read your post in the MSDN forums. Unfortunately it looks like this is just a limitation of the SSRS Report Viewer web part - if it hardcodes an absolute URL I can't think of any course of action other than what you have done. Either that, or simply edit the web part page *after* the import has been done on the target. Sorry I can't be more help. Chris. Hello Chris, first of all thank you for sharing this tool. I have a little problem when trying to migrate reports(from reporting services) this reports are on a Document Library, and when the import procedure is starting the tool is saying for every particular report that it's located there. Thanks for help!! Laureano. @Laureano, Can you tell me what the exact error message is? Thanks, Chris. Hi Chris, This is in continuation with my earlier post about "Problem in Import / Export the SSRS Web Part". We've come up with a concrete solution for this issue. Please refer the resolution at this thread : Thanks. Vishwajit Hi Chris, Thanks for creating such a great tool. I've been testing a lot of things with it, and I generally understand it. But I do have a question. I am dealing with moving an entire site collection from location A to location B. I am aware that, if the URL of A is and the URL of B is, then I should leave the 'Import Web URL' field blank and check the 'retain object IDs' box. However, what if the URL of A is and the URL of B is? Then do I have to specify an 'Import Web URL'? And should I check the 'retain object IDs' box? The reason I ask is because you say "if it is reparented" to specify the 'Import Web URL' field. But in that situation, is it being reparented or not? And why? My thoughts are that it IS being reparented in the second situation I mentioned, simply because the "top level site" (as SP calls it when you create a new site collection) is different on the destination than it is on the source. Thanks. -Kyle @Kyle, Great question. In fact, the content *isn't* being reparented in the example you mention - this is reparenting really refers to anything *beneath* a site collection, rather than a site collection itself. So reparenting examples include moving a web to another place in the structure/moving a list to another web etc. This is basically because a site collection is the boundary for many things in SharePoint, including references between objects. HTH, Chris. Hi Chris, Kyle here again. Thanks a lot for your previous reply, that helps to clarify. As a follow up question, what if I had already completed the move I described in my previous post (i.e., now both /webApp/site and /otherApp/otherSite have the same site collection on them). Now I want to move a SINGLE site called "HelpSite". On /webApp/site it is located at /webApp/site/HelpSite and I'm moving it to /otherApp/otherSite/HelpSite. I'm assuming that, according to your prior explanation, I do NOT need to specify an Import Web URL since no reparenting is occurring? In other words it is not the URL itself that matters, it is only the location of the item that you are moving relative to the entire site collection. So if the whole site collection is at /1/2 on the source and at /1/2/3/4 on the destination, you can still safely move ONE site from /1/2/SiteBeingMoved to /1/2/3/4/SiteBeingMoved since its location relative to the site collection has not changed. Sorry if those examples were confusing. And again, your product is great, immensely helpful, and I appreciate you taking the time to respond to my comments. -Kyle @Kyle, Happy to help! I had to give this one some thought, but yes you're right - because the path within the site collection is not changing, this *isn't* a reparenting operation. Consequently you shouldn't specify an Import Web URL. It does get slightly tricky thinking some of these scenarios through, but something which simplifies it is remembering that SharePoint's Content Deployment framework is based on the idea of creating an exact mirror between source/destination. When you pick up some content, it has a reference to the path within the site collection - any time you change that, you are reparenting and need to tell it where the new path is via the Import Web URL. HTH, Chris. Hi Chris Love your tool. I was able to easily copy a list from one site to another. One thing I keep getting errors with is when I try to do the export of one item from a list. The error message says the list item does not exist. Any idea of what I might be doing wrong? Thanks Jennifer @Jennifer, It sounds like you're specifying 'Retain object IDs and locations' - this would cause the import to look for the list by ID, and maybe the list doesn't have the same ID as where you exported the item from. What happens if you try again without this checkbox checked? Thanks, Chris. Hi Chris Thanks for the reply. The issue I was having was getting errors when trying to export one list item. I think it is an issue with this particular list since this site has a lot of problems. I was able to export the whole list and import to another site. I then tried to do an export of one item from this new site and didn't have any issues. So, I am set. Thanks Jennifer Thank you so much for this tool Chris, it saved my life. After spending considerable time trying to get test and live environments to match up using the microsoft way and hitting the most un helpful errors, your tool came to the rescue and did it one. Thank you for this, an amazing piece of software. Have problem with import of documentlibrary or customlist in moss 2007, sp2 installed. Trying to export document library from one site collection to another. import log, says FatalError: Specified cast is not valid.() works fine in sharepoint foundation 2010. what could be the problem.
http://www.sharepointnutsandbolts.com/2007/12/using-sharepoint-content-deployment.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+ChrisObrien+%28Chris+O%27Brien+%5BMVP+SharePoint%5D%29
CC-MAIN-2015-14
refinedweb
7,078
72.36
query the pathname prefix tree #include <sys/prfx.h> int qnx_prefix_query( nid_t nid, char *path, char *buffer, int len ); The qnx_prefix_query() function returns the prefix tree below path on node nid, in buffer. The data in buffer is returned as a string and limited to len characters. If path is "" then the entire prefix string is returned in the form: [prefix=string[:prefix=string] ... ] For example, /=//1/:/dev=8,a where the square brackets aren't present, but indicate that the item enclosed is optional. The string is either an alias, such as /=//1/, or a resource manager mapping, such as /dev=8,a, where 8 is the process id, and a is the unit number. If path isn't "", then a list of directories in the prefix tree immediately below the path is returned in the following form: [dirname[\ndirname] ... ] For example, where path = "/": dev This function may set errno to any of the values listed for qnx_vc_attach(). See qnx_prefix_attach(). QNX errno, qnx_prefix_attach(), qnx_prefix_detach(), qnx_vc_attach()
https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/qnx/qnx_prefix_query.html
CC-MAIN-2022-33
refinedweb
166
62.68
In a stock market, there is a product with its infinite stocks. The stock prices are given for N days, where arr[i] denotes the price of the stock on the ith day. There is a rule that a customer can buy at most i stock on the ith day. If the customer has an amount of k amount of money initially, find out the maximum number of stocks a customer can buy. For example, for 3 days the price of a stock is given as 7, 10, 4. You can buy 1 stock worth 7 rs on day 1, 2 stocks worth 10 rs each on day 2 and 3 stock worth 4 rs each on day 3. Examples: Input : price[] = { 10, 7, 19 }, k = 45. Output : 4 A customer purchases 1 stock on day 1, 2 stocks on day 2 and 1 stock on day 3 for 10, 7 * 2 = 14 and 19 respectively. Hence, total amount is 10 + 14 + 19 = 43 and number of stocks purchased is 4. Input : price[] = { 7, 10, 4 }, k = 100. Output : 6 The idea is to use greedy approach, where we should start buying product from the day when the stock price is least and so on. So, we will sort the pair of two values i.e { stock price, day } according to the stock price, and if stock prices are same, then we sort according to the day. Now, we will traverse along the sorted list of pairs, and start buying as follows: Let say, we have R rs remaining till now, and the cost of product on this day be C, and we can buy atmost L products on this day then, total purchase on this day (P) = min(L, R/C) Now, add this value to the answer. total purchase on this day (P) = min(L, R/C) Now, add this value to the answer total_purchase = total_purchase + P, where P =min(L, R/C) Now, substract the cost of buying P items from remaining money, R = R – P*C. Total number of products that we can buy is equal to total_purchase. Below is C++ implementation of this approach: // CPP program to find maximum number of stocks that // can be bought with given constraints. #include <bits/stdc++.h> using namespace std; // Return the maximum stocks int buyMaximumProducts(int n, int k, int price[]) { vector<pair<int, int> > v; // Making pair of product cost and number // of day.. for (int i = 0; i < n; ++i) v.push_back(make_pair(price[i], i + 1)); // Sorting the vector pair. sort(v.begin(), v.end()); // Calculating the maximum number of stock // count. int ans = 0; for (int i = 0; i < n; ++i) { ans += min(v[i].second, k / v[i].first); k -= v[i].first * min(v[i].second, (k / v[i].first)); } return ans; } // Driven Program int main() { int price[] = { 10, 7, 19 }; int n = sizeof(price)/sizeof(price[0]); int k = 45; cout << buyMaximumProducts(n, k, price) << endl; return 0; } Output: 4 Time Complexity :O(nlogn).: - Job Scheduling with two jobs allowed at a time - Greedy Algorithms | Set 1 (Activity Selection Problem) - Minimum Swaps for Bracket Balancing - Scheduling priority tasks in limited time and minimizing loss -.
https://www.geeksforgeeks.org/buy-maximum-stocks-stocks-can-bought-th-day/
CC-MAIN-2018-34
refinedweb
533
78.28
import a bunch of pkgsrc articles from the old pkgsrc.se wiki **This page should use cross references to avoid duplicate content. Please help us by cleaning it up. ?** **Contents** [[!toc levels=2]] #Synopsis HP-UX is a version of Unix for HP's PA-RISC and Integrity line of servers and workstations. HP-UX 11.x versions are pretty well supported by pkgsrc and it's also quite usable on 10.20. #Preparations ##pkgsrc Simply download the pkgsrc snapshot tarball as you would do on other architectures. You can also use CVS if its avalible. XXX TODO: explain in pkgsrc page and link to there. ##Patches Read Readme.HPUX for the required patches and prerequisites. ##Compiler You will need a compiler which can be HP's ANSI C/C++ compiler or GCC, which is availible [from HP]() or other third parties. ##Bootstrap Bootstrapping is done the usual way. CC=path_to CXX=path_to ./bootstrap --abi 32 --compiler gcc XXX TODO: explain in pkgsrc page and link to there. #Audio Audio playback works pretty well on Series 700 workstations through HP Audio and esound. You will need to install the following depot beforehand: B6865AAA -- HP Audio Clients for Series 700 - English You can also use libao-esd with packages which support libao. #See also * [README.HPUX]() * [[Hardware/HP-UX TODO List]]
https://wiki.netbsd.org/cgi-bin/cvsweb/wikisrc/pkgsrc/how_to_use_pkgsrc_on_hp-ux.mdwn?rev=1.1;content-type=text%2Fx-cvsweb-markup
CC-MAIN-2016-22
refinedweb
220
67.86
An Excel Programmability blog by Gabhan Berry As well as C/C++ and VBA, I'll be blogging a lot about managed code. So I figured it would be useful to lay out the basics of how Excel and managed code interoperate today. If you write Excel addins you’ve probably seen articles like this one that show you how you can write your addin in C#. You will have used Visual Studio’s Extensibility Project template to build a simple “Hello, Excel” addin in C# with nothing more than a few clicks of the mouse. I remember the first time I did this too. I remember adding a Messagebox.Show(“Does this really work?”); line to the wizard generated OnConnection method then tentatively pressing F5 not quite sure what I expected to happen. Well (of course) it all worked. Excel started; loaded my addin; my message box got displayed. I was amazed. How was this happening? So I looked at the source code the wizard had generated for me and noticed there were a few things I didn’t understand. I mean, I was used to writing COM code and could recognise ProgIDs and CLSIDs in the code and could make obvious statements like – “Oh, that’s the ProgID of my addin” while hoping that no one followed that up with “How does that ProgID get mapped to your managed code?”. If you’re like me you like to understand what your code’s doing. I have nothing against wizard generated code (it can save a lot of time) but I still like to be able to read the generated code and know what it is doing and why it is doing it. So I asked myself: How come Excel can use an addin written entirely in managed code? COM Addin Basics I guess a good place to start is by looking at what code gets generated for us. Once we've created our new shared addin project (File->New->Project->Other Project Type->Extensibility->Shared Addin) in Visual Studio we're presented with a solution containing two projects: the addin and a setup project. Let's ignore the setup project for now. In the addin's project, there is a Connect.cs file containing a class called Connect. This class has some interesting attributes: Now, if you've written COM addins before you'll likely recognise a few things here. If you're not familiar with COM then these attributes need explaining a bit. The GuidAttribute contains, well, a Guid. I'm not going to explain what a guid is other than to say that it's a (g)lobally (u)nique (id)entifier. COM relies on guids to identify classes and interfaces. Every COM class and every COM interface has a guid. Additionally, COM uses another identifying value called a ProgID (programmatic identifier). Again, I'm not going to go into ProgIDs. There is endless information on the web covering this subject. So all we need to understand about COM (for now) is that a COM class has a Guid and a ProgID. The Guid is a unique identifier for the class and the ProgID is what we use to create an instance of the class. When we register our COM addin with Excel, Excel stores the ProgID of our addin in the registry (more on this later). When Excel starts, it reads the ProgID from the registry and uses it to create an instance of our addin. But there is more to writing a COM addin than this. Excel needs a way to call our addin, for example to get the addin to initialise itself. So Excel requires that all COM addins implement specific methods. They can, of course, implement additional methods - but they need to implement at least these specific methods in order for Excel to be able to interact with it. These methods are specified in the IDTExtensibility2 interface. The IDTExtensibility2 is documented here. You'll notice that the wizard automatically generated the code to implement IDTExtensibility2 for us. This sounds like COM stuff ... but I want a Managed Addin If you hadn't guessed it by now, a managed addin is really a COM addin written in managed code. The managed addin needs to support the same things that COM addins do and Excel treats it in the same way. In fact, Excel doesn't even know your addin is written in managed code. It simply makes a call to the COM libraries for an instance of your addin's ProgID and gets back a pointer. All the magic that makes this happen isn't in Excel; its in the .NET CLR and is called COM Interop. The CLR creates a COM Callable Wrapper (CCW) of your addin and it is this CCW that Excel thinks is your addin (CCW's are covered in this article). The fact that an addin written in C# is really a COM addin is a subtle but important concept to grasp. Excel does not have a managed API - it has a COM API. This means that whenever you call Excel from managed code you are using the COM Interop facilities of the CLR. Over time, I'll be covering why we need to care about COM Interop. In the meantime, here's a good article. Calling Excel's API from Managed Code Like I said, Excel's API is COM based but we can still call it from managed code. When managed code calls unmanaged COM code, the CLR uses a runtime callable wrapper (RCW). This wrapper handles the transitions between the managed world and the unmanaged world. RCWs are implemented in .NET assembly files and these files are called Interop Assemblies. Excel ships Primary Interop Assemblies (PIAs). A PIA is a normal interop assembly that has been marked by its vendor as being the one everyone should use. So, if a COM library (like Excel) offers a PIA, you should use that rather than generating your own interop assemblies. There is a little more to PIAs than this, but we don't need to care that much for now. More details on PIAs can be found here and details of the Office PIAs are here. From managed code, PIAs look like any other managed code. To call the Excel PIAs (and hence call Excel via its COM API via its RCWs by way of its PIAs :o) ) you add a reference to the PIAs. This is done in Visual Studio using the Add Reference dialogue shown below. Once we've done this, we can make calls to Excel from our managed addin. Excel's RCWs are in a namspace called: Microsoft.Office.Interop.Excel. This is a bit of a mouthful so sticking a: using Excel = Microsoft.Office.Interop.Excel; statement at the top of your source files means that you can access the RCWs via the Excel namespace i.e. instead of: Microsoft.Office.Interop.Excel.Application you can type: Excel.Application. The Visual Studio wizard doesn't reference the Excel PIAs for us so this is something we need to do manually. COM Addins and the Registry The last main area we should introduce is the registry. Excel stores the ProgIDs of all its COM addins under the HKCU\Software\Microsoft\Office\Excel\Addins. There is a key for each ProgID and subkeys which tell Excel when the addin should be loaded. For your managed code addin, you need to have the same entries. That is, you need to have a key with a value of your addin's ProgID (i.e. MyAddin.Connect) along with the subkeys as detailed here. Summary briefly covered the main topics of writing an Excel addin in managed code. The following are the high level points we should remember about managed addins: and finally: If you would like to receive an email when updates are made to this post, please register here RSS When coding in C# with Excel, it doesn't take long before you encounter the dreaded 'optional parameter' After I posted about getting up-and-running with managed code and Excel , I realised that I was really When presented with a table of data in Excel, sometimes it is useful to be able to learn some quick facts
http://blogs.msdn.com/gabhan_berry/archive/2008/01/30/excel-and-managed-code-how-does-that-work.aspx
crawl-002
refinedweb
1,383
72.26
In recent years, it has become clear that HTTP is not just for serving up HTML pages. It is also a powerful platform for building Web APIs, using a handful of verbs (GET, POST, and so forth) plus a few simple concepts such as URIs and headers. ASP.NET Web API is a set of components that simplify HTTP programming. Because it is built on top of the ASP.NET MVC runtime, Web API automatically handles the low-level transport details of HTTP. At the same time, Web API naturally exposes the HTTP programming model. In fact, one goal of Web API is to not abstract away the reality of HTTP. As a result, Web API is both flexible and easy to extend. In this hands-on lab, you will use Web API to build a simple REST API for a contact manager application. You will also build a client to consume the API. The REST architectural style has proven to be an effective way to leverage HTTP - although it is certainly not the only valid approach to HTTP. The contact manager will expose the RESTful for listing, adding and removing contacts, among others. This lab requires a basic understanding of HTTP, REST, and assumes you have a basic working knowledge of HTML, JavaScript, and jQuery. Note:. ASP.NET Web API, similar to ASP.NET MVC 4, has great flexibility in terms of separating the service layer from the controllers allowing you to use several of the available Dependency Injection frameworks fairly easy. There is a good sample in MSDN that shows how to use Ninject for dependency injection in an ASP.NET Web API project that you can download it from here. All sample code and snippets are included in the Web Camps Training Kit, available at. Objectives In this hands-on lab, you will learn how to: Implement a RESTful Web API Call the API from an HTML client Prerequisites The following is required to complete this hands-on lab: - Microsoft Visual Studio Express 2012 for Web or superior (read Appendix B for instructions on how to install it). Setup Installing Code Snippets For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. To install the code snippets run .\Source\Setup\CodeSnippets.vsi file. If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document "Appendix A: Using Code Snippets". Exercises This hands-on lab includes the following exercise: Exercise 1: Create a Read-Only Web API Exercise 2: Create a Read/Write Web API Exercise 3: Consume the Web API from an HTML Client Note: Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises. Estimated time to complete this lab: 60 minutes. Exercise 1: Create a Read-Only Web API In this exercise, you will implement the read-only GET methods for the contact manager. Task 1 - Creating the API Project In this task, you will use the new ASP.NET web project templates to create a Web API web application. Run Visual Studio 2012 Express for Web, to do this go to Start and type VS Express for Web then press Enter. From the File menu, select New Project. Select the Visual C# | Web project type from the project type tree view, then select the ASP.NET MVC 4 Web Application project type. Set the project's Name to ContactManager and the Solution name to Begin, then click OK. Creating a new ASP.NET MVC 4.0 Web Application Project In the ASP.NET MVC 4 project type dialog, select the Web API project type. Click OK. Specifying the Web API project type Task 2 - Creating the Contact Manager API Controllers In this task, you will create the controller classes in which API methods will reside. Delete the file named ValuesController.cs within Controllers folder from the project. Right-click the Controllers folder in the project and select Add | Controller from the context menu. Adding a new controller to the project In the Add Controller dialog that appears, select Empty API Controller from the Template menu. Name the controller class ContactController. Then, click Add. Using the Add Controller dialog to create a new Web API controller Add the following code to the ContactController. (Code Snippet - Web API Lab - Ex01 - Get API Method)C# public string[] Get() { return new string[] { "Hello", "World" }; } Press F5 to debug the application. The default home page for a Web API project should appear. The default home page of an ASP.NET Web API application In the Internet Explorer window, press the F12 key to open the Developer Tools window. Click the Network tab, and then click the Start Capturing button to begin capturing network traffic into the window. Opening the network tab and initiating network capture Append the URL in the browser's address bar with /api/contact and press enter. The transmission details will appear in the network capture window. Note that the response's MIME type is application/json. This demonstrates how the default output format is JSON. Viewing the output of the Web API request in the Network view Note: Internet Explorer 10's default behavior at this point will be to ask if the user would like to save or open the stream resulting from the Web API call. The output will be a text file containing the JSON result of the Web API URL call. Do not cancel the dialog in order to be able to watch the response's content through Developers Tool window. Click the Go to detailed view button to see more details about the response of this API call. Switch to Detailed View Click the Response body tab to view the actual JSON response text. Viewing the JSON output text in the network monitor Task 3 - Creating the Contact Models and Augment the Contact Controller In this task, you will create the controller classes in which API methods will reside. Right-click the Models folder and select Add | Class... from the context menu. Adding a new model to the web application In the Add New Item dialog, name the new file Contact.cs and click Add. Creating the new Contact class file Add the following highlighted code to the Contact class. (Code Snippet - Web API Lab - Ex01 - Contact Class)C# public class Contact { public int Id { get; set; } public string Name { get; set; } } In the ContactController class, select the word string in method definition of the Get method, and type the word Contact. Once the word is typed in, an indicator will appear at the beginning of the word Contact. Either hold down the Ctrl key and press the period (.) key or click the icon using your mouse to open up the assistance dialog in the code editor, to automatically fill in the using directive for the Models namespace. Using Intellisense assistance for namespace declarations Modify the code for the Get method so that it returns an array of Contact model instances. (Code Snippet - Web API Lab - Ex01 - Returning a list of contacts)C# public Contact[] Get() { return new Contact[] { new Contact { Id = 1, Name = "Glenn Block" }, new Contact { Id = 2, Name = "Dan Roth" } }; } Press F5 to debug the web application in the browser. To view the changes made to the response output of the API, perform the following steps. - Once the browser opens, press F12 if the developer tools are not open yet. - Click the Network tab. - Press the Start Capturing button. - Add the URL suffix /api/contact to the URL in the address bar and press the Enter key. - Press the Go to detailed view button. - Select the Response body tab. You should see a JSON string representing the serialized form of an array of Contact instances.. Create a new folder in the solution root and name it Services. To do this, right-click ContactManager project, select Add | New Folder, name it Services. Creating Services folder Right-click the Services folder and select Add | Class... from the context menu. Adding a new class to the Services folder When the Add New Item dialog appears, name the new class ContactRepository and click Add. Creating a class file to contain the code for the Contact Repository service layer Add a using directive to the ContactRepository.cs file to include the models namespace.C# using ContactManager.Models; Add the following highlighted code to the ContactRepository.cs file to implement GetAllContacts method. (Code Snippet - Web API Lab - Ex01 - Contact Repository)C# public class ContactRepository { public Contact[] GetAllContacts() { return new Contact[] { new Contact { Id = 1, Name = "Glenn Block" }, new Contact { Id = 2, Name = "Dan Roth" } }; } } Open the ContactController.cs file if it is not already open. Add the following using statement to the namespace declaration section of the file.C# using ContactManager.Services; Add the following highlighted code to the ContactController.cs class to add a private field to represent the instance of the repository, so that the rest of the class members can make use of the service implementation. (Code Snippet - Web API Lab - Ex01 - Contact Controller)C# public class ContactController : ApiController { private ContactRepository contactRepository; public ContactController() { this.contactRepository = new ContactRepository(); } ... } Change the Get method so that it makes use of the contact repository service. (Code Snippet - Web API Lab - Ex01 - Returning a list of contacts via the repository)C# public Contact[] Get() { return contactRepository.GetAllContacts(); } Put a breakpoint on the ContactController's Get method definition. Adding breakpoints to the contact controller Press F5 to run the application. When the browser opens, press F12 to open the developer tools. Click the Network tab. Click the Start Capturing button. Append the URL in the address bar with the suffix /api/contact and press Enter to load the API controller. Visual Studio 2012 should break once Get method begins execution. Breaking within the Get method Press F5 to continue. Go back to Internet Explorer if it is not already in focus. Note the network capture window. Network view in Internet Explorer showing results of the Web API call Click the Go to detailed view button. Click the Response body tab. Note the JSON output of the API call, and how it represents the two contacts retrieved by the service layer. Viewing the JSON output from the Web API in the developer tools window Exercise 2: Create a Read/Write Web API In this exercise, you will implement POST and PUT methods for the contact manager to enable it with data-editing features. Task 1 - Opening the Web API Project In this task, you will prepare to enhance the Web API project created in Exercise 1 so that it can accept user input. Run Visual Studio 2012 Express for Web, to do this go to Start and type VS Express for Web then press Enter. Open the Begin solution located at Source/Ex02-ReadWriteWeb Services/ContactRepository.cs file. Task 2 - Adding Data-Persistence Features to the Contact Repository Implementation In this task, you will augment the ContactRepository class of the Web API project created in Exercise 1 so that it can persist and accept user input and new Contact instances. Add the following constant to the ContactRepository class to represent the name of the web server cache item key name later in this exercise.C# private const string CacheKey = "ContactStore"; Add a constructor to the ContactRepository containing the following code. (Code Snippet - Web API Lab - Ex02 - Contact Repository Constructor)C# public ContactRepository() { var ctx = HttpContext.Current; if (ctx != null) { if (ctx.Cache[CacheKey] == null) { var contacts = new Contact[] { new Contact { Id = 1, Name = "Glenn Block" }, new Contact { Id = 2, Name = "Dan Roth" } }; ctx.Cache[CacheKey] = contacts; } } } Modify the code for the GetAllContacts method as demonstrated below. (Code Snippet - Web API Lab - Ex02 - Get All Contacts)C# public Contact[] GetAllContacts() { var ctx = HttpContext.Current; if (ctx != null) { return (Contact[])ctx.Cache[CacheKey]; } return new Contact[] { new Contact { Id = 0, Name = "Placeholder" } }; } Note: This example is for demonstration purposes and will use the web server's cache as a storage medium, so that the values will be available to multiple clients simultaneously, rather than use a Session storage mechanism or a Request storage lifetime. One could use Entity Framework, XML storage, or any other variety in place of the web server cache. Implement a new method named SaveContact to the ContactRepository class to do the work of saving a contact. The SaveContact method should take a single Contact parameter and return a Boolean value indicating success or failure. (Code Snippet - Web API Lab - Ex02 - Implementing the SaveContact Method)C# public bool SaveContact(Contact contact) { var ctx = HttpContext.Current; if (ctx != null) { try { var currentData = ((Contact[])ctx.Cache[CacheKey]).ToList(); currentData.Add(contact); ctx.Cache[CacheKey] = currentData.ToArray(); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } } return false; } Exercise 3: Consume the Web API from an HTML Client In this exercise, you will create an HTML client to call the Web API. This client will facilitate data exchange with the Web API using JavaScript and will display the results in a web browser using HTML markup. Task 1 - Modifying the Index View to Provide a GUI for Displaying Contacts In this task, you will modify the default Index view of the web application to support the requirement of displaying the list of existing contacts in an HTML browser. Open Visual Studio 2012 Express for Web if it is not already open. Open the Begin solution located at Source/Ex03-ConsumingWeb Index.cshtml file located at Views/Home folder. Replace the HTML code within the div element with id body so that it looks like the following code.HTML <div id="body"> <ul id="contacts"></ul> </div> Add the following Javascript code at the bottom of the file to perform the HTTP request to the Web API.HTML @section scripts{ <script type="text/javascript"> $(function() { $.getJSON('/api/contact', function(contactsJsonPayload) { $(contactsJsonPayload).each(function(i, item) { $('#contacts').append('<li>' + item.Name + '</li>'); }); }); }); </script> } Open the ContactController.cs file if it is not already open. Place a breakpoint on the Get method of the ContactController class. Placing a breakpoint on the Get method of the API controller Press F5 to run the project. The browser will load the HTML document. Note: Ensure that you are browsing to the root URL of your application. Once the page loads and the JavaScript executes, the breakpoint will be hit and the code execution will pause in the controller. Debugging into the Web API call using Visual Studio 2012 Express for Web Remove the breakpoint and press F5 or the debugging toolbar's Continue button to continue loading the view in the browser. Once the Web API call completes you should see the contacts returned from the Web API call displayed as list items in the browser. Results of the API call displayed in the browser as list items Stop debugging. Task 2 - Modifying the Index View to Provide a GUI for Creating Contacts In this task, you will continue to modify the Index view of the MVC application. A form will be added to the HTML page that will capture user input and send it to the Web API to create a new Contact, and a new Web API controller method will be created to collect date from the GUI. Open the ContactController.cs file. Add a new method to the controller class named Post as shown in the following code. (Code Snippet - Web API Lab - Ex03 - Post Method)C# public HttpResponseMessage Post(Contact contact) { this.contactRepository.SaveContact(contact); var response = Request.CreateResponse<Contact>(System.Net.HttpStatusCode.Created, contact); return response; } Open the Index.cshtml file in Visual Studio if it is not already open. Add the HTML code below to the file just after the unordered list you added in the previous task.HTML <form id="saveContactForm" method="post"> <h3>Create a new Contact</h3> <p> <label for="contactId">Contact Id:</label> <input type="text" name="Id" /> </p> <p> <label for="contactName">Contact Name:</label> <input type="text" name="Name" /> </p> <input type="button" id="saveContact" value="Save" /> </form> Within the script element at the bottom of the document, add the following highlighted code to handle button-click events, which will post the data to the Web API using an HTTP POST call.JavaScript <script type="text/javascript"> ... $('#saveContact').click(function() { $.post("api/contact", $("#saveContactForm").serialize(), function(value) { $('#contacts').append('<li>' + value.Name + '</li>'); }, "json" ); }); </script> In ContactController.cs, place a breakpoint on the Post method. Press F5 to run the application in the browser. Once the page is loaded in the browser, type in a new contact name and Id and click the Save button. The client HTML document loaded in the browser When the debugger window breaks in the Post method, take a look at the properties of the contact parameter. The values should match the data you entered in the form. The Contact object being sent to the Web API from the client Step through the method in the debugger until the response variable has been created. Upon inspection in the Locals window in the debugger, you'll see that all the properties have been set. The response following creation in the debugger If you press F5 or click Continue in the debugger the request will complete. Once you switch back to the browser, the new contact has been added to the list of contacts stored by the ContactRepository implementation. The browser reflects successful creation of the new contact instance Note: Additionally, you can deploy this application to Azure following Appendix C: Publishing an ASP.NET MVC 4 Application using Web Deploy. Summary This lab has introduced you to the new ASP.NET Web API framework and to the implementation of RESTful Web API's using the framework. From here, you could create a new repository that facilitates data persistence using any number of mechanisms and wire that service up rather than the simple one provided as an example in this lab. Web API supports a number of additional features, such as enabling communication from non-HTML clients written in any language that supports HTTP and JSON or XML. The ability to host a Web API outside of a typical web application is also possible, as well as is the ability to create your own serialization formats.. Appendix A: Using Code Snippets With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them, as shown in the following figure. Using Visual Studio code snippets to insert code into your project To add a code snippet using the keyboard (C# only) Place the cursor where you would like to insert the code. Start typing the snippet name (without spaces or hyphens). Watch as IntelliSense displays matching snippets' names. Select the correct snippet (or keep typing until the entire snippet's name is selected). Press the Tab key twice to insert the snippet at the cursor location. Start typing the snippet name Press Tab to select the highlighted snippet Press Tab again and the snippet will expand To add a code snippet using the mouse (C#, Visual Basic and XML) Right-click where you want to insert the code snippet. Select Insert Snippet followed by My Code Snippets. Pick the relevant snippet from the list, by clicking on it. Right-click where you want to insert the code snippet and select Insert Snippet Pick the relevant snippet from the list, by clicking on it Appendix B: Installing Visual Studio Express 2012 for Web You can install Microsoft Visual Studio Express 2012 for Web or another "Express" version using the Microsoft Web Platform Installer. The following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer. Go to. Alternatively, if you already have installed Web Platform Installer, you can open it and search for the product "Visual Studio Express 2012 for Web with Azure SDK". Click on Install Now. If you do not have Web Platform Installer you will be redirected to download and install it first. Once Web Platform Installer is open, click Install to start the setup. Install Visual Studio Express Read all the products' licenses and terms and click I Accept to continue. Accepting the license terms Wait until the downloading and installation process completes. Installation progress When the installation completes, click Finish. Installation completed Click Exit to close Web Platform Installer. To open Visual Studio Express for Web, go to the Start screen and start writing "VS Express", then click on the VS Express for Web tile. VS Express for Web tile Appendix C: Publishing an ASP.NET MVC 4 Application using Web Deploy This appendix will show you how to create a new web site from the Azure Portal and publish the application you obtained by following the lab, taking advantage of the Web Deploy publishing feature provided by Azure. Task 1 - Creating a New Web Site from the Azure Portal Go to the Azure Management Portal and sign in using the Microsoft credentials associated with your subscription. Note: With Azure you can host 10 ASP.NET Web Sites for free and then scale as your traffic grows. You can sign up here. Log on to Portal Click New on the command bar. Creating a new Web Site Click Compute | Web Site. Then select Quick Create option. Provide an available URL for the new web site and click Create Web Site. Note: Azure is the host for a web application running in the cloud that you can control and manage. The Quick Create option allows you to deploy a completed web application to the Azure from outside the portal. It does not include steps for setting up a database.. Opening the Web Site management pages In the Dashboard page, under the quick glance section, click the Download publish profile link. Note: The publish profile contains all of the information required to publish a web application to a Azure for each enabled publication method. The publish profile contains the URLs, user credentials and database strings required to connect to and authenticate against each of the endpoints for which a publication method is enabled. Microsoft WebMatrix 2, Microsoft Visual Studio Express for Web and Microsoft Visual Studio 2012 support reading publish profiles to automate configuration of these programs for publishing web applications to Azure. Downloading the Web Site publish profile Download the publish profile file to a known location. Further in this exercise you will see how to use this file to publish a web application to Azure from Visual Studio. Saving the publish profile file Task 2 - Configuring the Database Server If your application makes use of SQL Server databases you will need to create a SQL Database server. If you want to deploy a simple application that does not use SQL Server you might skip this task. You will need a SQL Database server for storing the application database. You can view the SQL Database servers from your subscription in the Azure Management portal at Sql Databases | Servers | Server's Dashboard. If you do not have a server created, you can create one using the Add button on the command bar. Take note of the server name and URL, administrator login name and password, as you will use them in the next tasks. Do not create the database yet, as it will be created in a later stage. SQL Database Server Dashboard In the next task you will test the database connection from Visual Studio, for that reason you need to include your local IP address in the server's list of Allowed IP Addresses. To do that, click Configure, select the IP address from Current Client IP Address and paste it on the Start IP Address and End IP Address text boxes). Web deploy configuration Configure the database connection as follows: - In the Server name type your SQL Database server URL using the tcp: prefix. - In User name type your server administrator login name. - In Password type your server administrator login password. - Type a new database name, for example: MVC4SampleDB. Azure This article was originally created on February 18, 2013
http://www.asp.net/web-api/overview/older-versions/build-restful-apis-with-aspnet-web-api
CC-MAIN-2015-48
refinedweb
4,062
63.39
Add a carriage return \r and linefeed \n to the beginning of a sentence using a regular expression without replacing the text - Michael Poplawski last edited by The Following text has a carriage return (\r) and line feed (\n) after certain sentences or paragraphs. As can be seen in the following text, paragraph 28. has space before the paragraph. Paragraph 29 does not have space at the beginning of the sentence. I want to use Regular Expressions in notepad++ to find these sentences then add a \r\n to the beginning of sentences that do not have any space. I don’t want to replace the text found; just find the paragraph marker and add carriage return / line feed to the beginning. Here is my regular expression in the Find what box: [\r\n]{1}+[\d]{1,2}.\s\w My pseudocode is as follows: find the single carriage return / line feed, followed by 1 or 2 digit number, followed by period, followed by space, following by single character. I don’t know what to enter in the Replace with box? Any help is greatly appreciated. inequality and income inequality go hand in hand. In many EMDCs, low-income households and available financial products tend to be more limited and relatively costly. IV. INEQUALITY DRIVERS A. Factors Driving Higher Income Inequality - Global trends: the good side of the story. Over the past four decades, technology has reduced the costs of transportation, improved automation, and communication dramatically. New markets have opened, bringing growth opportunities in countries rich and poor alike, and hundreds of millions of people have been lifted out of poverty. However, inequality has also risen, possibly reflecting the fact that growth has been accompanied by skill-biased technological change, or because other aspects of the growth process have generated higher inequality. In this section, we discuss potential global and country-specific drivers of income inequality across countries. - Technological change. New information technology has led to improvements in productivity and well-being by leaps and bounds, but has also played a central role in driving up the skill premium, resulting in increased labor income inequality (Figure 15). This is because technological changes can disproportionately raise the demand for capital and skilled labor over low-skilled and unskilled labor by eliminating many jobs through automation or upgrading the skill - Scott Sumner last edited by Scott Sumner Not sure why this was downvoted…are regex questions becoming hated here? I guess I can see that, although they don’t bother me (like HTML/CSS questions do!) Anyway, to try and help without reading too much into what you really want (or maybe I am), try: Find what zone: ([^\r\n]\R)(\d\d?\.\s.) Replace with zone: \1\r\n\2 Hi, michael-poplawski, @Scott-sumner and All, Just a variant of the Scott’s solution : SEARCH [^\r\n](?=\R\h*\d+\.\h+) REPLACE $0\r\n Notes : The searched string is, essentially, the part [^\r\n], which represents any single character, different from, either, the Carriage Return and the New Line characters But the regex engine will consider this match ONLY IF the positive look-ahead (?=\R\h*\d+\.\h+), ending this regex, is true. That is to say, IF it is, immediately followed with a Line Break ( \R), some horizontal blank characters, even 0 ( \h*), at least one digit ( \d+), then a literal dot ( \.) and, finally, at least, one horizontal blank character ( \h+) If this condition is true, in replacement, that single character is, simply, rewritten, due to the $0syntax, with represents the overall match, and followed by the usual \r\nsequence, which defines a Windows line-break ! Best Regards, guy038
https://community.notepad-plus-plus.org/topic/15289/add-a-carriage-return-r-and-linefeed-n-to-the-beginning-of-a-sentence-using-a-regular-expression-without-replacing-the-text
CC-MAIN-2019-51
refinedweb
611
50.87
Powerful insights in business, technology, and software development. If you’ve adopted Linux, chances are you might have done so for development purposes. After all, it has everything you need to program in most languages, and do so for (almost) free. With Linux you can program in some of the most important languages on the planet, such as C++. In fact, with most distributions, there’s very little you have to do to start working on your first program. And what’s better, you can easily write and compile all from the command line. If you’re a lone programmer or you work for a custom software development company like BairesDev, it should take you no time to get up to speed on programming with Linux as your platform of choice. With that said, I want to guide you through the process of writing and compiling your first C++ program on Linux. I’ll demonstrate how this is done on both Ubuntu and Red Hat distributions. What you’ll need The only things you’ll need for this tutorial are: A running instance of a Ubuntu- or Red Hat-based Linux distribution. Some C++ code. And that’s it. I’ll be demonstrating with the tried and true “Hello, World!”. This is an incredibly basic example, but it makes it easy for new users to follow. If you’re unfamiliar with it, all it does is print out the phrase “Hello, World!” on the screen. Installing the necessary tools Although there are some Linux distributions that come with everything you need to start developing (out of the box), you may come across one that doesn’t. Without the right tools, your bespoke software development experience will get frustrating fast. So, how do you install the necessary software? Let’s do this on Ubuntu first. Open a terminal window on your desktop and issue the command: sudo apt-get install build-essential -y In order to do this on Red Hat, you’ll use the dnf command with the groups options like so: sudo dnf group install “Development Tools” Either command will install everything you need to compile your first C++ application. Writing the program Now we need to write the “Hello, World!” program. Because this is a simple application, you can use the Nano editor. Open a terminal window and issue the command: nano hello.cpp That command will create a new file, named hello.cpp, and open it for editing. In that empty file, paste the following text: #include <iostream> using namespace std; int main() { cout << "Hello, World!" \n; return 0; } Save and close the file with the keyboard shortcut [Ctrl]+[X] and then type “y” (no quotes) to use the name we gave the file from the start. At this point you now have your C++ file, hello.cpp, ready to compile. Compiling the program The next step is to compile our newly-written program. The command to do this is really quite simple. The basic command is: g++ hello.cpp That command will compile the program and create an executable file named a.out. Not very helpful, right? So instead of letting g++ name the executable, let’s give it the name hello, by using the output option (-o) with the command: g++ -o hello hello.cpp The above command will compile the hello.cpp file and create a new executable binary, named hello. Running the new program Now that you’ve used g++ to compile your program, it’s time to run it. Because this is a terminal-only application, you have to run it from within the terminal as a command. To do this, issue the command: ./hello When you run the above command, you should see the output of the Hello, World! program (Figure 1).
https://hackernoon.com/writing-and-compiling-c-on-linux-a-how-to-guide-ddi032di
CC-MAIN-2022-40
refinedweb
631
74.19
询问者 DebuggerTypeProxy strange behaviour Hi, in our company we are working on big project which contains multiple data models. We want to make our day to day debugging life easier and we want to simplify data models debug view by using DebuggerTypeProxy attribude on our class. However I think this attribute will make it even worse. Imagine that you have following structure of your class. Wehn you will try to debug code with DebuggerTypeProxy defined on top level following will happen. On first level you will see output from DebuggerTypeProxy which is what we want (simplify overview of type). On next level you can expand RawView which will show original content of the type + you can go to base class definition. And here all the problems will start :). As soon as base class level is extended VS will again show content of runtime type over DebuggerTypeProxy which is really strange and confusing, plus RawView is available again. You need to expand RawView if you want to see content of base type. And this will happen on all the way down to base class. So even if DebuggerTypeProxy is defined on top most level of inheritance VS will show it for each and every child class in inheritance model. This will basically bring one extra level which you need to click for each inheritance level. Again very, very confusing. Second problem is that when you will expand first RavView in inheritance model you will see all content from DerivedClass + expandable acces to base class (which is ok) and you will see also expandable access to top most class for which DebuggerTypeProxy was configured. Again I somehow don't see reason for this behaviour and it's really confusing that in any inheritance level, access to level on which DebuggerTypeProxy is configured will be available. Last problem is related to behaviour described in second point. As for each level you have always access also to top most level something like cyclic dependency will ocure and you will and up with situation where type during debugging don't have end point :). So you can extend it in view over hundreds levels even if inheritance model contains only 2 levels. Without DebugerTypeProxy configured you will be able to expand BaseClass level as very end level. Does anybody know what is the reason for this behaviour ? Because of this we don't want to use this attribute at all as it will bring more confusion that benefits. If there any way how to overcome this behaviour ? E.g. DebugerTypeProxy view will be applied only when type on which attribute is assigned is shown in debugger view. All class in inheritance level will not show this extra level. Also last class in inheritance level should be last expandable level in view and there should be no access to top most level. For me this behaviour sounds like bug in VS handling and visualization but I want to hear some opinions before I will submit bug report. thnx for your help J 问题 全部回复 In my understanding, it is for one type, including the inherit types, not just the current class. DebuggerTypeProxyAttribute specifies a proxy, or stand-in, for a type and changes the way the type is displayed in debugger windows. When you view a variable that has a proxy, the proxy stands in for the original type in the display. For the second question, do you mean this? I have not found any documents talked about the Raw View when there's a DebuggerTypeProxy, but now, I do not think so it would be the product "issue". Mike Zhang[MSFT] MSDN Community Support | Feedback to us Hi Mike, thnx for your opinion to this. I understand that DebuggerTypeProxy is defined per type and runtime type is still same when you are extending base level of class. However still don't see any benefit from that. This brings nothing else than confusion and one extra level which you need to expand on the way down for each base class level. Can you think at least about one benefit which this behaviour will bring ? For that raw view, yes that's what I mean. And again, if this isn't bug what is the benefit from this behaviour ? Can you think at least about one ? thnx J - 已编辑 Julius.Petko 2012年2月28日 10:52 typo fix I have found no documents talked this aspect, but based on my understanding, it can told us which class is used the DebuggerTypeProxy attribute, so that we can know the proxy properties's "owner". namespace ConsoleApplication32 { class Program { public static void MethodABC() { } static void Main(string[] args) { var test = new NextDerivedClass(); } } internal class BaseClass { //[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal string BaseClassProperty { get; set; } //[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal string BaseClassProperty1 { get; set; } internal string BaseClassProperty2 { get; set; } internal string BaseClassProperty3 { get; set; } } internal class DerivedClass:BaseClass { internal string DerivedClassProperty { get; set; } internal string DerivedClassProperty1 { get; set; } internal string DerivedClassProperty2 { get; set; } internal string DerivedClassProperty3 { get; set; } } [DebuggerTypeProxy(typeof(VisualProxy))] internal class NextDerivedClass : DerivedClass { internal string NextDerivedClassProperty { get; set; } internal string NextDerivedClassProperty1 { get; set; } internal string NextDerivedClassProperty2 { get; set; } internal string NextDerivedClassProperty3 { get; set; } } internal class NextNextDerivedClass : NextDerivedClass { internal string NextNextDerivedClassProperty { get; set; } internal string NextNextDerivedClassProperty1 { get; set; } internal string NextNextDerivedClassProperty2 { get; set; } internal string NextNextDerivedClassProperty3 { get; set; } } internal class VisualProxy { private NextDerivedClass classIn; public VisualProxy(NextDerivedClass classIn) { this.classIn = classIn; } public string VisualProxyProperty2 { get { return this.classIn.NextDerivedClassProperty2; } } public string VisualProxyProperty1 { get { return this.classIn.NextDerivedClassProperty1; } } } }And one engineer told me the benefit, "This allows an advanced user to dig for something that they know is there." Mike Zhang[MSFT] MSDN Community Support | Feedback to us - 已编辑 Mike Dos ZhangMicrosoft contingent staff, Moderator 2012年3月1日 6:26 - 已建议为答案 Mike Dos ZhangMicrosoft contingent staff, Moderator 2012年3月1日 6:27 - 取消建议作为答案 Julius.Petko 2012年3月2日 16:07 - I am writing to check the status of the issue on your side. What about this problem now? Would you mind letting us know the result of the suggestions? Mike Zhang[MSFT] MSDN Community Support | Feedback to us Hi, I'm not sure which suggestion you mean. If this is about statment that debugger want to visualize who is "owner" I don't think that this is the reason for the behaviour. I'm going to post this question to Microsoft directly and will come back when I will have their response. J It will be good if you can get more "benefits" information, since I just got one as I provided in my post, "This allows an advanced user to dig for something that they know is there.". Best wishes, Mike Zhang[MSFT] MSDN Community Support | Feedback to us This is an old post... but has anything happened with this? This appears to still be the behavior of the C# debugger in Visual Studio 2013 Update 2. It's a frustrating problem because it makes DebuggerTypeProxy worse than the default scenario for classes that have even a single base class. One of the best use cases of a proxy object (other than for using it with DebuggerBrowsableState.RootHidden on a collection class) would be to collapse a deep object inheritance hierarchy. This isn't just my opinion, see JaredPar's blog post of 2/19/2010 for proof that this is a use case desired by Visual Studio MVPs: The "feature" that causes the proxy objects to be repetitively displayed completely undermines this use case for no reason. Seeing the proxy object again every time you expand a "base" node for the same object provides absolutely no value. It pointlessly wastes clicks and screen real estate. There is no valid reason to display a proxy ("stand-in") object more than one time for a single object in a single tree displayed in a variable window. Arguing otherwise is just silly.
https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/71d3c0b0-6855-4d57-93c3-5455ccc000de/debuggertypeproxy-strange-behaviour?forum=vsdebug
CC-MAIN-2015-22
refinedweb
1,299
60.95
Document To Do: add some concrete examples! Contents - Background and Terminology - Managing Overlap - Fallback Procedures - Choice: What Fallback Mechanisms Are Mandated? - Choice: Where Is The Extension Metadata? - Choice: How complex an impact structure? - Random Questions - Strawman - Example Extensions - References 1. Background and Terminology 1.1. Basic Terms A RIF Document is an XML document with a root element called "Document" in the RIF namespace (). In general, RIF documents are expected to convey machine-processible rules, data for use with rules, and metadata about rules. A RIF System is anything which might produce or consume a RIF Document. Typical RIF systems include rule authoring tools and rule engines. These systems may consist of a non-RIF subsystem and a RIF translation subsystem; taken as a whole, they form a RIF system. A RIF Dialect is an XML language for RIF Documents. Each RIF Dialect defines semantics for the set of RIF Documents which conform to its syntax definition. Dialects may overlap other dialects; that is, a given document may be an expression in multiple dialects at the same time. A Language Conflict occurs when multiple dialects specify different meanings for the same document. That is, if there can exist a RIF Document which syntatically conforms to two dialects, and a system can be conformant to one of the dialects without also being conformant to the other, then there is a language conflict between the dialects. A RIF Extension is a set of changes to one dialect (the "base" dialect) which produce another dialect (the "extended" dialect), where the extended dialect is a superset of the base dialect. A RIF Profile is the complement of a RIF Extension; it is a set of changes to one dialect (the "base" dialect) which produce another dialect (the "profile" dialect), where the profile dialect is a subset of the base dialect. A system is Backward Compatible if it accepts old versions of its input language. All systems are backward compatible for languages which change only by incorporating extensions (that is, by growning). In a large, decentralized system (like the Web), backward compatibility is extremly important because new system will almost certainly have to read old-version data (either old documents, or documents recently written by old software). A system is Forward Compatible if it behaves well when given input in future or unknown languages. In a large, decentralized system (like the Web), if the systems are not all forward compatible, new language versions are extremely difficult to deploy. Systems which are not forward compatible will behave badly when they encounter new-version data, so the users of these systems will tend to push back on the people trying to publish the new-version data. If a large enough fraction of the user base is using such systems, the push back becomes too great and migration to new versions is prevented. In small, controlled environments, the software for all the users can be upgraded at once, but that is not practical on the Web. A Fallback mechanism provides forward compatibility by defining a transformation by which any RIF document in an unknown (or simply unimplemented) dialect can be converted into a RIF document in an implemented dialect. In many cases, fallback transformations will have to be defined to be lossy (changing the semantics of the document). Fallback mechanisms can be simple, like saying that certain kinds of unrecognized language constructs are to be ignored (as in CSS), or they can be complex, invoking a Turing complete processor (as in XForms-Tiny). Impact is information about the type and degree of change performed by a fallback transformation. For instance, a fallback transformation which affects performance might be handled differently from one which will cause different results to be produced. This difference is considered impact information. 1.2. Extensibility An Invisible Extension defines a dialect which has exactly the same syntax as some other dialect but different semantics. This is sometimes desirable when the different semantics are related in a practical and useful way, such as reflecting the different capabilities of competing implementation technologies. Deployment, testing, and the definition of conformance for invisible extensions require out-of-band information, which may be problematic. For example, there is a subset of OWL-Full which has the same syntax as OWL-DL, but which has more entailments (ie different semantics). This subset of OWL-Full is an invisible extension of OWL-DL; its presence (and thus the different intended semantics) cannot be determined by inspection and must be conveyed out-of-band in any applications where the semantic difference might matter. Extensible systems may support User Extensions (Vendor Extensions), Official Extensions or both. A user extension is one which can be defined and widely (and legitimately) deployed without coordinating with a central authority (such as W3C or IANA). Official extensions are those produced under the auspices of the organization which which produced the base dialect (in this case W3C). Some people consider user extensibility to be required for a system to truly be extensible. The RIF Charter extensibility requirement concerns user extensions. Some partially-formed ideas about dependencies: An extension A requires extension B if the base dialect of A is a superset of the extended dialect of B. Extensions A and B are independent if, for all dialects D which can be a base dialect for both A and B, the dialects D+A+B and D+B+A are well-defined and identical. An extension A is compatible with extension B if A requires B, B requires A, or A and B are independent. Dialects are incompatible if either there is no dialect which can be a base for both of them or if they are not compatible. 1.3. Motivation Scenario Acme Widget Co. has a complex pricing structure, with bulk discounts, high-volume customer discounts, periodic sales, overstock sales, and multiple shipping options. They encode their pricing structure in a RIF ruleset which they want to give to customers so that the customers can computationally determine their best timing and grouping of of orders. This provides a mutual advantage, as long as Acme designs their pricing structure to accurately reflect their costs and business goals. Unfortunately, at the time of this effort, Acme finds there is no standard RIF dialect which supports pricing structures varying over time. They can publish a simplified version of their rules, without time-varying parts, but that version would be missing some important information. So they meet with their two biggest customers, who they know are rules-savvy and design an extension to a RIF dialect which gives them this functionality. Some questions arise: - Do they need permission from anyone to do this? (That is, is RIF user extensible or not?) - What should the syntax look like? What namespace? (How do they avoid language conflict?) - What happens if RIF-WG wants to make it a standard later? Will the namespace have to change? - Can they still publish just one ruleset, and have it work for both the users understanding the extension and those not? (That is, is there an effective fallback mechanism?) 1.4. Goals These are some of the less obvious goals. Maybe they should all be enumerated here. User Extensibility: user communities should be able to deploy dialects without any sort of approval from anybody (eg W3C) Let user extensions function as prototypes for standards: it should be possible to prototype possible standard dialects using the user extensibility mechanism, so that (for instance) some community can gain practical experience with a feature before W3C incorporates it into a standard. 2. Managing Overlap The straightforward way to provide for backward compatibility is to ensure that there are no language conflicts. This requires that designers of extensions never accidentally use the same syntax, and that they are careful to use the same semantics when they do use the same syntax. 2.1. Choice: How Do Extension-Creators Discover Overlap? Because RIF uses an XML syntax with XML namespaces (which are URIs), there are several options here. 2.1.1. One Namespace + Best-Effort Coordination The "do-nothing" solution is for all extensions to stay in the RIF namespaces and to ask people to try to coordinate their efforts as best they can, such as by publishing web pages and/or papers about their work, and doing a thorough search for any work that might use the same syntax. Con: - Accidental re-use may occur, with no one at fault, eg due to language differences - Unclear how to resolve disputes 2.1.2. Central Authority Another approach is to require that all extensions be coordinated through the W3C (such as by the RIF-WG). Con: - Expensive for W3C and RIF-WG partipants - Sets a high barrier on creating extensions - Keeps W3C in the critical path 2.1.3. One Namespace + Informal Central Registry Between those two options is a third: have W3C run a mailing list and/or wiki page and require that all extension creators discuss their work their in advance, as part of claiming some syntax. Con: - Potential for problems if disputes arise. (Might end up being expensive for W3C and participants in any relevant WG.) - Keeps W3C in the critical path 2.1.4. Independent Namespace Authorities (Also called URI-based extensibility) The last option is to use the namespace URIs as a point of coordination. This is equivalent to options 2 or 3 for W3C namespaces, but allows anyone else to mint a namespace URI and use it for their extension. Then they would not need to coordinate with W3C on their extension. They should, however, be required to provide for people extending their work. That is, available via the namespace URI there should be some sort of registry, informal or not, which allows users wishing to build beyond their extension to coordinate their syntaxes. Con: - More complicated 2.2. Random Questions Does every syntactic element bless by RIF-WG go in one w3.org namespace, multiple w3.org namespaces, or can some of them be in non-w3.org namespaces? implies: Do user extensions have to change namespaces if they become part of a W3C recommendation? Do we ever allow invisible extensions? How do you know when extensions are compatible? Do people ever need to specify dialects, or can they just specify extensions from a null core? Maybe BLD is a package of 6 extensions? Or maybe it's just one extension? Is that a useful concept? Do we recommend/allow/forbid document-level flags to change the meaning of syntactic elements? e-mail. 3. Fallback Procedures 3.1. Choice: What Fallback Mechanisms Are Mandated? If a system receives a document which does not conform to the syntax of any dialect it implements, what should it do? 3.1.1. Trim To Fit The simplest fallback procedure is to ignore XML subtrees which fall outside the grammar of some implemented dialect. Pro: - Very simple to implement - Needs no information about the extensions or dialects used to do the fallback (but still does for Impact) Con: - May fall back very far, making huge changes to document 3.1.2. Incremental Trim To Fit A variation on Trim-to-Fit is to recursively replace the roots out-of-grammar subtrees with their content, potentially encountering some usable in-grammar elements. This is the approach famously taken by HTML. Same Pros/Cons as Trim-to-Fit. Determining which approach would be better for RIF will require analysis of actual extension syntaxes. 3.1.3. Fixed Substitution in Fallback Data There can be some fixed text to be substituted for particular branches of the extended syntax. 3.1.4. Fixed Substitution in Instance Data The document itself, at the point of using an extension, might include alternative text to use if the extension is not known. Somewhat HTML's [ <object>] specification, which says that if you can't render the object, you should try to render the provided content in its place. For RIF, this might be provided as a "Extension" element, explicitely giving the text you should use if you implement the extension and the text you should use if you do not. This approach segregates extended dialects from other dialects. If an extension were incorporated as part of a standard dialect, its syntax would have to change. See XMLSchema WG proposal for FallbackElement. Pro: - Very straightforward Con: - Clutters up instance documents, possibly making them very large 3.1.5. Template Substitution in Fallback Data The fallback might be a set of single-pass substitution rules, where the new text is given with variables which are bound with values from the old text. 3.1.6. XSLT For a full, Turing complete, fallback mechanism, one could use XSLT. That is, for each extension, there can be an XSLT "stylesheet" (transformation ruleset) which rewrites documents using the extension into documents not using the extension. Having proper independence may be difficult -- it may be hard for XSLT to do its job properly in the presense of other extensions. Pro: - Powerful enough to handle rewriting away syntactic sugar (so such extensions become automatic) - A W3C Recommendation with considerable support and uptake; fairly mature technology Con: - Unknown how hard it will be to write these transforms 3.1.7. BLDX Another option for fallback would be to use a RIF ruleset in some fixed dialect (called "BLDX" as a placeholder here, and assumed to be similar to BLD). This might be Turing complete (like BLD) or not (eg the datalog subset of BLD). While it could operate on the documents at the XML tree level here, it's probably better to take advantage of the frame/object model of the syntax and operate at that level. That is, rules map from a frame facts about the syntactic content of the input document to frame facts about the output document. (Probably needs NAF; might like access to modular databases or something.) Pro: - Powerful enough to handle rewriting away syntactic sugar (so such extensions become automatic) - Closer to the problem domain than XSLT - Operating at the frame/object level should make independence of extensions easier to support - A Cool demonstration of RIF (eating our own dogfood) Con: - Less flexible about arbitrary XML that XSLT - Unproven technology - A fairly high bar on implementation. (Hopefully, BLDX would be not far beyond Core, so it doesn't raise the bar much.) 3.2. Choice: Where Is The Extension Metadata? Again, if a system receives a document which does not conform to the syntax of any dialect it implements, what should it do? Specifically, how can it learn which elements belong to which extensions? How can it learn what Impact is associated with each fallback option it has? How do I learn which fallbacks to perform? Some of these options parallel the Approaches to Discovering Overlap, but there are some others available here, too. All the net-access approaches involve some possible security risks. Perhaps the links could optionally include a secure-hash (if you want to make sure no one changes the extension metadata) or a public key (if you want to let the extension metadata change but are worried about imposters changing it). 3.2.1. Best Effort (Publish+Search) Basically, use Google to try to find the on-line version of the specification of the extension. Hard to automate reliably. 3.2.2. Central Authority Look in some w3.org registration database. Keeps W3C in the loop. 3.2.3. Independent Namespace Authorities Dereference the namespace URIs (maybe with the element names added) to get the metadata. This is a superset of "Central Authority", since W3C would be the namespace authority for the elements in the RIF namespace. 3.2.4. Inline All the fallback metadata is in the document itself. Pro: works off-line Pro: allows localized semantics (nice for local patching of bugs, experimentation) Con: might make RIF files prohibitively larger Con: allows localized semantics (fallback code more likely to diverge from standards) 3.2.5. Imports The fallback metadata is on the web, in a location named in the document. Allows for localized semantics like "Inline". 3.2.6. All Of The Above It's possible to have all of these at the same time. Systems gather data from inside the document, from following import statements in the document, and by dereferencing namespace URIs. Some approach to conflicting information is needed -- maybe the document can say explicitely whether it means to override or be overriden by the namespace documents. (If you're providing the data so that applications still work offline, then you probably want the namespace document to be used if available. If you're providing the data in the document because you want localized semantics, then you don't care about the namespace document.) Maybe there can just be a way to turn off dereferencing of particular namespaces. 3.3. Choice: How complex an impact structure? The design of the impact information structure depends on what you might do differently, based on the information. Many prior extensible languages just use 1-bit of impact information. Sometimes (eg in SOAP) it is a "Must Understand" flag. Other times anything that is not "must understand" is considered to be metadata. The rest of this section is from the Arch/Extensibility2 strawman. Each fallback substitution has zero or more two-part impact flags. Each flag consists of a type and a severity, indicating what kind of effect performing that substitution will have. Based on the type and severity, different types of RIF-consuming systems can behave differently. Repeats of the same impact SHOULD NOT have greater impact. soundness : performing this substitution will make the resulting ruleset produce incorrect answers and/or behaviors. completeness : performing this substitution will make the resulting ruleset produce fewer distinct answers and/or behaviors than it otherwise would. If the results would have been complete before, they no longer will be. performance : performing this substitution may cause rule processing systems to handle this ruleset with significantly degraded performance presentation : this substitution only affects aspects of the ruleset intended for human readers. Under certain conditions, impact flags may be interrelated. For instance, if a negation-as-failure component is being used, a completeness impact flag being set should automatically raise the soundness impact flag. Systems MUST NOT silently perform any fallback substitution which has even a slight chance of producing incorrect answers or behavior. Instead, software SHOULD inform users of fallback substitutions which have minimal affects and SHOULD require confirmation from users before performing fallback substitutions which may have greater affects. RIF Software MUST NOT lead a reasonable user to think that errors stemming from fallback substitutions are due to faulty input. Suggested Response This table indicates suggested handling of impact information by a system which answers queries for users, using reasoning on a rulebase provided in RIF. 3.4. Random Questions Can we use the namespace+element URI to look up the fallback information? Must we support off-line fallback? Do we have a simple flag indicating non-semantic (metadata) extensions? (Do we consider metadata an extension?) Is there a way to make the fallback processing extensible? Could we make only Trim-to-Fit manditory, but have XSLT or BLDX be encouraged and motivated? 4. Strawman 4.1. Overview All official dialect elements go into rif: namespace. That namespace will dereference just like everyone else's SHOULD: - pointers to fallback/impact information - pointers to documentation - pointers to community resources User extensions go in separate own namespaces (which might happen to be on w3.org, or purl.org, or whatever). If they become official, the namespace has to change. But fallback substitution between the two should mean implementations and data don't have to change. extensible fallback options, up to fixed-replacement. no invisible extensions having in-line data or in-line imports is an extension. no specific notion of metadata -- it's just extensions for elements which can be ignored with minimal impact. 4.2. Input Processing Procedure Proposed, that all systems which consume RIF MUST do this: - You have a RIF document to process - You try to parse it (or schema validate it) according to each of the dialects you know. If you succeed with any of them, you're done. Otherwise... - You parse the document using the all-RIF schema to obtain the dialect metadata. - The metadata (or its absence) will indicate whether you should do web-based fallback processing. If so, you must either do it, or give the user an error message. If it fails, the user must be given an error message. If it succeeds, you have more dialect metadata. - The dialect metadata allows you to construct additonal XML schemas. The document must be schema valid with respect to at least one of them. - The dialect metadata also includes fallback/impact information, back to a base dialect you probably implement. You must do this transformation or warn the user. Based on the impact, you may have to warn the user 4.3. Dialect Metadata Whole Dialect include grammar for dialect, and set of zero or more fallbacks to other dialects. Extension includes a partial grammar to match against and additional branches to add to it. Also, zero or more fallbacks which transform from the modified grammar back to the original. Names any element/attribute URIs which are not to followed. Names any additional URIs which are to be followed. Fallback procedures are named by URIs, which are to be followed unless also given in dialect metadata. Namespace documents, fallback data, etc, is all in RDF/XML. (Alternatively, in some RIF dialect.) @@ Can we add content hashes, somehow, later? 4.4. Fallback Functionality - xml tag/attr substitution [ with this impact ] - omit this subtree [ with this impact ] - replace this subtree with its content [ with this impact ] - replace this subtree with this value [ with this impact ] Additional fallback mechanisms may be specified later; esp XSLT and BLDX. This is done by simply saying that if you don't understand some of the Extension data, you ignore it. (@@ Is that okay? Elsewhere, we seem to want schema validity.) Impact information is as in previous strawman. 5. Example Extensions See RIF Dialect Structure, and other versions of that.... 5.1. Add Neg (classical negation) to BLD 5.2. Add SMNAF (Stable Model Negation-As-Failure) to BLD 5.3. Add WFNAF (Well-Founded Negation-As-Failure) to BLD 5.4. Add Lists to BLD 5.5. Add Object-Oriented Non-Monotonic Inheritance to BLD 6. References David Orchard has edited a series of drafts on "versioning" for the TAG and XML Schema Working Group:
http://www.w3.org/2005/rules/wg/wiki/Arch/Extensibility_Design_Choices.html
CC-MAIN-2016-18
refinedweb
3,763
54.42
Important: Please read the Qt Code of Conduct - Visual Studio Code in parallel with QtCode Hi Comunity, I have an old app written in C++ using Visual Studio enviroment. I have to replace its GUI, so I have developed an small GUI in Qt. I have a point in that old program where the old GUI is created. I thought that just in that point should I the Qt gui in paralel start and the rest will be send signals to interface. I readed the next post for the threads In First place, I'm trying to write an small program where the MainWindow will moved into a new thread and after, furthermore code (a cout << "hello" << endl; for example) will executed. To follow the method in above link showed, I'm trying to build an object with the necessary calls to create the main window, thinking in moving that object into a new thread. here is the code: (main.cpp) #include "mainwindow.h" #include <QApplication> #include <QObject> class GuiApp : public QObject { Q_OBJECT public: explicit GuiApp(int argc, char *argv[]); ~GuiApp(); int returnExec(); private: QApplication *a;//QApplication a(argc, argv); }; GuiApp::GuiApp(int argc, char *argv[]) { a = new QApplication(argc, argv); MainWindow w; w.show(); returnExec(); } GuiApp::~GuiApp() { delete a; } int GuiApp::returnExec() { return a->exec(); } //*********************************************** //*********************************************** int main(int argc, char *argv[]) { GuiApp gApp(argc, argv); /*I intend write here the sentences to move gApp to the new thread * * */ //The code after this point should be executed in parallel cout << "hello" << endl; } That's my idea, but I get the following linkage errors main.obj : error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall GuiApp::metaObject(void)const " (?metaObject@GuiApp@@UBEPBUQMetaObject@@XZ) main.obj : error LNK2001: unresolved external symbol "public: virtual void * __thiscall GuiApp::qt_metacast(char const *)" (?qt_metacast@GuiApp@@UAEPAXPBD@Z) main.obj : error LNK2001: unresolved external symbol "public: virtual int __thiscall GuiApp::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@GuiApp@@UAEHW4Call@QMetaObject@@HPAPAX@Z) debug\parallel_test.exe : fatal error LNK1120: 3 unresolved externals Is this the right way? Please Could anybody help me or to fix the linker errors (case that the right way ist) or show me the right form to make this? Any help oder suggestion will be good welcomed Thanks in advance. - Christian Ehrlicher Lifetime Qt Champion last edited by You should create your Visual Studio solution with the help of qmake and a .pro - file: and @Christian-Ehrlicher Thank you very much, that's a point to begin with the import process of the visual studio project. Any help with the paralel execution from the code? thanks in advance - mrjj Lifetime Qt Champion last edited by mrjj @Josz Hi you can try ( worked for me on win 10) all credits to mr kshegunov This post is deleted! @mrjj Sadly Did not work :_(. The loop run only when I close the MainWindow. I'm on Windows 7 with msvsc2015 32 bits and Qt 5.11.2. In my .pro I have CONFIG += c++11. Replacing for c++14 is the same here is my code #include "mainwindow.h" #include <QApplication> #include <thread> #include <iostream> using namespace std; void guiLoader(int argc, char *argv[]){ QApplication a(argc, argv); MainWindow w; w.show(); //return a.exec(); QApplication::exec(); } void loop(){ while(1) cerr << "Parallel hello World" << endl; } int main(int argc, char *argv[]) { thread guiLoaderThread(guiLoader, argc, argv); guiLoaderThread.join(); loop(); } Didn't work because the position of "guiLoaderThread.join();". This sentence must be placed at the end of the code that you want to execute. Is like "The code will run until here" The next version work fine #include "mainwindow.h" #include <QApplication> #include <thread> #include <iostream> using namespace std; void guiLoader(int argc, char *argv[]){ QApplication a(argc, argv); MainWindow w; w.show(); //return a.exec(); QApplication::exec(); } void loop(){ for(int i = 0; i < 100; i++) cerr << "helloworld parallel" << endl; } int main(int argc, char *argv[]) { thread guiLoaderThread(guiLoader, argc, argv); loop(); cerr << "last line to be executed" << endl; guiLoaderThread.join(); return 11; }
https://forum.qt.io/topic/96606/visual-studio-code-in-parallel-with-qtcode
CC-MAIN-2021-04
refinedweb
671
62.58
CodePlexProject Hosting for Open Source Software Hi, Anybody know if json.net supports the following scenario and if it does please show me how I have the following model structure public abstract class Animal { } public class Cat : Animal{ } I want to deserialize to an container object that has a list of animal objects public class Zoo{ public IList<Animal> AnimalList; In the Json the content list contains a drived type: Cat "animalList":[ { "type":"Cat", So I need to be able to configure Json.net to be able to create a list of (Cat)animal objects. Obviously the derived class of Animal can change, so whatever comes in Json, Json.net will know to create a derived Type. Thanks, Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://json.codeplex.com/discussions/353413
CC-MAIN-2013-48
refinedweb
154
63.29
Problem Statement In this problem, we are given a set of three points in an X-Y 2-D plane. We need to return whether they form a boomerang or not, that is whether they are any three distinct points and do not form a straight line. Example Points = {{1 , 2} , {2 , 6} , {1 , 2}} false Points = {{1 , 1} , {2 , 3} , {6 , 7}} true The first input has two same points out of 3, so it is not a valid boomerang and we print false. The second test has 3 distinct points that do not form a straight line and we print true. Approach(Slope Test) In the problem Check If It is a Straight Line, we have learnt that three distinct points are only collinear if the slope of the line formed by every pair of points is the same. Here, we need to check: - If points are distinct - the points do not lie on a straight line If any pair of points is the same, then the given input will pass the collinearity test, as any 2 points(or a single point) are always collinear. So, we just need to check for the equality of slopes. Note that if any three points, P1, P2 and P3 are collinear, we have (y2 – y1) : (x2 – x1) :: (y3 – y2) : (x3 – x2) , or (y2 – y1) * (x3 – x2) = (x2 – x1) * (y3 – y2) where x1, x2, x3, y1, y2, y3 are the corresponding x and t coordinates of P1, P2 and P3. Algorithm - Initialize dx1 = difference of x-coordinates of the first two points and dy1 = difference of y-coordinates of first two points - Similarly, store dx2 = difference of y-coordinates of the last two points and dy2 = difference of y-coordinates of last two points - Return if ((dx1 * dy2) != (dx2 * dy1)) (the slope test condition) - Print the result Implementation of Valid Boomerang Leetcode Solution C++ Program #include <bits/stdc++.h> using namespace std; bool isBoomerang(vector <vector <int> > &points) { int dx1 = (points[1][0] - points[0][0]); int dy1 = (points[1][1] - points[0][1]); int dx2 = (points[2][0] - points[1][0]); int dy2 = (points[2][1] - points[1][1]); return (dx1 * dy2) != (dy1 * dx2); } int main() { vector <vector <int> > points = {{1 , 1} , {2 , 3} , {6 , 7}}; if(isBoomerang(points)) cout << "true\n"; else cout << "false\n"; return 0; } Java Program class valid_boomerang { public static void main(String args[]) { int[][] points = {{1 , 1} , {2 , 3} , {6 , 7}}; if(isBoomerang(points)) System.out.println("true"); else System.out.println("false"); } static boolean isBoomerang(int[][] points) { int dx1 = (points[1][0] - points[0][0]); int dy1 = (points[1][1] - points[0][1]); int dx2 = (points[2][0] - points[1][0]); int dy2 = (points[2][1] - points[1][1]); return (dx1 * dy2) != (dy1 * dx2); } } true Complexity Analysis of Valid Boomerang Leetcode Solution Time Complexity O(1) as we perform a constant number of operations. Space complexity O(1) as we use constant memory space.
https://www.tutorialcup.com/leetcode-solutions/valid-boomerang-leetcode-solution.htm
CC-MAIN-2021-31
refinedweb
489
69.55
On 6 Mar 2007 09:49:55 -0800, Martin Unsal <martinuns__? You have to reload the importing module as well as the module that changed. That doesn't require rewriting the import infrastructure. It's only an issue because you're changing things at one level but you're trying to use them at a level removed from that. I never work that way, because I only have any need or desire to reload when I'm working interactively and I when I'm doing that I work directly with the modules I'm changing. The interfaces are what my unit tests are for. If you're doing stuff complicated and intricate enough in the interpreter that you need reload() to do very much more than its doing, then you're working poorly - that sort of operation should be in a file you can run and test automatically. > > >! > All the files on the PYTHONPATH will map into the namespace. However, you can have items in the namespace that do not map to files. The main reasons to do so are related to deployment, not development though so I wonder why you want to. > >. > Thats not answering the question. Presumably you have some sort of organization for your code in mind. What about that organization doesn't work for Python? If you want multiple files to map to a single module, make them a package.
https://mail.python.org/pipermail/python-list/2007-March/416983.html
CC-MAIN-2014-15
refinedweb
234
72.26
have checked in the latest round of updates to WSDL2PERL. I am focusing on RPC style encoding and decoding for now. This round of updates also requires that the latest version of SOAP::Lite also be checked out an installed. Changes include: * new format_datetime subroutine * new use_prefix subroutine - for .NET compatibility WSDL2PERL is at a point right now where it is beginning to pass a first set of basic unit tests. What remains you ask? Simple... * figure out a way to have all the namespaces used in an envelope collected and serialized in the Envelope element. * produce a find_nsprefix subroutine which when given a URI will return the corresponding NS prefix. This will help in automatic type resolution ^byrne :/ The wsdl2perl module is now available... it sometimes takes a while for the code to be distributed out to the CVS servers for distribution... Its there now. >) > > > > ------------------------------------------------------- > This SF. Net email is sponsored by: GoToMyPC > GoToMyPC is the fast, easy and secure way to access your computer from > any Web browser or wireless device. Click here to Try it Free! > > _______________________________________________ > Soaplite-devel mailing list > Soaplite-devel@... > > > ^byrne :/ Same here... Al. -- Dr. A. Allan, School of Physics, University of Exeter Byrne Reese writes: > :-( -- Michael Brader michael.brader@... Senior Software Developer (Unix) ntl:ipd Hook 01256 75(3413) cvs -z3 -d:pserver:anonymous@...:/cvsroot/soaplite co wsdl2perl ^byrne :/ I wanted to inform the SOAP::Lite community, that the first checkin of the wsdl2perl utility has been made. It has not been packaged for distribution yet, as it is still in a pre-alpha phase... and will most likely not work for most people - if not all. The utility uses Perl's Template module to generate client side (and ultimately server side as well) code stubs for call a SOAP based Web service using SOAP::Lite. This effort is serving as major point of feedback to SOAP::Lite itself and will be informing future development efforts. Until the module stablizes, all future discussion should take place on the SOAP::Lite developer mailing list: soaplite-devel@... I checked in the module to CVS on sourceforge. To retrieve it, run the following cvs command: > export CVS_RSH=ssh; > cvs -d:ext:anonymous@...:/cvsroot/soaplite co wsdl2perl The code has not yet appeared in the browsable CVS repos. online, but I imagine it just takes a little time. Anyway, that's it. I am just pleased to let the community know that development continues. ^byrne :/
https://sourceforge.net/p/soaplite/mailman/soaplite-devel/?viewmonth=200311&style=flat
CC-MAIN-2017-39
refinedweb
408
66.44
Failing to Bound Kissing Numbers Cody brought up the other day the kissing number problem.Kissing numbers are the number of equal sized spheres you can pack around another one in d dimensions. It’s fairly self evident that the number is 2 for 1-d and 6 for 2d but 3d isn’t so obvious and in fact puzzled great mathematicians for a while. He was musing that it was interesting that he kissing numbers for some dimensions are not currently known, despite the fact that the first order theory of the real numbers is decidable I suggested on knee jerk that Sum of Squares might be useful here. I see inequalities and polynomials and then it is the only game in town that I know anything about. Apparently that knee jerk was not completely wrong Somehow SOS/SDP was used for bounds here. I had an impulse that the problem feels SOS-y but I do not understand their derivation. One way the problem can be formulated is by finding or proving there is no solution to the following set of equations constraining the centers $ x_i$ of the spheres. Set the central sphere at (0,0,0,…) . Make the radii 1. Then$ \forall i. |x_i|^2 = 2^2 $ and $ \forall i j. |x_i - x_j|^2 \ge 2^2 $ I tried a couple different things and have basically failed. I hope maybe I’ll someday have a follow up post where I do better. So I had 1 idea on how to approach this via a convex relaxation Make a vector $ x = \begin{bmatrix} x_0 & y _0 & x_1 & y _1 & x_2 & y _2 & … \end{bmatrix}$ Take the outer product of this vector $ x^T x = X$ Then we can write the above equations as linear equalities and inequalities on X. If we forget that we need X to be the outer product of x (the relaxation step), this becomes a semidefinite program. Fingers crossed, maybe the solution comes back as a rank 1 matrix. Other fingers crossed, maybe the solution comes back and says it’s infeasible. In either case, we have solved our original problem. import numpy as np import cvxpy as cvx d = 2 n = 6 N = d * n x = cvx.Variable((N+1,N+1), symmetric=True) c = [] c += [x >> 0] c += [x[0,0] == 1] # x^2 + y^2 + z^2 + ... == 2^2 constraint x1 = x[1:,1:] for i in range(n): q = 0 for j in range(d): q += x1[d*i + j, d*i + j] c += [q == 4] #[ x1[2*i + 1, 2*i + 1] + x[2*i + 2, 2*i + 2] == 4] #c += [x1[0,0] == 2, x1[1,1] >= 0] #c += [x1[2,2] >= 2] # (x - x) + (y - y) >= 4 for i in range(n): for k in range(i): q = 0 for j in range(d): q += x1[d*i + j, d*i + j] + x1[d*k + j, d*k + j] - 2 * x1[d*i + j, d*k + j] # xk ^ 2 - 2 * xk * xi c += [q >= 4] print(c) obj = cvx.Maximize(cvx.trace(np.random.rand(N+1,N+1) @ x )) prob = cvx.Problem(obj, c) print(prob.solve(verbose=True)) u, s, vh = np.linalg.svd(x.value) print(s) import matplotlib.pyplot as plt xy = vh[0,1:].reshape(-1,2) print(xy) plt.scatter(xy[0], xy[1] ) plt.show() Didn’t work though. Sigh. It’s conceivable we might do better if we start packing higher powers into x? Ok Round 2. Let’s just ask z3 and see what it does. I’d trust z3 with my baby’s soft spot. It solves for 5 and below. Z3 grinds to a halt on N=6 and above. It ran for days doin nothing on my desktop. from z3 import * import numpy as np d = 2 # dimensions n = 6 # number oif spheres x = np.array([ [ Real("x_%d_%d" % (i,j)) for j in range(d) ] for i in range(n)]) print(x) c = [] ds = np.sum(x**2, axis=1) c += [ d2 == 4 for d2 in ds] # centers at distance 2 from origin ds = np.sum( (x.reshape((-1,1,d)) - x.reshape((1,-1,d)))**2, axis = 2) c += [ ds[i,j] >= 4 for i in range(n) for j in range(i)] # spheres greater than dist 2 apart c += [x[0,0] == 2] print(c) print(solve(c)) Ok. A different tact. Try to use a positivstellensatz proof. If you have a bunch of polynomial inequalities and equalities if you sum polynomial multiples of these constraints, with the inequalities having sum of square multiples, in such a way to = -1, it shows that there is no real solution to them. We have the distance from origin as equality constraint and distance from each other as an inequality constraint. I intuitively think of the positivstellensatz as deriving an impossibility from false assumptions. You can’t add a bunch of 0 and positive numbers are get a negative number, hence there is no real solution. I have a small set of helper functions for combining sympy and cvxpy for sum of squares optimization. I keep it here along with some other cute little constructs import cvxpy as cvx from sympy import * import random ''' The idea is to use raw cvxpy and sympy as much as possible for maximum flexibility. Construct a sum of squares polynomial using sospoly. This returns a variable dictionary mapping sympy variables to cvxpy variables. You are free to the do polynomial operations (differentiation, integration, algerba) in pure sympy When you want to express an equality constraint, use poly_eq(), which takes the vardict and returns a list of cvxpy constraints. Once the problem is solved, use poly_value to get back the solution polynomials. That some polynomial is sum of squares can be expressed as the equality with a fresh polynomial that is explicility sum of sqaures. With the approach, we get the full unbridled power of sympy (including grobner bases!) I prefer manually controlling the vardict to having it auto controlled by a class, just as a I prefer manually controlling my constraint sets Classes suck. ''' def cvxify(expr, cvxdict): # replaces sympy variables with cvx variables in sympy expr return lambdify(tuple(cvxdict.keys()), expr)(*cvxdict.values()) def sospoly(terms, name=None): ''' returns sum of squares polynomial using terms, and vardict mapping to cvxpy variables ''' if name == None: name = str(random.getrandbits(32)) N = len(terms) xn = Matrix(terms) Q = MatrixSymbol(name, N,N) p = (xn.T * Matrix(Q) * xn)[0] Qcvx = cvx.Variable((N,N), PSD=True) vardict = {Q : Qcvx} return p, vardict def polyvar(terms,name=None): ''' builds sumpy expression and vardict for an unknown linear combination of the terms ''' if name == None: name = str(random.getrandbits(32)) N = len(terms) xn = Matrix(terms) Q = MatrixSymbol(name, N, 1) p = (xn.T * Matrix(Q))[0] Qcvx = cvx.Variable((N,1)) vardict = {Q : Qcvx} return p, vardict def scalarvar(name=None): return polyvar([1], name) def worker(x ): (expr,vardict) = x return cvxify(expr, vardict) == 0 def poly_eq(p1, p2 , vardict): ''' returns a list of cvxpy constraints ''' dp = p1 - p2 polyvars = list(dp.free_symbols - set(vardict.keys())) print("hey") p, opt = poly_from_expr(dp, gens = polyvars, domain = polys.domains.EX) #This is brutalizing me print(opt) print("buddo") return [ cvxify(expr, vardict) == 0 for expr in p.coeffs()] ''' import multiprocessing import itertools pool = multiprocessing.Pool() return pool.imap_unordered(worker, zip(p.coeffs(), itertools.repeat(vardict))) ''' def vardict_value(vardict): ''' evaluate numerical values of vardict ''' return {k : v.value for (k, v) in vardict.items()} def poly_value(p1, vardict): ''' evaluate polynomial expressions with vardict''' return cvxify(p1, vardict_value(vardict)) if __name__ == "__main__": x = symbols('x') terms = [1, x, x**2] #p, cdict = polyvar(terms) p, cdict = sospoly(terms) c = poly_eq(p, (1 + x)**2 , cdict) print(c) prob = cvx.Problem(cvx.Minimize(1), c) prob.solve() print(factor(poly_value(p, cdict))) # global poly minimization vdict = {} t, d = polyvar([1], name='t') vdict.update(d) p, d = sospoly([1,x,x**2], name='p') vdict.update(d) constraints = poly_eq(7 + x**2 - t, p, vdict) obj = cvx.Maximize( cvxify(t,vdict) ) prob = cvx.Problem(obj, constraints) prob.solve() print(poly_value(t,vdict)) and here is the attempted positivstellensatz. import sos import cvxpy as cvx from sympy import * import numpy as np d = 2 N = 7 # a grid of a vector field. indices = (xposition, yposition, vector component) '''xs = [ [symbols("x_%d_%d" % (i,j)) for j in range(d)] for i in range(N) ] gens = [x for l in xs for x in l ] xs = np.array([[poly(x,gens=gens, domain=polys.domains.EX) for x in l] for l in xs]) ''' xs = np.array([ [symbols("x_%d_%d" % (i,j)) for j in range(d)] for i in range(N) ]) c1 = np.sum( xs * xs, axis=1) - 1 c2 = np.sum((xs.reshape(-1,1,d) - xs.reshape(1,-1,d))**2 , axis=2) - 1 print(c1) print(c2) terms0 = [1] terms1 = terms0 + list(xs.flatten()) terms2 = [ terms1[i]*terms1[j] for j in range(N+1) for i in range(j+1)] #print(terms1) #print(terms2) vdict = {} psatz = 0 for c in c1: lam, d = sos.polyvar(terms2) vdict.update(d) psatz += lam*c for i in range(N): for j in range(i): c = c2[i,j] lam, d = sos.sospoly(terms2) vdict.update(d) psatz += lam*c #print(type(psatz)) print("build constraints") constraints = sos.poly_eq(psatz, -1, vdict) #print("Constraints: ", len(constraints)) obj = cvx.Minimize(1) #sum([cvx.sum(v) for v in vdict.values()])) print("build prob") prob = cvx.Problem(obj, constraints) print("solve") prob.solve(verbose=True, solver= cvx.SCS) It worked in 1-d, but did not work in 2d. At order 3 polynomials N=7, I maxed out my ram. I also tried doing it in Julia, since sympy was killing me. Julia already has a SOS package using JuMP using SumOfSquares using DynamicPolynomials using SCS N = 10 d = 2 @polyvar x[1:N,1:d] X = monomials(reshape(x,d*N), 0:2) X1 = monomials(reshape(x,d*N), 0:4) model = SOSModel(with_optimizer(SCS.Optimizer)) acc = nothing for t in sum(x .* x, dims=2) #print(t) p = @variable(model, [1:1], Poly(X1)) #print(p) if acc != nothing acc += p * (t - 1) else acc = p * (t - 1) end end for i in range(1,stop=N) for j in range(1,stop=i-1) d = x[i,:] - x[j,:] p = @variable(model, [1:1], SOSPoly(X)) acc += p * (sum(d .* d) - 1) end end #print(acc) print(typeof(acc)) @constraint(model, acc[1] == -1 ) optimize!(model) It was faster to encode, but it’s using the same solver (SCS), so basically the same thing. I should probably be reducing the system with respect to equality constraints since they’re already in a Groebner basis. I know that can be really important for reducing the size of your problem I dunno. Blah blah blah blah A bunch of unedited trash Peter Wittek has probably died in an avalanche? That is very sad. These notes Positivstullensatz. kissing number Review of sum of squares minimimum sample as LP. ridiculous problem min t st. f(x_i) - t >= 0 dual -> one dual variable per sample point The only dual that will be non zero is that actually selecting the minimum. Hm. Yeah, that’s a decent analogy. How does the dual even have a chance of knowing about poly airhtmetic? It must be during the SOS conversion prcoess. In building the SOS constraints, we build a finite, limittted version of polynomial multiplication x as a matrix. x is a shift matrix. In prpducing the characterstic polynomial, x is a shift matrix, with the last line using the polynomial known to be zero to eigenvectors of this matrix are zeros of the poly. SOS does not really on polynomials persay. It relies on closure of the suqaring operaiton maybe set one sphere just at x=0 y = 2. That breaks some symmettry set next sphere in plane something. random plane through origin? order y components - breaks some of permutation symmettry. no, why not order in a random direction. That seems better for symmettry breaking
https://www.philipzucker.com/failing-to-bound-kissing-numbers/
CC-MAIN-2021-39
refinedweb
2,037
66.03
I am making a programming that allows a user to search a database of player statistics. I am using conditionals, and I was wondering how i could make a variable two words, (The Players First Name and the Players Last Name). Here is what i mean. public class Players { public static void main (String[] args) throws IOException { Buffered reader...... Here is what i want ----> String John Smith; String playername; System.out.print("Player Name::"); playername = keyboard.readline.. if(playername.equals("John Smith"){ System.out.print(Stats); } } What you are trying to do poses some problems. In general it is considered pretty bad form to make a variable name look like a constant. Variables should be variable and shouldn't necessarily be specific to one person. You could do something like a constant: public final String NAME = "John Smith" if you're certain you will always be using it in your code. You could name a string variable John_Smith, but it would do nothing for you so I don't know how to adequately answer this. in my conditional could i make a statement that requires the first and last name to be present, and just define each part of the name by itself, such as String John; String Smith; if(playername.equals("John" and "Smith"). I'm still baffled by why you would want to name a variable after a name that is going to be put inside of it. The only other thing I can think of is to make your own "name" object and make comparisons based on it. Of course you might want to add other stats to Name and then it would become more of a "Player" class anyway. public class Name { private String first, last; public Name(String first, String last) { this.first = first; this.last = last; } public String getFirst() { return first; } public String getLast() { return last; } public boolean equals(Name otherName) { // return true if and only if both the first and last names match if (first.equals(otherName.getFirst()) && last.equals(otherName.getLast()) return true; else return false; } } Expanding on the above idea might be helpful to you. Other than that I don't know what you hope to gain from it. in my conditional could i make a statement that requires the first and last name to be present, and just define each part of the name by itself, such as String John; String Smith; if(playername.equals("John" and "Smith"). I'm not sure you have the right idea about how the variables work. The name of the variable is totally irrelevant. You can call it whatever you want and it doesn't matter. All that matters is what it points to. In the above code John and Smith point to nothing, so they are null. Also, they are not used in your conditional. They have no relation whatsoever to the string literals "John" and "Smith" in the if statement. Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?140613-Rounding&goto=nextnewest
CC-MAIN-2016-36
refinedweb
506
73.37
What did one have to do to win these prizes? Simple; The phrase "Nigritude Ultramarine" (Which is a latin phrase meaning Dark Blue, the sponsoring company,) had 0 matches on Google as of May 6th. Whoever's page was the top search result for the phrase, on Google, wins. In 13 days, the 4th most frequent search on the web was for the phrase "Nigritude Ultramarine". At one point, there were over half a million hits for the phrase with Google. Pages in Spanish, Greek, Norwegian, Japanese, and French appeared with the phrase, and The Wall Street Journal published an article on it. The goal of the contest was to show how one can optimize a web site to be very high up on various search engines ranking, and to publicize the company, Dark Blue. The winner, Anil Dash, won through completely aboveboard means; He asked people to link to his site, and people "advertised" for him on many popular forums using links to his page with the phrase. This strategy beat out many other contestants who use proactive rigging, with page naming and buying namespace in many forums. The attitude of many contestants can be summed up neatly, as Vijay, a contestant put it; "Some tactics might be aggressive but I don't care, after all this is a competition right?" The response, by Anil Dash, was a sentiment appreciated by many watchers; ." Sources: Log in or register to write something here or to contact authors. Need help? accounthelp@everything2.com
https://m.everything2.com/title/Nigritude+Ultramarine?showwidget=showCs1629847
CC-MAIN-2021-43
refinedweb
252
67.38
THE WINE MERCHANT. Issue 86, November 2019 Dog of the Month: Roscoe Tanner, Tanner’s Safely gathered in It was a soggy harvest at Rathfinny in Sussex, but yields were up by 19%, the producer says Indies are backing Beaujolais The style was once derided by specialists, but many are finding that a new crowd appreciates Nouveau B e Continues page five Viv Blakey, Rathfinny Wine Estate An independent magazine for independent retailers EDITORIAL Inside this month 6 comings & Goings Good news for Bedminster, Crowborough and Cirencester 12 tried & tested We rather like Olaszrizling and Petite Sirah. OK? 18 david williams Reporting back from some quite boring supermarket tastings 26 the old bridge wine shop A place for everything and everything in its place at this Huntingdon independent 32 buyers trip to austria Discovering Burgenland and Styria with some intrepid indies 46 French connections Eleven artisanal producers have wines they believe are tailormade for specialist merchants The Spirits World, page 58; Make a Date, page 60; Supplier Bulletin, page 61 You think you hate Vivino? Just imagine what might come next B eing naturally fearful of change, and not particularly up to speed with digital media, we were quite late to the party here at The Wine Merchant when it comes to Vivino. Most, if not all, independents will have encountered the app by now. It’s a kind of Shazam for bottles of wine: simply snap a picture of the label, and within seconds you’ll have a wealth of information at your fingertips, including stuff about grape varieties, producer and region, and reviews from fellow Vivinists – possibly a word we’ve invented – telling you what the wine tastes like. That’s all very exciting stuff, and it doesn’t cost anything to be part of the action. It’s quicker than a Google search and you get to store all your favourite wines, along with your own review, for easy reference another time. Vivino also gives users a guideline price which is based on the kind of figure that an e-commerce site might be able to offer if you disregard things like courier costs and minimum orders. That detail doesn’t stop customers from using Vivino as a stick with which to beat their friendly local wine merchant or restaurant, against whom they believe they now have rock-solid evidence of shameless profiteering. Many merchants despise Vivino for exactly that reason. They also resent the fact that some customers seem determined to keep their noses stuck to their smartphone screens, reading reviews that say “cracking red!” in the company of a retailer who would happily, if called upon, tell them everything they need to know about the wine in question. But, as Edward Symonds of Saxty’s in Hereford argued at our recent round table event in Birmingham (see pages 41-45), this kind of technology is only going to get better, and if Vivino isn’t the long-term app of choice for wine drinkers, something else will come along. The technology is not about to be un-invented. The challenge for indies is to find their own ways of engaging with their customers in the digital space. Some have apps of their own, admittedly not as allencompassing as Vivino, but they do a job. When 5G goes live, and technology moves on even more, we’ll probably look back at the current version of Vivino and smirk. But whatever comes next will pose more challenges for retailers, and possibly present lots of opportunities. Those of us who like to pretend digital media is an irrelevant fad would do well to at least try to keep up with developments. 2019 Registered in England: No 6441762 VAT 943 8771 82 THE WINE MERCHANT november 2019 2 NEWS Matt’s all smiles at being out of date restaurants which have gone bust. “It’s been a bad year for restaurants,” he says, “but a really good year for our customers. We are able to get wines that could retail Matt Ellis at the Smiling Grape Company for £16 but we can do them for £6.99. We in St Neots is often head of the queue can get very cheap spirits that way too.” when it comes to innovative ideas. Ellis is currently considering locations This is the wine merchant who is for some pop-up shops leading up to well known for his sideline in extreme Christmas with the intention of harnessing adventure tours: at the end of this year the party crowd who might not be able he is inviting customers to join him on to resist the huge discounts on offer. For an expedition to Ethiopia. “Join us,” his example, Ellis is able to offer cans of Resin website reads, “for the adventure of a lifetime as we visit the Danakil Depression in Ethiopia, aka The Gateway to Hell.” Perhaps more mainstream is his interest in beer. Ellis says that a significant part of his business is now selling out-of-date from Sixpoint Brewery with an RRP of This man can sell you £4.50 beer for just 99p “The breweries contact us and we buy it beer both from his shop and from www. from them at a very cheap price and people really taken off and helped the business,” with Tesco and once the beers become lowcost beer.com, the website he’s set up specifically for this retail offshoot. “It’s Ellis explains. “We worked out the other day that we have sold 60,000 bottles and cans over the past year. are quite happy to buy it from us. We also work with a couple of breweries that deal out of date, they send them back to the brewery.” Ellis is also buying up stock from Join us at the UK's first ever Cava Summit The first ever London Cava Summit will include a round-table discussion for independent wine specialists, hosted by The Wine Merchant. The event brings together experts and industry influencers to discuss the promising future of premium Cava in the UK. The summit takes place on Monday, December 2 at The ICETANK, London WC2 where personalities from across the wine trade will debate the way in which merchants, together with the prime movers in the DO Cava, can influence the way consumers drink and appreciate Cava. The event starts with a keynote address by DO Cava president Javier Pagés, followed by a a panel discussion including Sarah Jane Evans MW and Dawn Davies MW. An open tasting, featuring a selection of Reserva, Gran Reserva and Cava de Paraje wines, will take place from 12.30pm. The Wine Merchant round table starts at 2pm. Merchants interested in taking part in the round table can contact claire@winemerchantmag.com. To register for the event itself, email angeline@bespokedrinksmedia.com. THE WINE MERCHANT november 2019 4 £4.50 for just 99p each. Are there any dreaded health and safety implications when it comes to drinking out-of-date beer? Ellis says not and explains that although it would depend on how the beer is made, breweries generally allow a drinking window of “more or less” two years beyond the best-before date. “Another plan in the pipeline is to have our own out-of-date beer bar called The Best Before Bar,” he says. “We can become the next Wetherspoons.” Merchants gear up for Nouveau party From page one – even more so than last year’s I’d say. I Yields have dropped by 20% think the quality has improved over recent different ideas of how to make wine, and francophiles either. I’ve been surprised that changed their whole viewpoint – there are years – it’s a lot more serious. It’s not just a whim for the cool kids or the traditional • Although sparkling red wines ae often regarded as an Australian novelty, they were being produced in the country as early as 1881. It is thought that the world’s first sparkling reds appeared in Burgundy in the 1820s. ....... prices. all been positive about the ’19 vintage “Our Man with the Facts” they’ve travelled. But it’s not necessarily a question of age. There are people who.” THE WINE MERCHANT november 2019 5 • According to research, the cost of growing organic wine grapes is on average 10% to 15% higher than that for conventional grapes. The cost of growing biodynamic grapes increases by a further 10% to 15% compared to that of the organic product. ....... • A study into terroir, carried out at UC Davis, analysed red wines made from grapes from five different vineyards within a 40-mile radius, vinified in separate wineries. It was found that both the vineyard and the winery impacted on the chemical composition of the finished wine, throwing yet more doubt over the real effect of terroir. ....... • Rather confusingly, Morillon is both an old French synonym for Pinot Noir as well as the word used in Styria, Austria, for Chardonnay. The term was once also popular in Chablis. Food hall moves to Hercules site Popular Kent food hall Macknade has taken on the Faversham branch of Hercules Wine Warehouse and rebranded as Macknade Wine & Spirits. Macknade’s general manager Finn Dunlop says: “Sarah [Dodd] had been a tenant for 10 years and now she is concentrating on her shop in Sandwich. We just bought the stock and amalgamated the wine shop within our existing business.” “It was a very good offer,” admits Dodd, “one I would have been foolish to turn down … so I didn’t!” She explains that while the Faversham site was always 100% retail, the wholesale, e-commerce and private client side of the business has always been handled from Finn Dunlop expects the current range of 400 wines to grow Sandwich. “It’s business as usual,” she says, in regularly and conduct tastings for make a perfectly comfortable living,” he location.” has a soft spot for wine from eastern things, and that’s what I’m going for with “but I wouldn’t rule out taking on another site if one popped up in the ‘perfect’ Dunlop and his team will continue to engage their customers through wine events and tastings. “Already with our customer base we encourage people to explore the boundaries of their palate, with their cooking and so on, so we want to do that not just in culinary terms but in wine terms as well,” he says. The food hall had already been retailing wine but this new development brings its customers,” he says. Looking further afield he says he European countries. “I think they are both underrepresented and underrated Phoenix rises in Cirencester Simon Griffiths was managing the Cirencester branch of Appellation suppliers including Boutinot, Berkmann the helm of his new shop, Phoenix Wines, at which point he decided to go it alone. and Alliance and is “open” to working with which he set up with a little financial help deals with a large number of Kentish wine producers. “We are dedicated to maintaining strong relationships with the winemakers, who are invited to come The remainder of the selection is based I ever anticipated because it seems to be interest amongst our customers,” he says. that it expects to grow. Dunlop is proud to say that Macknade the shop.” on wines Griffiths has tasted and decided Nation when the lease came to an end, others. price point because they all offer different and I very much want to reinvigorate that offering to more than 400 wines, a figure The company buys from a number of UK says. “But you can get great wine at every Fast forward a few months and he is at from his dad. Griffiths admits that being in the heart of the Cotswolds his clientele has classic tastes. “I could probably get by with having a shop of three square feet with nothing but white Burgundy and red Bordeaux and THE WINE MERCHANT november 2019 6 were “good for the money”. He says: “I’ve got more Australian that showing really well at the tastings I’ve been to.” Currently he has around 380 lines including spirits and he estimates that he is 80% of the way to full capacity. The company does some direct importing: “We’ve got a Champagne, Bernard Lonclas in Bassuet; very Chardonnay-led, just the sort of thing that I like, and a Côtes de Gascogne producer who does our house red and white,” he says. But he is also working with a number of UK suppliers including Liberty, ABS and Graft. Wholesaling is on the agenda once the AWRS accreditation is in the bag, and plans are also in place for a tasting room on the Adeline Mangevine Hasty despatches from the frontline of wine retailing first floor of the building. Appellation Nation’s other branch, in Cheltenham, continues to trade. A reason to visit south Bristol A new wine bar and shop called Kask opened in Bedminster, south of Bristol, last month. The focus is on minimal intervention and organic wines with a four-tap wine wall that was installed on the premises by G av comes back from a couple of days of hanging out with his cool wine pals in London . “We went to an amazing place in Hackney called Folliard where all they serve is Gamay. I can’t wait till the 21st.” I look puzzled. “Beaujolais Nouveau day!” he exclaims, in disbelief, with a quizzical look that says “you’re in the trade, how can you not know?” Well, I should have remembered, given Uncharted Wines. the amount of enticements I now get up with their university pals Charlie and I couldn’t give a fig. And judging by the Sophie and Henry Poultney, owners of Grace + James in Birmingham, have teamed Natalie Taylor to launch the new business. “Kask is pretty much the same concept as Grace + James,” explains Sophie, “but the main difference is that we have really from suppliers who are all jumping on Beaujolais’ supposed revival. But frankly, dust that gathers on my finer bottles of Gamay, most of my customers don’t, either. Don’t get me wrong. I like some of the homed in on the wine-on-tap thing.” stuff. I’ve been known to really like some corkage fee. Burgundies would be the bottles I saved. There are about 100 lines in stock to buy by the bottle and any can be drunk in for a On top of that there are 12 wines available by the glass at any one time and the business is using Graft and Les Caves de Pyrene for the tap wines. “The idea is that we only buy one keg of each wine and so we always have something different for customers to try,” says Sophie. “We’ve got a number of orange wines, lots of skin contact, lots of chillable reds, sparkling reds, lots of pet nat. We encourage people to have a little sample and taste the wines before buying and we’ve had some great feedback.” of the cru stuff (oh all right, Morgon). But what sort of wines we’re doing here.” supplier lists are awash with carbonic wannabes from Chile to New Zealand, when what I really need are some more rib-sticking but interesting reds that my customers actually want to drink at this time of year. Wines that take them off the beaten track but still satisfy the need for Du vin, du pain, du Boursin. Why all the excitement over something as retro as Nouveau? wants to run a campaign, go ahead. He their beret-wearing shenanigans every November, racing to be the first back from France with their Beaujolais Nouveau – to be consumed with gusto with Boursin and supermarket baguette (they never had time to stock up on food in France, so keen was the contest). That confected smell leaping from their glasses still haunts me. Of course, they don’t touch the stuff now. “Have you seen the prices, Adeline?” Yes. I have. I also find the near-cult worship of through what I suffered. Now, the rest of all around simply because they’ve heard of creating the original smashable red. Now their friends for my neutrality, with You could blame my parents and have to – everyone goes north of the river. But we’ve had a lot of people come from I also blame Beaujolais itself, for a robust and hearty liquid. Beaujolais among younger members of one goes south of the city unless you really extensive list of Beaujolais. if the shop was on fire, my Barolos and She adds: “Kask is in a suburb south of the city, and there’s a joke in Bristol that no opening gambit is telling me about their the trade a bit off-putting. Perhaps I am just envious that they never had to go the trade is trying to sound hip and with it. Pity the poor potential supplier whose THE WINE MERCHANT november 2019 7 When I explain all this to Gav, he looks (as ever) downhearted. So I tell him if he can choose the supplier, the producer and do all the paperwork and promotion. But I want to see all those bottles sold, and for a decent margin. So, here I am working in the shop wearing a beret and a striped T-shirt, looking just like my mother all those years ago. It’s part of Gav’s promotion for his FEELING NOOVY night. We’ll have a DJ playing 80s vinyl and be serving Boursin and baguettes – because Gav’s realised that in our neck of the woods, it’s the best way to get people enthused. Go retro to show people the new Nouveau. Career change in Crowborough Chartered accountant turned wine merchant Alastair Wighton is confident that his recent career change was the environment where people are working under one roof, we’re not only able to because they want to do it. I don’t expect to relationship with our range of offerings.” because they feel they have to, but everyone I talk to in this industry does it make millions but I can make a living out of it and enjoy it.” right move. He and his wife Teresa opened their expand our hours for both sides of the business but develop a more flexible Customers will now be able to select any bottle of wine from the shelf to drink in, and the by-the-glass list is changed frequently – “at least once a week”. shop, Alteus Wines, in Crowborough, East Wine shop is Bourne again independent wine merchant on this site for over 40 years,” says Alastair, “and the Victor Chapman has bought the Artisvin somewhere that sells alcohol. off – I’m not making any massive changes Sussex, six months ago and life is sweet. “There’s been either an off-licence or an reason for holding out for this location store in Eastbourne from Steve Hodden. “We gutted the place completely and but I am having a tasting at the weekend to “The plans are to pick up where Steve left was the local community knows it as revamped it. We had a chap come in to help us with the shelving and we’re really pleased with it. It’s absolutely solid – nothing is falling off there!” Teresa is still working full time as a sales director for Bupa Global, but shares Alastair’s passion for wine. “Teresa studied Organic and natural wines are Forest’s focus Marrying the grill next door get an idea of what the locals like to drink rather than filling the shelves with what I like,” Chapman explains. Chapmans Wine Merchants displays a huge black and white photo of a group of men on board a ship. “It’s the ship that my great-grandfather and his two brothers left Nantes on,” he says. “They were laying for her Diploma many years ago and l When things become a squash and a for Level 3, which incorporated a bursary immediate neighbourhood. customer relationships through a series to be able to do just that. Canadian. “Up the road from here in Meads forces with our Bar & Kitchen space. By back to Canada,” he says. “I’ve worked in did my WSET Level 2 and 3 last year,” he squeeze not everyone is able to expand explains. “I was lucky enough to win a prize their retail space and still remain in the The business will focus on building good Wines in Walthamstow, was lucky enough from the Vintners Company.” of tastings and events. Alastair, having recently escaped the corporate world of boardrooms and long commutes, is happily embracing his new role. “The biggest fun I have is sourcing the wine,” he says “putting together this But Jana Postulkova, owner of Forest She says: “In September we made a big move – all the way next door – to join marrying our takeaway and sit-in service close to my heart.” Eastbourne is familiar ground for the is the hotel management school where I graduated from 28 years ago before going other countries over the years and I’ve been working for the last 15 years with wholesalers all over the south east of Chapman is keen to engage with the local that people are going to be interested in. community and in addition to the weekend So I have actually cast the net quite wide in tasting he mentions, there are plenty of terms of the suppliers I’m using. so friendly and helpful. I’m used to an got a particular focus on the Loire, it is with to stock my shelves.” balance, the right price point; getting stuff It’s been fantastic; people have been Canada, where I’m from. So while I haven’t England, a lot of whom I’m now working collection, trying stuff, getting the right “They’ve all been really supportive. cable across the ocean and they settled in Any wine can now be enjoyed on the premises THE WINE MERCHANT november 2019 8 other events he has in mind. But he says he’ll keep it “light, interesting, informal and fun – not too cerebral and stressful”. Tissue’s a big issue WBC’s in-house artist Gabriela Soria de Felipe has designed some limited-edition wine-themed tissue paper, guaranteed to add a touch of pizzazz to even the most modest of bottles. Available in three designs, the tissue is printed with water-based inks and is priced at £16.50 plus VAT for a pack of £400 sheets. There’s no minimum order and free delivery on orders of £150 and above. A daring decanter Fashioned after the ebullient Macebeo grape, a staple for white Riojas, the styling of The Waiter’s Friend Company’s Macebeo decanter is described as “a daring departure that promises to both intrigue guests while chilling whites to pleasing perfection”. The newly-launched decanter has a capacity of 90cl and comes with a suggested retail price of £49.99. NOT YOU AGAIN! customers we could do without 7. Mrs Carmichaels … You’re not the lady that was here last time, she found me a lovely wine, beautiful it was, pretty label as well, even my sister said how delicious it was and she doesn’t drink, or she’s not supposed to, because she’s on tablets. Begins with a Sh. Do you know that one? I think it was a Sh. Some sort of picture on the front. I can’t remember what of. A flower of some kind? Or it might have been an animal. Do you know the one I mean? No, not a Sherry, I don’t think it was a Sherry. It might have sounded like Sherry. Shandy? No, I don’t like beer, it gives me wind. Shiraz, did you say? No, none of those looks right. Château what? No, no, I can’t even read that tiny writing, and it’s all in foreign. It definitely wasn’t Château. What colour was it? Now you’ve got me thinking. Wine-coloured, definitely. Chablis, did you call it? What’s that when it’s at home? A kind of Chardonnay, you say? Ah – Chardonnay! No, that wasn’t it either. Not Champagne, that tastes like battery acid. Gives me heart burn. Oh, you know the one I mean, it’s won some sort of award. I can’t remember how much the lady said it cost, but I bet you it wasn’t cheap, five pounds or probably even more. Not Chenin. I can’t really tell you what it tasted like I’m afraid, I’m no expert, but it certainly got me a bit tipsy. Schuchmann Saperavi ... might have been that. No, definitely not that. Chappaz Fendant des Copains ... now that does ring a bell … no, that wasn’t it. Hmm. Maybe it was Sherry. Oh come on, you must know the one I mean … DECEMBER DOES NOT EXIST This is The Wine Merchant's last issue of 2019. We now take our usual one-month publication break and will return with our January edition, in which we'll be writing about Australian wine, cava, ready-made cocktails, canned wine and all sorts of other things. It will also be time to launch our annual reader survey, and The Wine Merchant Top 100. Thanks as always to our readers and advertisers for your support this year and good luck with the festive sales period. THE WINE MERCHANT november 2019 9 ANALYSIS Be afraid of the light It’s marketing madness to sell Champagne in clear glass, according to some experts. So why do producers persist with a format that can make wine smell like rotting cabbage or sewage? C Fiona Blair lear glass is ruining countless bottles of Champagne and sparkling wine. Yet there is a with a UV filter that blocks UV light from packaging, despite all the evidence that entering the shop, so I am confident that ultraviolet light can make even the best any clear bottles on shelves we sell will not cuvées smell like mouldy vegetables or suffer light strike – at least until they have human excrement. left the shop! That’s the claim of Tom Stevenson and “Rosé certainly looks less appealing Essi Avellan MW in the new edition of in coloured glass and I cannot imagine Christie’s World Encylopedia of Champagne any producer voluntarily abandoning it, & Sparkling Wine. A section is devoted despite the risks to their product. A very to so-called light strike, which it seems few follow the Cristal route of a protective is being almost wilfully ignored by sleeve, but that invites the question: why Champagne producers – particularly when put it in clear glass in the first place? it comes to blanc de blancs and rosé wines. UV can wreck wine in the space of one hour their creations but insist they are routinely The problem is caused by the breakdown Privately, many winemakers in the region overruled by marketing departments. Lanson, Mercier, Perrier-Jouët, Taittinger, Heidsieck & Co Monopole, Louis Roederer Cristal, Ruinart, AYALA and Gosset are among the marques that sell at least some of their range in clear glass. There are many others. Stevenson and Avellan accept that the presentation can look beautiful but maintain “it makes no sense whatsoever” to use clear glass bottles. “Traditional-method sparkling wines are particularly vulnerable to light,” they say. “At its very worst, affected wine smells of stagnant water, old drains and sewage. At lower thresholds, goût de lumière merely inflicts an otherwise fresh aroma with the barest hint of rotten cabbage.” either – brown glass is the best solution.” He adds: “All of our windows are coated worrying trend for producers to favour this accept that clear glass is inappropriate for but green glass is not a perfect UV barrier of a sulphur-bearing amino acid called methionine, which can happen within 60 minutes of exposure to UV. “Readers are advised never to purchase a clear bottle of any wine straight from the shelf, particularly sparkling wine,” say Stevenson and Avellan. “Clear-glass bottles are marketing madness. What is wrong with the sparkling wine industry that they continue to market a potentially flawed product? The best solution would be to ban clear glass bottles by law.” J eroboams wine director Peter Mitchell MW (pictured right) says Stevenson and Avellan “are entirely correct that it is potentially a big problem, THE WINE MERCHANT november 2019 10 “It is marketing madness, but I am not in favour of banning things just because they are stupid. I try to train our staff to tell customers about the dangers of storing clear glass anywhere that is exposed to light and make sure that we look after the bottles properly.” Tuggy Meyer of Huntsworth Wine in London says: “I have many firm opinions on wine but not religiously strong on this. “We typically have one bottle on display and the rest of any stock still in their original boxes. We don’t leave any bottle out too long and if we do, or it is in the window briefly – very briefly – it will typically be taken home by one of us. “And that is for traditional green glass. For clear glass, the same ENOMATIC principle applies but obviously even more Stories so. I would give a customer a clear glass Champagne from an opened or unopened box and when buying retail, I would request likewise. Currently out of around 35 Champagnes we stock, only one is in a clear glass bottle.” C hristine Marsiglio MW of the WSET School in London says Alex Proudfoot Grape to Grain Prestwich and Ramsbottom “light strike is definitely one of the faults found in wine that is least understood by consumers”. She adds: “It’s hard to know the prevalence of light strike in wines as it tends to happen to individual bottles, rather than batches, as it depends on the storage conditions of the bottle. Clear bottles can really only block around 10% of UV light, whereas green and brown “Nothing ever stays in there for very long. In some shifts we can change the contents of the entire machine twice” bottles can block upwards of 50%; this makes wine in clear bottles much more susceptible to light strike. “Light strike means that delicate, fruity wines will start to smell of cabbage and their fruit aromas will fade. This process is accentuated in sparkling wines because of the dissolved CO2. “As a consumer, I would be wary of Tell us about your wine jukebox, then. It’s an eight-bottle unit that draws the nitrogen from the atmosphere rather than using an argon tank. We’ve had the machine since we opened three years ago. We have four reds and four whites by the glass that we have on indefinitely and that offering changes seasonally. The idea is that if you don’t fancy what we have on by the glass, or you’re feeling a bit more lavish or you want to try something a bit more out-there, anyone can use it. How do you select what goes in there? It depends on our mood and the seasons. Sometimes we might have standard things in there like a New Zealand Sauvignon Blanc and then sometimes we’ll put in a £150 bottle of Montrachet. We had a bottle of Antinori Tignanello 2015 – that was a good one. We’ve had a few really exceptional bottles in there but every now and then you get taken by surprise by a wine that punches well above its weight and its price tag. Does that automatically translate to bottle sales? Yes, absolutely. If you are trying to hand-sell a bottle and the customer is unsure of it, if you’ve got something in the machine and you can just whip out a little taster, it makes it much easier. You have to sell the idea of a wine to somebody but if you can actually give them a taste, it changes everything instantly. How often do you change the selection? The beauty of the machine is that we can keep more expensive bottles open for longer, but nothing ever stays in there for very long. They fly out. In fact in some shifts we can change the contents of the entire machine twice. buying clear bottles, especially for wines that have been on the shelf and exposed to sunlight, or even fluorescent bulbs, for any period of time as there is the risk of tainted wine. “I’m not sure banning clear bottles is necessary but it would be wise for supply chains to ensure wines in clear bottles are What does the Enomatic mean for your business? For the sake of diversity in what people can try in your shop, it’s certainly worth doing. It increases your offering by a massive amount and it opens up a whole different avenue of wines to people that they wouldn’t normally try. It’s earned its money back for us, definitely. It works very well. protected from light and stored in dark conditions. “Perhaps having showcase bottles on shelf could be the answer? The stock to be sold could then be kept in less damaging conditions. “This would be particularly important for any wines that are meant for long-term ageing, be they in clear or darker glass.” Has your Enomatic got a name? It’s called the wine jukebox by quite a few people. THE WINE MERCHANT november 2019 11 Rising Stars Balfour The Red Miller 2018 Last year’s almost perfect conditions got imaginations racing at Hush Heath, hence this still Pinot Meunier. Ivana Mendes Vinoteca City, London T TRIED & TESTED It’s got quirk value aplenty, but that’s not what makes he rewards of wine education for both employers and staff are clear and as Ivana Mendes is finding out, her WSET Level 3 is proving to be a solid stepping stone in her career progression. Since starting at Vinoteca as a waitress three years ago, this lovingly-crafted silky and spicy red so enjoyable to drink. The fruit has ripened beautifully, and there are savoury edges reminiscent of Pinot Noir and a freshness that all adds up to a very classy affair indeed. RRP: £40 ABV: 12% Ivana is now one of the duty managers at the City branch Hush Heath Estate (01622 832794) and her manager predicts she will continue to go far. hushheath.com “We are mainly a wine bar and restaurant with a bit of retail, so it is a little more complex in terms of what we expect from our staff,” says Federico Vicani, general manager at Vinoteca City. “Ivana is really great with customers and she’s very good at managing people. She is running shifts on her own and is in charge of all the staff inductions and training. Ivana is very young and it is harder nowadays to find younger people with such a hardworking attitude. She knows what she wants and it is good for her and good for us; it is great for us to have this sort of person in the business.” Ivana joined Vinoteca when she was 21 and was newly arrived in London. “I did work a little bit with wine before in France, because all restaurants have wine, but nothing as intense as now,” she says. “Here we have a lot of training Tandem Inmune Garnacha 2017 A blend created with grapes from several high-altitude vineyards spread across Navarra, including bush vines that have been in the ground for 80 years or so. There’s dark, meaty, concentrated and saliva-inducing fruit here, and hints of dark chocolate, but also a brisk acidity, all seasoned with a healthy sprinkle of mountain herbs. RRP: £13.49 ABV: 14.5% Hallgarten & Novum Wines (01582 722538) hnwines.co.uk and tastings and all my colleagues and I have had the chance to do our WSET qualifications.” She admits that it was hard, English not being her first language, but she says by Level 3 she had really worked on her language skills. Federico says: “The next step for Ivana is to be a manager and she can do that in a couple of years. Potentially she can go very far at a very young age.” “I love the hospitality part of my job,” says Ivana. “What I really enjoy is the customer engagement. I like to recommend wine and to match wines to food. I am happy if they are happy enjoying their meal and their wine.” Can she see another role for herself within the trade, maybe as a buyer? “That would be great, but for the moment, I am still learning and it takes such a long time to gain experience and knowledge of wine, so I don’t want to jump ahead of myself, but when I’m ready, why not?” she says. Martinus Olaszrizling 2017 Zesty, petillant and dry: “It’s like licking the inside of a cave,” as one of our tasters put it, presumably talking from experience. That would be a Dolomitic limestone cave in Hungary’s Mount Tagyon, the source of the grapes that were fermented in stainless steel and blended after six months on fine lees. Racy and invigorating, with notes of citrus and nuts. RRP: £13.50 ABV: 12.5% Davy’s Wine Merchants (020 8858 6011) davywine.co.uk “I really love the atmosphere at work, it’s great. It is a sharing sort of job; you work with your colleagues and the customers and I think this is really nice – sharing is caring, as you say in English.” Ivana wins a bottle of Artadi Viñas des Gain 2016. To nominate a rising star in your business, email claire@winemerchantmag.com Cortese Vanedda Bianco 2016 A blend of Sicilian Cattarato and Grillo fermented on skins aged in large oak botti, creating a gorgeously honeyed wine that, during certain phases of the moon, could easily be mistaken for New World Chardonnay. Lots of tropical notes on the nose, especially pineapple, followed on the palate by yellow fruits, vanilla, hazelnuts and a touch of spice. Excellent stuff. RRP: £15.99 ABV: 13.5% North South Wines (020 3871 9210) northsouthwines.co.uk THE WINE MERCHANT november 2019 12 Weingut Corvers-Kauter Assmanhausen Pinot Noir 2016 “It’s like a ballerina with a six-pack,” declared winemaker Philipp Corvers at the Graft tasting in London, a reference to the elegance and power of this Rheingau red from a Riesling specialist. It’s bolder DEDICATED TO THE VALUATION AND AUCTIONING OF FINE AND RARE WINES and more rounded than might be expected, thanks to judicious lees contact and a malolactic moment. RRP: £40 ABV: 13% Graft Wine Company (0203 490 1210) graftwine.co.uk Ironstone Petite Sirah 2016 Sometimes wine just needs to be a comfort blanket and this is just the job for a bleak winter evening after a long, fruitless conversation with the Talk Talk technical team. Lovely aromas of blackcurrant and spice, and a luscious, rich but not-too-heavy palate of cocoa, vanilla and blueberries make this pretty irresistible, however uncool it might seem. RRP: £14 ABV: 13.5% Walker & Wodehouse (07813 626491) walkerwodehouse.com MATURE AND INTERESTING WINES WITH NO MINIMUM ORDER Bride Valley Chardonnay 2018 USER FRIENDLY WEBSITE Aspiring young wine writer Stephen Spurrier has chanced his arm with this offering from his chalky west Dorset estate, and a very curious and entertaining beast it is too. The wine spends four months on its lees and sees no oak, resulting in a wine with such saline BUY and citric qualities that thoughts turn inexorably to fish 12% and chips, straight out of the wrapper. RRP: £24.99 RARE & MATURE WINES 12% COMMISSION ABV: 12% Liberty Wines (020 7720 5350) GLOBAL AUDIENCE libertywines.co.uk Monte da Ravasqueira Vinha das Romãs 2016 BI-MONTHLY AUCTIONS Until 2002 the Alentejo vineyard that gives birth to this blend of Touriga Franca and Syrah was a field of pomegranates, and the vine roots now intertwine with those of that former crop. Precision viticulture is doing its job here, as witnessed by a solid, earthy but elegant wine, full of black fruit richness ... but no pomegranate. RRP: £27.30 ABV: 14% Awin Barratt Siegel (01780 755810) abswineagencies.co.uk 5% COMMISSION 2018 JAN MAR MAY JUL SEPT NOV SELL 5% A FINANCIALLY ATTRACTIVE ALTERNATIVE TO BIN-END DISCOUNTING BUY & SELL YOUR WINES AT WINEAUCTIONEER.COM/ WINEMERCHANT THE WINE MERCHANT november 2019 13 BITS & BOBS Magpie Wines won’t need VI-1 forms, for now The UK government has confirmed it will temporarily suspend import certification requirements – known as VI-1 forms – for wines from the EU, for nine months from the date of the UK leaving the EU. Henry Poultney Grace + James Birmingham Favourite wine on my list Probably Gentle Folk Blossoms 2018 from Adelaide Hills. Sophie (my wife) and I first drank this whole-bunch Pinot Noir with winemaker Gareth Belton in his garden by the pool with some of his family and friends. It was one of the hottest days ever recorded in a major city – as Adelaide hit over 46˚C. This wine reminds me of good times. Favourite wine and food match The paperwork was to be introduced if the UK agreed to a no-deal Brexit, and applied to EU wines coming into the UK, as well as English wines exported to EU countries. The WSTA had been urging the government to suspend them again, as it believes shoppers will choose wines without being swayed by the label or price. Participants, who can buy tickets for £4, will get to sample eight 75ml taster glasses of wine along with light nibbles. Lidl’s Richard Bampfield MW said: “At Lidl Châteaux Noir, we want to encourage visitors to see if they can identify a wine’s quality in a completely new setting – using darkness to dispel common prejudices that come with buying wine.” The Sun, October 26 claimed failure to do so would cost the UK • Sotheby’s has branched out from sales been impossible from the start, and would France, Italy and California, which has gone wine industry at least £70m a year. It also into production with the launch of a have added 10p to each bottle of wine. on sale in the US. warned that introducing VI-1s would have 12-strong own-label wine range from Decanter, October 21 The Drinks Business, October 30 © auremar / stockadobe.com Vin Jaune and Comte. Favourite wine trip Last January Sophie and I travelled around Australia and New Zealand searching out some of our favourite organic vineyards. Some of the highlights were Alex Craighead’s Kindeli Wine in Nelson; Anna and Jason Flowerday’s Te Whare Ra, a small winery in Renwick; and Lance Redgwell’s Cambridge Road on the North Island, who make some serious Pinot Noir. In Australia, as well as Gentle Folk, we visited the natural wine wizard Tom Shobbrook who has just moved to a new vineyard in Flaxman. Favourite wine trade person Andrea Asciamprener of Les Caves de Pyrene who helped us set up our first wine list. Top chap with great hair! Favourite wine shop Loki in Birmingham. Loki’s wine educator Paul Creamer first got me into wine and I have been obsessed ever since. I also love Dalston’s natural wine shop and deli run by Kirsty Tinkler called Weino BIB. Such a great place with a focus on sustainability, bag-in-box and wine on tap. The VI-1 forms would have meant more unwanted aggravation for merchants Customers kept in the dark by Lidl Bordeaux boss quits after fraud Lidl is hosting a series of pop-up wine The head of the federation that tastings in the dark. represents Bordeaux’s most acclaimed The events called Châteaux Noir will take place in London, Manchester and Glasgow. By shutting out the light, the supermarket THE WINE MERCHANT november 2019 14 châteaux has resigned amid claims his fraud conviction tainted their image. Hervé Grandeau is standing down as chairman of the Federation of Great Wines ? THE BURNING QUESTION of Bordeaux to try to end the rows that have split the region since his trial. What plans have you been making for the Christmas sales period? � Grandeau and Régis, his brother, who Christmas is a very important part of our calendar and we have a Christmas wine tasting here in the first week of December – we have four suppliers coming down for a ticketed event. We’re all geared up for Christmas; we’ll be getting some more stock in. We’ll shut about 6pm on Christmas Eve and open up again just before New Year. I haven’t thought about what I’ll be drinking with my Christmas dinner yet – I usually wait and see what’s left on the shelves and take a case of wine home. own Château Lauduc, were found guilty of fraud in connection with the sale of almost 800,000 bottles of wine worth more than €1.3m that failed to comply with French regulations. The Times, October 30 Tesco considers Xmas wine bars Tesco plans to take its Finest brand into the on-trade with a string of pop-ups in major cities across the UK over the leadup to Christmas. The supermarket is looking to open wine bars complete with their own sommeliers, offering food tasting platters and ticketed John Barnes The Blue Glass, Bedford � We have a large winter tasting on November 22 that we’ll be doing with about 50 wines. We’ll have lots of our suppliers there and some producers and we’ll have between 150 and 200 guests. We expect to take a reasonable amount of advance orders that day. It gets everyone into the swing of spending money and thinking about Christmas. We’re just finalising a gifting range including a mixture of wine and produce. We’re bringing in some vacuumed packs of local meats with wines to match. ” Kent Barker Stony Street House, Frome masterclasses with an eye to boosting the presence of its posh range over the coming � months. We do buy in more top-end things and look at Christmas gifting. We look at more classic areas such as Champagne, nice Burgundies, good Rhônes, some super Tuscans. We have a bar as well and we are doing a Christmas menu and trying to make it a fun Christmas where you can drink great wine matched with some great food in a party atmosphere. I think you have to make people aware of what you’re doing as early as you can – let them know what’s available and what’s possible. The Grocer, October 23 Aldi hands out free wine diplomas ” Aldi is launching the Aldiploma, its own wine course which will be available for Robin Nugent Iron & Rose, Shrewsbury free. It’s the first supermarket course of its type in the UK and those who sign up will be able to learn about wine and how to pair it with food, without having to spend any money or being subject to any pressure to buy. Aldi’s MW, Sam Caporn, who has devised six online modules and video tutorials, said: “Aldi is known for its affordable, great quality wines so this creates the perfect platform to help consumers try new things and gain the perfect introduction to the world of wine.” ” � This year we’re doing our first Christmas tasting event on November 16. There’s a restaurant two doors down so we’re doing it there and we’re teaming up with a lot of other independents in the village. There’s a couple of butchers who are working alongside us and the fish and chip shop is doing some food on the day, so our Christmas tasting will be a community event with everyone getting together. It’s a nice way for people to taste a wide range of wines and take the opportunity to shop our Christmas promotions on the day. Sarah Mehan Village Vineyards, Barnt Green, Birmingham ” Champagne Gosset The oldest wine house in Champagne: Äy 1584 The Mirror, October 24 THE WINE MERCHANT november 2019 15 ight ideas r b 6: Dynamic Dartboard Discounts . T H E D R AY M A N . Verbosity by the pint W ho’s for a To Øl Sjø Tæhm Speciel Fejø Limited Don’t You Be Messing With The Mikkeller Bar Tender Crew Or They Will Fuck You Up! Dobbelt Vintage Ekstra Extra Barrel Aged Edition Cassis x 2? The beer – for that’s what it is – was among the suggestions in a Rate Beer discussion group for the longest-named beer on the site and, quite frankly, we can’t top it. And, really, why would you want to? There’s little argument that the flair and colour that goes into modern bottle labels and cans has had a transformative and positive effect on beer’s image. But the age of collaboration, novelty/esoteric ingredients and factors such as wood-ageing and unconventional fermentation have also made it increasingly difficult for a lot of people to understand exactly what it is they’re being invited to drink. Of course, Don’t You Be Messing Etc is a wilful gallery-play on its creators’ parts to the nerdy-geek world, but branding such as Gamma Brewing x Lervig Pretty Good Regards Imperial Stout With Pistachio & Coconut is increasingly becoming the norm. Some product descriptions are becoming so long that they’re relegated to tiny type on a side or back panel so as not to obscure the psycho-funk graphics used to achieve shelf stand-out. So here’s a plea to all those colourful craft beer producers out there: keep the lovely bold colours and the Bridget Riley patterns but try to distil your beer names and product descriptions to a few easy-to-grasp words that you put on the front – then let rip with the verbosity on the back if you must. You’ll be doing a favour to retailers who want to sell your stuff and the people who you expect to drink it – and to yourselves. Rob Hoult, Hoults, Huddersfield In a nutshell … Install a dartboard and give customers one dart with a chance to win a discount when they bring their purchases to the till. What the dickens, Rob? “The idea was simple and fun – whenever a customer made a purchase, they had the option before paying of earning a discount. We gave them one dart and they could stand behind the line and throw it at the dartboard. Wherever the dart landed that was their discount, doubles and trebles not included. If they hit the bull, inner or outer, then they automatically won a bottle of my favourite wine. As such the maximum discount was 20% so nothing too horrendous, but for the customer it made their purchase more memorable.” Was everyone a good sport? “The surprising thing was the number of people who missed the board completely and were still perfectly happy. Male customers tended to be a lot more competitive about it and the women were better at embracing the spirit and the sheer joy of it. It engaged the customer, and put a smile on their face and gave them a story to tell.” Have you done this since you’ve added the bar? “Before we changed the shop around we had a lot more space. At one point we put a fullsized table-tennis table in the shop and Ben was the shop champion. If you beat Ben you got a free bottle of wine. Luckily for us he was very good so we didn’t give many bottles away. People were bringing in ringers to try to beat him! “We weep regularly for the loss of that table but there’s no space for it anymore. We might bring back the dartboard but it’s where we’d fit it in without damaging our nowlovely walls, because you do end up with a lot of holes – it was like Swiss cheese.” What would you say to other merchants who might want to give this a try? “I don’t think anyone else is stupid enough to do it! Really, it wasn’t about mucking around; it was about customer engagement. We can be very serious about the wine side of things and by offering a bit of something different so customers can be involved, the dartboard thing seemed like so much fun. I bought the table-tennis table for about £150, so it’s not a big outlay.” Rob november 2019 16 > THE WINEMAKER FILES Caroline Latrive, Champagne AYALA Caroline is a Champagne native who started in her father’s lab, as a consultant to growers, before taking the Oenologist National Diploma and joining Champagne Bollinger. She switched to AYALA after it was acquired in 2005 and became cellar master in 2012. Caroline was recently in London for the AYALA SquareMeal Female Chef of the Year Award goal to increase volume. The Champagne AYALA winery is a gift seven years old she was very curious for AYALA since the beginning. In focus is to have a vinification of a specific put words to my feelings. brut nature cuvée for a long time. I think There’s a picture of me as a girl with my nose in a glass of Champagne. When my youngest daughter was six or about everything and I was like that too. I wanted to find aromas in the glass and In 2004 I had the opportunity for an internship at Bollinger and I stayed one and a half years. The family bought AYALA in 2005 and the cellar master there, Nicolas Klym, needed help. I started at the beginning of 2007 and worked for five years with Nicolas. It was a very exciting time and I learned a lot. We relaunched the range in 2005 and in 2011-12 with the aim of making very clear and pure wine. We moved to only stainless steel vinification to maintain the primary fruit. We maintained the most loyal growers we were working with, people who had the same mindset as us. It was necessary for us to find more growers because we had a AYALA Le Blanc de Blancs 2013 RRP: £55 A very elegant expression of Chardonnay, with fruit from Grands Crus and some Premiers Crus. It spends a minimum of five or six years on lees. There are clear fruity notes and butter and very light pastry too. It's delicious as an aperitif and a perfect match for scallops. Zero dosage has been a signature 1865 the vintage was made dry for the future King Edward VII. We’ve had a it’s a very gastronomic cuvée for more knowledgeable consumers of wine. There’s an echo of history. I think it shows our ability to make a high-quality wine without make-up. It’s very pure; it’s an aromatic explosion, with minerality, citrus, toasted nuts and salinity. I’m not against dosage; I just think we can express the wine better without it. I am a Chardonnay addict. It is such an elegant grape variety. It’s a mysterious one because at the beginning of the vinification it’s a little bit austere and closed and a little bit aggressive, with a high level of acidity. But if you give the wine more opportunity to express its style with age, it’s just an incredible evolution, with such diversity of aromas. for me. I have huge diversity of vats, more than 120 vats of different volumes. The cru and a palette of colours and different expressions to have a wide choice during the blending process. It’s like being a painter. It’s been an incredible harvest. It was very dry and sunny at the beginning of the summer. There was not enough water, and it was too dry for the vineyards but finally we had rain at the beginning of August and it gave the opportunity for the grapes to develop. It was so incredible to see this very quick maturation, one of the quickest we’ve seen for 20 years. It’s amazing the aromas we have in the winery. Very fruity and delicate and clear. Incredible. It’s early to talk about it – but I’m feeling positive! It’s not possible to do this job without passion and enthusiasm. You give a little bit of yourself to the blend. AYALA Brut Majeur AYALA Brut Majeur Rosé RRP: £32 RRP: £37.50 It’s the ambassador of the AYALA style and represents about 80% of our production. It’s 40% Chardonnay, with 40% Pinot Noir and 20% Pinot Meunier. We age it for a long time to give richness, a silkier texture and more complexity. A convivial wine for an aperitif or celebration. It's 50% Chardonnay, 40% Pinot Noir and 10% Pinot Meunier. I want to express red fruit like wild strawberries, as well as blackberries, yellow plums, apricots, violets … sometimes I can sense a touch of rhubarb in this wine. It’s a perfect match for salmon but you can also enjoy it with lemon tart. Champagne AYALA is imported into the UK by Mentzendorff 020 7840 3600 THETHE MERCHANT may 2019 20192019 WINE WINE MERCHANT MERCHANT november september june 2018 THE WINE MERCHANT 17 15 17 JUST WILLIAMS Chain mail David Williams reports back from the autumn flurry of press tastings. Which of the mults, if any, pose the biggest threat to indies these days – or is the trend to boring, industrial ranges continuing? A s we head into the most important trading period of the year, I’ve been doing a little industrial espionage on your behalf. After tasting the ranges of the major multiple grocers (and the last surviving, still justabout-standing multiple specialist), I’ve smuggled out a few ideas about what your customers will be offered as they wheel group’s first-ever half-year loss. Most of the is actually pulling ahead of the pack at the were down by 0.8%, and the food-retailing least in its well-made “W” range of lesser- damage was done in the department store part of the business, but Waitrose’s sales wing has been offloading underperforming stores, shaking up its buying department, and preparing for a switch of online their trolleys past the gondola ends over What are the vinous trends in the range of suppliers, the willingness to be a bit different (it showed two New Zealand moving forward is helped by the unarguable fact that its rivals are either in view? These are questions from a different standstill or moving backwards. retailing universe, maybe, but it’s one that Marks & Spencer, after years of impacts the independent galaxy, and one challenging Waitrose for the most if it’s only to remind you of how not to do Waitrose has increased its focus on own-label Waitrose on top at the top next year. Partnership, with the announcement of the what really marks it out is the still-broad Of course, the perception of Waitrose best shape from a wine quality point of for Waitrose – or at least for the John Lewis Manseng), launched earlier this year. But the £10 to £15 region. Which of the big beasts is currently in the It has by all accounts been a difficult year spotted varietals (Mencía, Marselan, Petit for example), and the strength of its offer in supermarkets? Where are they on price? things. an increased emphasis on own-label, not Albariños at its most recent press tasting, the next couple of months. that is surely worth understanding, even moment. Like all supermarkets, there’s partner when its deal with Ocado expires For all that, however, when it comes to the wine range itself, Waitrose, or Waitrose & Partners as it was rebranded in 2018, The perception of Waitrose moving forward is helped by the unarguable fact that its rivals are either in standstill or moving backwards THE WINE MERCHANT november 2019 18 interesting, dynamic and best quality (if not always best-value) supermarket wine range, has been in retreat for a couple of years now. This is clearly a response to its own well- publicised financial troubles. But, while there is still plenty to enjoy in the M&S range, it was sad to go through a line-up featuring very few new wines, considerably less of the adventurous sourcing from new or emerging countries that earned the retailer so many friends in the presspack in recent years, and a switch to a smaller portfolio of larger, more industrial suppliers focusing on £10 and under. David Williams is wine critic for The Observer The Big Four For now, M&S remains ahead of the Big Four, but only just. The Tesco range, while not exactly dazzling, has emerged from the truly dark place it fell into around the accounting scandal, and there’s now a decent smattering of well-made wines from judiciously chosen suppliers (Feudi San Gregorio, Villa Maria, De Bortoli, Catena) in the finest own-label that dominates the range. It’s a similar story at Sainsbury’s. After years of stagnation when each press tasting felt like a particularly dull experience of déjà-vu, with only the vintage moving on in its never-changing range of own-labels, in the past year or two the company has started to add a few new wines. The Taste the Difference own-label remains the overwhelming focus, but, as with Tesco, there are some good suppliers operating David Hohnen is represented in the new Tesco line-up in there (Markus Huber, Viña Indomita, range to make the pulse race, perhaps. a major overhaul of the range (for good Gaillac; a Marzemino) have injected a little to be, while retaining the odd star buy its reliance on the centralised, standalone CVNE, David Hohnen), and a bunch of more adventurous selections (a red and a white bit of life and fun into what was becoming a stagnant range. Meanwhile, Morrisons continues its solid performance under head of wine operations, Mark Jarman. This is not a But it is dotted with £7-and-under wines that are often much better than they need (some excellent own-label Port and Rioja, for example) in the indie-bothering £12 region. Asda, by contrast, has been keeping or ill) in the pipeline. On the strength of recent experiences of the Asda offer, with supplier arm, International Procurement & Logistics, this can’t come soon enough. itself to itself, with no press tasting this Continues page 20 autumn, and with what I understand is november 2019 19 © TTstudio / stockadobe.com JUST WILLIAMS From page 19 Discounters, The Co-op – and a Majestic revival? Much of what has been happening in mainstream supermarket wine retail has been a response to the rise of the discounters. Aldi, which now has an 8% share of the UK grocery market, is for my money the more consistent of the two Germans when it comes to wine, its vastly improved and improving 100-strong core range outperforming the more piecemeal, hit-and-miss additions of Lidl. It will be fascinating to see what the formation of a centralised wine-buying unit, based in Aldi’s head office in Salzburg in Austria, and led by former head wine buyer at Aldi UK, Mike James, will bring to the range. Much reduced prices, no doubt. But will it have the same market specificity that has made Aldi so much more interesting in recent years? For all the focus on Aldi and Lidl, however, the multiple retailer that has come up with the most consistently interesting sub-£10 wines in recent years has been The Co-op. That was again the case at this year’s Co-op tastings. And criticisms that some of the more interesting wines are not available in much of the company’s sprawling estate have been offset by a website that lets customers track down their nearest stockist. If it seems unlikely that many indie customers would actively travel more than a few miles in search of a Co-op wine, there’s no doubt that a lot of them would still be happy to make the effort to find an in-form Majestic. Having escaped the Naked greed of Rowan Gormley, the company had a relaunch in October. The PR word has of course focused on how Majestic is looking to return Salzburg, famous for being the home of Aldi’s HQ and centralised wine buying team to its traditional strength, the wine to make it a more compelling choice than parcels that recall the company’s old questions of 2020. But, given how tough range, with less of the gimmicky sales fuss, fewer own-labels, and discounted knack of securing vintage gems from the Scandinavian monopolies, rather than the recent tendency of passing off any old listing as a rare and fleeting find. For now, there are quite a few smart buys in the Majestic range. Whether that’s enough THE WINE MERCHANT november 2019 20 a supermarket on price or a local indie on quality and variety will be one of the the retailing environment is for multiple specialists of all kinds, I wouldn’t be surprised if new owner, investment firm Fortress, will be looking to recoup at least some of its £100m investment from store divestments sooner rather than later. THE WINE MERCHANT november 2019 21 BOOK REVIEW Christie’s World Encyclopedia of Champagne & Sparkling Wine is still too new to have a discernible track the changing market with a drier style of settled opinion on its output. with its new-found love of terroir, with Tom Stevenson and Essi Avellan MW standards have gradually risen around the Bloomsbury, £200 W e live in an age of handsoff winemaking, where producers boast less about record, or because Avellan is honest enough to admit that she has yet to form a Champagne obviously dominates proceedings, but perhaps not as comprehensively as might be assumed. As world, and sparkling wines are no longer regarded as inferior, downmarket add-ons to a producer’s portfolio, Stevenson and Avellan have been happy to accommodate more names from Argentina, Australia, Chile and the USA within their pages. what they get up to in the winery and more It works out at about 10p per producer But much of the action is found in old Europe. Avellan describes Italy as “perhaps for the numbers – maintains is impossible. in Franciacorta, Trentodoc and Alta Langa.” assessments of her subjects at least give the impression of a rigorous and consistent thought process. Indeed many hundreds of the producers she mentions are awarded no score at all, either because the producer Encylopedia raised eyebrows in 2003 but might not do so this time with a further There are words of warning for an 80 and sometimes bestowing unrealistic obviously highly subjective, but Avellan’s British Isles, whose chunky share of the lovers consider them undrinkable. thousands of those humans, and the wines some unfortunates. These numbers are to watch, Avellan says. And then there’s the makes regular Cava or New World fizz staggering depth as it introduces us to 98, for Krug, and dips as low as 60 for China, India and Japan are also countries “searing acidity” of many of the wines still of the Encylopedia goes into almost Avellan’s own scale goes as far as industrial for their tastes. ladder, but Avellan points out that the Stevenson and Avellan. The fourth edition the Scandinavian MW who is responsible grands marques a little too formulaic and many of them keep climbing the quality the greatest and matters most,” argue 100s that imply a perfection that Avellan – consumers who might sometimes find the and more multi-vintage blending will help the wines where human intervention is various reasons, often rarely dipping below producers developing fanbases among advances to date. Warmer temperatures specialism. “Sparkling wines are arguably systems are inherently problematic for too is opening new frontiers, with grower- producers based on their remarkable in Champagne, or anywhere that fizz is the 100-point scale. Usually, such numerical Penedès leading the charge. Champagne Avellan offers encouragement to English This isn’t a claim you hear quite so much In all more than 2,000 producers are Corpinnat, Cavas de Paraje and Classic progress made in the past 16 years. they like to insist, is at the controls. profiled, most of whom are rated on a Spain is also attracting attention expanded section, such has been the about how much they don’t do. Nature, that they toil so hard to produce. its famous fizz. currently the most dynamic sparkling wine country, with exciting progress taking place Even Asti, she points out, has responded to industry that seems locked on a course for continued exponential growth and a potential glut of liquid. “Costs are high,” she points out. “Scarcity allows high pricing today, but in the long run English winemakers need to make sure that quality develops accordingly, enabling positioning among the finest sparkling wines in the world.” Graham Holter Avellan describes Italy as perhaps currently the most dynamic sparkling wine country, with exciting progress in Franciacorta, Trentodoc and Alta Langa THE WINE MERCHANT november 2019 22 SPONSORED EDITORIAL FREEDOM OF EXPRESSION Having rebelled against stifling Rioja regulations, Artadi is relishing the chance to make wines like La Hoya, which celebrate the characteristics of individual vineyards B odegas Artadi has no shortage of land to work with, but one plot in particular is getting winemaker Juan Carlos López de Lacalle rather excited. La Hoya, an east-facing vineyard between the river and the mountains in Laguardia, is his current fixation. Four years ago, Artadi finally lost patience with the Rioja Consejo Regulador, arguing it makes no sense to bottle and market wines using terms such as crianza and reserva. By giving up its right to label under the Rioja name, Artadi was now able to make single-vineyard expressions. For López, the “inflexibility” of the Rioja The winery operates along biodynamic principles regulations was exasperating. “The reality is in our area we have different parcels and different expositions, different soils and vineyards of different ages. It’s like a mosaic of different expressions,” he points out. All Artadi vineyards have been worked organically since 2002 The latest UK release is La Hoya 2017, who likes to look after his land properly. Artadi-owned sites. through a metre of clay and limestone into this way in all of its vineyards since 2002. different plots, and this is exciting,” says a 100% Tempranillo made with fruit from 50-year-old vines whose roots delve the bedrock beneath. This limestone strata acts like a sponge, slowly releasing its water content so that the vines never get too stressed. They sound like happy vines. López laughs in agreement. This is a man La Hoya is an organic vineyard and the company has been on a journey to work “The difference is enormous,” says López. There are obvious ecological benefits. “That’s true, but for me it’s about preserving the purity of the vineyard, the soil and the vine.” La Hoya 2017 was aged in older French barrels, López having moved away from Artadi’s previous policy of using new oak. “New oak is too much,” he’s now happy to admit. The end result, in the winemaker’s own words, is not a big wine, but a fruity, energetic and powerful wine. Juan Carlos López de Lacalle and son Carlos La Hoya 2017 is now available in the UK through Pol Roger Portfolio. It could soon be joined by more launches from other THE WINE MERCHANT november 2019 23 “Our idea with this project is to express the purity of the different wines and the López. “We have more than 45 different plots and every year we can discover more about the potential of the wines they produce. It’s impossible for us to produce 45 different wines – but it is my dream!” Find out more Visit or or call 01432 262800 Twitter: @Pol_Roger BUYERS’ TRIP TO SANLUCAR The answer is blowing in the wind The Manzanillas of Sanlúcar get their world-famous character from the salty ocean breezes. Five merchants were invited to sample the sea air for themselves at Hidalgo, the family business that gave the world one of its most beloved Sherries, La Gitana T he tourist season is over in Sanlúcar de Barrameda when we visit in early October. The unassuming Andalusian seaside town has shrunk back to its natural population of 70,000, there are no horses racing on its sandy beach, and there are tables available in restaurants and tapas bars. (According to TripAdvisor, the pick of the bunch is an ice cream parlour.) But one thing never changes in this part of the world: the wind, delivering the salty humidity that gives Manzanilla Sherry its distinctive tang. Hidalgo’s name is rarely far from view in Sanlúcar – its warehouses have been focal points since the mid 19th century. But the name that most catches the eye is La Gitana, the Manzanilla that accounts for around 70% of the familyowned company’s production. Our visit begins at Hidalgo’s highest vineyard and winery, classified in this case as Jerez rather than Sanlúcar. From this vantage point we have clear views of the Atlantic. There’s a stiff breeze up here, as there always is, and it hasn’t rained properly since January. Fermín Hidalgo fetches a mattock and hacks into the powdery white Albariza soil. At a depth of perhaps 30cm, the ground is remarkably moist. These vines aren’t going to dry out any time soon, with the chalky earth acting as a natural sponge. It’s hard to imagine this was once a vast sea, but the fossilised clams in the calcium-rich soil provide the evidence. There’s been a move towards a more natural style of viticulture, says Fermín, who left his job at PwC to join the family business in 2014. He now runs the company with his brothers. “We harvest really late,” he tells us. “We get 10% less volume now, but more sugar content in the grapes, which means we fortify as little as possible.” Fermín takes us on a walking tour of Sanlúcar, the town of his birth, where he is greeted everywhere with smiles and handshakes. His family has been part of commercial and civic life here for generations; the obituary for his father Juan Luis, who died last year, described him reverently as “the last gentleman of Sherry”. Keeping up an old tradition, Juan Luis liked to sprinkle his handkerchief with Amontillado, ensuring he was always surrounded by a glorious scent of the wine he produced. As Fermín keeps our glasses charged with La Gitana and the cheese and jamon keep on coming, we watch the sun explode into the sea before heading off for our evening meal. It’s an opportunity to sample some exquisite local seafood, and to prove how well Hidalgo’s flagship Manzanilla pairs with all of it. S olera systems may look sedate in textbooks, but they can be surprisingly noisy. On our morning tour of Hidalgo’s San Luis winery, or “cathedral”, there’s a samba rhythm playing that turns out to be coming from the pumping machine used to transfer wines between the criaderas. Hidalgo operates two separate soleras in both its wineries, blending the wines THE WINE MERCHANT november 2019 24 from each to create the final product. Some of the solera barrels are almost 150 years old and the building itself dates from the mid 19th century. “I like to say there are particles of wine in your bottle that are from the 1860s,” says Fermín. “And it’s true.” T he system may be ancient, but Hidalgo is experimenting with new ideas. A tool resembling an elongated golf putter has been developed, which is inserted into the barrel to create a sort of batonnage. This way, the dead yeast cells become nutrients for the living flor, intensifying flavour. Fermín reaches for his trusty venencia, dips it into a barrel of unfortified 2017 wine that is likely to be released in limited quantities next autumn, and pours us all a sample. “My first thought is that it’s like a Jura wine – slightly oxidative,” says Colin Thorne of Vagabond. “There are some natural wines, and Savagnin as well, that smell like this – slightly yeasty, miso flavours.” We then try a wine of the same age, but from the first criadera of the solera. There’s a chalky complexity, but “it needs three more years of education”, Fermín says. Next up is a three-and-ahalf-year-old wine from further down the solera, which has more minerality and, according to Thorne, an “olive brine character”. Last of all is the unfiltered, unfined En Rama wine which is already familiar to the group – but which seems even more exhilarating and alive when tasted straight from the barrel. IN ASSOCIATION WITH BODEGAS HIDALGO LA GITANA AND MENTZENDORFF Beyond La Gitana: some other Hidalgo wines Pasada Pastrana Manzanilla A single-vineyard wine with a robust, fullbodied character by Manzanilla standards, produced only with free-run juice. Great with charcuterie or tuna. La Gitana Aniversario Effectively this is Pastrana with an extra three years of ageing – “the oldest and most expensive Manzanilla on the market,” Fermín says. The extra intensity conjures up nutty, smoky flavours and the finish is long and complex. Amontillado Napoleón VORS “The good Amontillados are produced in Sanlúcar,” says Fermín. “You could say that Jerez makes Bordeaux and in Sanlúcar we make Burgundy. Our Amontillado is very fine and very elegant, but still with a lot of yeast and saltiness.” Oloroso Faraón VORS Named after a guerrilla leader who fought against the French, this intriguing wine has pronounced bitter orange characters, toasted nut flavours and a volatile acidity that Fermín admits the winemakers don’t attempt to tame. “The smokiness would make this go well with Polish food,” says Natalia Samsoniuk of Evuna in Manchester. Las 30 del Cuadrado “We want to show the Palomino grape is good for making still wines,” says Fermín, pouring this exotic old-vine wine, which is aged in Manzanilla casks for six months and has a tropical nose despite its dryness. “It reminds me of those candied pineapple sweets we used to get,” says Gill Mann of Jaded Palates. “I always think of Palomino as quite a neutral grape, but this isn’t at all neutral.” For more information, visit or call 020 7840 3600 Email info@mentzendorff.co.uk Larry Cherubino is excited by the potential of Mediterranean varieties in Australia Inside Hidalgo’s “cathedral” in Sanlúcar Merchants’ verdicts Gill Mann Jaded Palates, Devon “The En Rama stood out for me. It was bone dry with a tangy, mineral and ozone freshness reflecting its coastal location. I was particularly struck with the success of food parings, not only with tapas, olives and almonds as you would expect, but also as a serious food wine, perfect with seafood and to be enjoyed as part of a meal. “I’m sure that the new generation at Bodegas Hidalgo’s insistence on quality and consistency, from the vineyards to the solera, will ensure that La Gitana remains at the forefront of Sherry production. The bodega’s provenance, and the finesse of the wines, guarantees La Gitana a place on our shelves.” Colin Thorne Vagabond Wines, London “There is a great deal of care and attention put into La Gitana Manzanilla that belies THE WINE MERCHANT november 2019 25 its price. And for me it was fascinating to taste the different stages of solera ageing that go towards refining the final product. That this wine is well distributed, relatively inexpensive and a benchmark for the style should make us all happy. “I’m not sure the word Sherry is reclaimable for the foreseeable future in a customer-facing role. I will be referring to this style as ‘a salty white wine from southern Spain’ to avoid any ‘oh, I don’t like that’ comments before people actually try the stuff! “I did find myself smitten by the 30-yearold Wellington Palo Cortado. A little goes a long way.” THE CHAMPAGNE DEVAUX MERCHANT PROFILE: THE OLD BRIDGE WINE SHOP Minnie-Mae Stott and Orson Warr, July 2018 John Hoskins MW Huntingdon, September 2019 THE WINE MERCHANT november 2019 26 John’s master plan Very few wine shops are owned and run by an MW, and hardly any are based inside hotels. The Old Bridge Wine Shop in Huntingdon isn’t your typical independent merchant, and that goes for its merchandising policy too J ohn Hoskins had no intention of joining the family hotels business; he was going to be a teacher. But families can be persuasive. After university, in 1985, he found himself lured into a position at Post Hotels. “They got me interested in wine as they thought their wine offer was a mess – which it was,” he says. “It was quite brave of them.” A list that had been dominated by the likes of Piesporter Michelsberg and more local things named after the former Bob Marley are emanating. It’s strikingly retrenched to The Old Bridge, which is A circular Enomatic takes pride of place than the latter. These days, the Hoskinses have bustling with diners of a certain age when The Wine Merchant visits on what for most provincial hoteliers would be a quiet weekday. Hoskins is to be found in the smart wine shop, just beside the reception desk, from where the soothing sounds of Niersteiner Gutes Domtal was given a well maintained, evidently the domain of an owner with ferocious attention to detail. and the shelving bays, each allocated its own taste category (fresh dry whites; light bright reds; earthy reds), are fastidiously arranged. Hoskins is a Master of Wine, responsible for setting the practical exams for MW students. “Being a Master of Wine doesn’t mean I automatically produce a great wine list,” explains a prominent sign on the shop sprinkle of young Hoskins magic. Things wall. “It’s about being selective. Most wine rolled along until 1994, when the family shops try to impress with a big choice split up the business: “I couldn’t stand of inexpensive bottles and superficial working with my uncle anymore,” Hoskins discounts. I want to sell only wines that are freely admits. truly outstanding of their type.” Together with his wife Julia, Hoskins Take us back to 1994 when you took the built up an estate of six or seven pubs as well as The Old Bridge Hotel, an ivy-clad decision to strike out on your own. little town that claims Oliver Cromwell back but my wife and I were lucky to get 18th century townhouse hotel on the My father lent me some money to buy the banks of the Ouse at Huntingdon. It’s a tidy and John Major among its most notable inhabitants: it’s conspicuous there are business. We’ll be forever trying to pay it Oliver Cromwell: Huntingdon royalty THE WINE MERCHANT november 2019 27 Continues page 28 THE CHAMPAGNE DEVAUX MERCHANT PROFILE From page 27 the chance to run our own business. We built it up and at one point I had six or seven businesses including the pubs and it was then that I realised I hated what I was doing. I hated being a manager of six or seven places, feeling like you had no control over them. You’d probably visit them all once a week – here, obviously more – and find out what disasters had happened in the last week. You’d look at the accounts, you’d ring up the accountant ... I didn’t like any of that really. There was hardly any time spent talking about the North Berwick has become “more and more vibrant”, with a growing tourist trade menu or talking to the team about wine, or any other product. I eventually came to my senses about 10 years after that and sold all the pubs and decided to put a wine shop in here, which took two years. This space was a private dining room before. Do you enjoy the business side of The hotel building dates back to the 18th century MW, and then as someone who owns a wine shop and who has bought wine for a long time. Does the shop stand on its own two feet, what you do as well as the wine side of business-wise? things? This wine shop works because it’s part of a It’s only in the last two or three years where I feel I have got the balance right so that I can actually get a measure of enjoyment out of having this business. The day-to-day harassment of running a business: most of that stuff fills me with dread. I do like coming in here and trying to get the team to be as good as they can be, and trying to get the range of wines as good as it can be, and making sure the wine hotel. If I said to someone, “have this wine shop”, I think it would be a struggle. There has to be some reason why on earth you’d put in all this effort and all this and shop – the shop is only 10% of the wine shop makes on its own is not the The last two or three years have been total business – works well. We have a successful business so I think I do understand a lot about the hospitality industry – I’ve been in it for 30 years. I understand a lot about the wine business, having been sort of on the edge of it as an point of difference and it’s amazing how many people come in and look around. We keep the food here simple and classic and people know the wine thing is quite special. What effect has the shop had on the overall business? ‘Wine is about feeling good. If you give someone the nicest moment of their day, then you’re doing your bit’ shop team are really informed. really good and the mix we have of hotel The Old Bridge Hotel unique. It gives us a time into customer care for a relatively small amount of profit. The profit that the point. It’s helpful. We don’t work it out separately – we have the hotel accounts and the wine shop is like the bar or the restaurant or the accommodation – it’s one of the revenue streams. The point is that the wine shop makes THE WINE MERCHANT november 2019 28 The wine thing is a key part of what we are as a hotel. Our overall drinks sales went up by about 30% in the first year of putting the wine shop in, and that was excluding the wine shop sales, because people think of this as the place to come and enjoy a drink. It’s not all alcohol of course. Like more and more places, we are selling alternatives – Seedlip and interesting cocktail-type stuff. THE OLD BRIDGE WINE SHOP What really makes me proud of this place is when you go out at lunchtime in particular, and look around the tables, you see how many people are having a glass of wine – wine that I’m pleased to be associated with. People can knock booze all they like, but wine in particular is about that moment in your life when you’re feeling good. If you give someone 20 minutes of civilisation, hopefully the nicest moment of their day, then you’re doing your bit. You said this shop is 10% of turnover. How much time do you spend here? This takes up half of my time – maybe more because we have the website to keep up to date. I’m a bit OCD about wine – not about too much else, though the team might say I am. You’re constantly changing vintage or changing wine or whatever and trying to keep everything precisely up to date and FMV and Dreyfus Ashby. We do virtually nothing direct. We did import a little bit of wine from Switzerland a few years ago but generally I have no interest in that simply because the reason to do it is to get a better margin. But for us two things weigh more heavily than that. One is space, and the second is freedom. I am fanatical about trying to have wines that are all in really good nick right now. And we have quite a lot of odd cases downstairs where we have started listing something then taken it off, because wine does that dip thing and sometimes it’s just not quite in the right spot. It will be better in two years, so we take it off. Or we’ll say to the supplier, “really sorry but if you’re not prepared to give us the 2018 now then we don’t want the 2017 anymore and we’ll send it back to you”. Tell us about the shelving and the accurate. decision to merchandise by style rather that’s all done on time and that the by-the- shelves. There’s rigidity to what we do. We change the Enomatics at the than country. beginning of the month, and make sure We have a very tight system with the much small detail – keeping all that right the bottle, you can get a maximum of 10 glass list is completely accurate. There’s so just takes a long time. I’ve got a really good team who can do quite a lot of that for me but in the end, someone has to write the text and make the final buying decisions, Generally, depending on the shape of bottles on the shelf and I really like that because it forces me to ask if every wine Wines are arranged by style, not country … deserves its spot. You keep trying stuff all the time because you want each bottle to be really representative of its sort. When I was a student, I worked at L’Escargot when Jancis Robinson and Nick Lander owned it. Jancis obviously did the wine list and when I was there in 1981- 82, she did the list by taste profile and she must have been one of the first. I thought it was brilliant and as a waiter, I could see that it worked. Doing it in the shop is a pain for the staff because people will come in and say, “what Rioja have you got?” or “what Rhône wines have you got?” – and those might be spread across all different sections. But that’s the and that is always me. price we pay – it does encourage people to try other stuff. What sort of a place is Huntingdon? Huntingdon is a really good location. We’re busy all the time. There’s stuff going on, Do you think geography is a secondary who come here for business or pleasure geography is what it is all about. For it’s quite a successful town. We’re close to consideration to flavour? meet here because it’s a central point for a anyone who wants to learn about wine, Cambridge but also a lot of our customers In my personal wine brain, I think the lot of places. it really is all about geography. It’s about understanding the different wine areas of the world, what they are good at and why. How many suppliers are you working with? About 15, including Liberty, Enotria, Hallgarten, Winegrowers, Flint, H2Vin, … but LPs seem to be in a random order THE WINE MERCHANT november 2019 29 That’s the really exciting thing about wine. Continues page 30 THE CHAMPAGNE DEVAUX MERCHANT PROFILE From page 29 What kind of people come into the shop? We have two types of customer. There are customers for whom coming in here is fine, it’s relaxing and interesting and they ‘I think the top end of eastern European countries will really change things for independents in the next two or three years. The potential is pretty huge’ just want to buy some wine. They might Is there a part of the world of wine that have some money or not, but for them it’s The real answer is wherever you go next or set as their limit when they walk through it’s the world leader at the moment. be wine-nerdy or wealthy people. Then you’re finding particularly inspiring or more of an aspirational thing and therefore you’ve just been. South Africa produces the there’s the rest of the world who might interesting? how far they’ll trade up is what they have best value – between £10 and £25 I think the door. We have our most expensive wines on a separate shelf – fine and rare wines. Again, that’s a bit of an aspirational thing. I think the top end of eastern European countries will really change things for the independents in the next two or three years. Croatia, Slovenia, Hungary, Romania … for a lot of them it started from quite a low base from an image point of view, but I think the potential in most of those countries is pretty huge. I think it’s only just getting going and what’s really good from everyone’s point of view is that it’s adding to the diversification of our product. In some ways it makes it more difficult and more complicated for people, but it gives opportunities for the independent John Hoskins became a Master of Wine in 1994. “I thought, I’m going to be the first MW from the restaurant business” THE WINE MERCHANT november 2019 30 THE OLD BRIDGE WINE SHOP merchants to be doing something that the It’s been great for me because it meant consumer finds genuinely interesting and that I was involved entirely in the wine Would I be opening a can of worms if I Does your Institute of Masters of Wine different. business. mention natural wines? work eat a lot of your time? No, not at all. It’s all part of the Yes. That’s why I’m going to stop next that included in the midst of what we sell. programme and it takes a lot of time. It’s diversification. From a sales point of view, I think it is fun and interesting to have But I’m an MW who spends a lot of time teaching, setting and marking tasting papers and you’re trying to assess people’s ability to analyse wines that are true to type – wines that have a sense of place, a sense of variety, a sense of winemaking – something that was intended to be there in the bottle. Natural wines can have lots of character year. For 25 years I’ve been either in education or in charge of that education probably 20 full days and a huge amount of correspondence. It’s been good for me – it’s kept me on the ball. In a way it works against me, because people [reps] don’t suggest stuff, because they’re scared of me – though not because I’m a scary person. How much wine do you buy to keep in but quite often – and it’s a complaint I’ve the cellars? wine has a personality which is almost all the Burgundy we sell, or the good Rhône heard many times before – it’s the funky We do buy a lot of good wine to keep, not unique to that bottle. – lots of weird, interesting stuff. factor, the unpredictability, that means the Purity is what I personally really like in wine, that’s what excites me: when a wine feels like a really good example of Pinot or a really great Barossa Shiraz. I’m very catholic in my taste; I like nearly all styles if they are really good of their sort. The natural thing adds an extra dimension that may be fun for you, the natural drinker out there, but doesn’t help me in my course. Do you remember what prompted you to do the MW exams? What has it done for your career? I passed MW in the same year I set up the business in 1994. I wasn’t really that interested in the hotel business, but quite early on I saw that in the wine business you could make a living. But to get good at it you had to do the academic work. I don’t know how I knew that – I read about it I suppose, but I thought “I’m going to be the first MW from the restaurant business”. for ever but for five to 10 years, so nearly We like to sell wine when it’s mature and tasting delicious. From a financial point of view there are two advantages. One is that quite often you make an extra margin. Most wines that are any good go up in price, so if you can afford to, you keep it for a few years. The other factor is that quite often you find that you have got something that is very desirable for a wine nerd. A lot of the wine we sell on the internet is to people who don’t know anything about us, but they’ve been Googling for particular wines. We’ve kept it back and we’ve got a full margin. When most people buy this stuff they sell it on offer at a lower margin straight away – there is an argument for that too, because it’s good for cash flow. I’d rather wait and make 33% on it. The internet has been really good for people who are into niche stuff, because those obsessives will find you. THE WINE MERCHANT november 2019 31 ARTISANS OF CHAMPAGNE Svetoslav Manolev Master Sommelier Flemings, Mayfair Champagne has definitely always been known as a celebratory drink for special occasions, which is great. However, we are now evolving into consuming Champagne in various other ways. Not only is it a delicious aperitif and celebratory drink but also a wonderful gastronomic wine. Devaux is a perfect example of that with its high quality and aromatic complexity making it ideal to pair with dishes creating ultimate flavour fusions. What I love about the style of Devaux is the versatility in its range of cuvées. From the fresh and creamy Cuvée D to the incredibly mineral and precise Ultra D and the complex and hedonistic vintage D Millésimé … they all have something different to offer, depending on the occasion. Recently, I paired a seven-course tasting menu with the full Devaux range including Stenopé. However, if I had to choose one pairing, it would be the Ultra D with one of our signature dishes – Jersey lobster ravioli with crab and tomato bisque. The low dosage makes it the perfect match for seafood – I could have that every day. We have done a few special events with Devaux in the past, both in the restaurant and in our barrel room. We are currently discussing our next Champagne dinner where we can show the versatility of Devaux’s wines when it comes to food and wine pairing. CHAMPAGNE DEVAUX A premium range of Champagnes from the Côte des Bar, including the Cuvée D: a Pinot Noir-dominant multivintage blend of 15 different vintages, aged for a minimum of five years on lees. Distributed by Liberty Wines Austria plays the right notes Whether it’s fresh, zippy whites or elegant, understated reds, Austria naturally produces the kind of wines that consumers are demanding, as our buyers’ trip to Burgenland and Steiermark proved B ritish consumers are increasingly looking for wines that are naturally lower in alcohol, yet big on flavour – and which express the personality of the land they come from. Burgenland and Steiermark may not be names that are immediately familiar in the UK, but the wines these Austrian regions produce could hardly be more on-trend for the evolving British palate. The Wine Merchant recently teamed up with Austrian Wine to lead a buying trip for a small group of independent merchants, all keen to check in on progress in a country which has long been regarded with admiration by the trade, and which many believe may yet make a breakthrough among consumers. Burgenland is heavily influenced by Hungarian winemaking traditions, sharing as it does a border on the eastern side. Its five Districtus Austriae Controllatus (DAC) appellations are Neusiedlersee, Rosalia, Leithaberg, Mittelburgenland and Eisenberg. Steiermark, whose southern border is shared with Slovenia, has three DAC regions: Vulkanland Steiermark, Südsteiermark and Weststeiermark. Most of the vineyards in Austria are family owned, and more than 70% of total production is white wine. But the group was wooed by the Blaufränkisch variety with its subtle cherry and spice flavours and interesting ageing potential. The Pinot Blancs were generous, with fruit, minerality and well-balanced acidity and appealing apricot, pear and candied fruit flavours – all thirst quenching stuff. The Welschriesling which, despite being the most widely planted variety is hardly ever exported, impressed with its opulent fruit. Perhaps one of the most interesting examples would be the Burgenland Ruster Ausbruch Welschriesling Auf den Flugeln der Morgenrote 2015, which was heavier in body and had lip-smacking baked THE WINE MERCHANT november 2019 32 apple flavours with a hint of Earl Grey. The Chardonnays were enticing, some displaying saline sharpness and others with creamier textures. Sweetie wise, one of the stand-outs was Haider’s Burgenland Eiswein 2015. Made from Grüner Veltliner, with around 25% botrytis grapes, this was candied and honeyed – a perfect pairing for sorbet. Common themes that emerged among the winemakers and estates we visited were the low-intervention approach, the use of natural yeasts, longer skin-contact times and the adoption of organic and occasionally biodynamic methods. This lack of intervention in the winery and the cellar should not be mistaken for wishful thinking; the choices made in the vineyard from the grape selection and the general viticultural practices are made with classic Austrian precision. The aim is simple – to produce the best wines that the terroir allows. Gernot Heinrich, Martin Nittnaus and Gernot Letiner Prieler Schützen am Gebirge, Burgenland “I’m not just a winemaker, I’m a wine drinker,” says Georg Prieler as he fills our glasses with a selection of vintages from his cellar. His vineyards, spread through Schutzen and Oggau, are predominantly planted with Weissburgunder (Pinot Blanc) and Blaufränkisch, with a “tiny” amount of Cabernet and Merlot. His father was inspired by “the big Bordeaux of the 1980s”, but Georg is focused on local varieties. “My heart is with the Blaufränkisch and the Weissburgunder,” he says. Georg describes his move to organics as “logical”: he sees himself as merely a custodian of the land until he passes it on to the next generation. “I want to protect it for my three sons – I think it’s the death of a wine region when they start to kick out the flora and fauna,” he says. Prieler’s wines are all minimal intervention. “We have no recipe to how we make the wines,” he says. “Every decision is very spontaneous; it depends on the grapes. We spend most of our time and our money in the vineyards and in the berry selection, so we can be very lazy in the cellar. We bring to the bottle what we have grown in the vineyards.” The resulting wines certainly impress, especially the spicy Blaufränkisch and intense, apricotty Pinot Blanc. It’s a joy to drink the wild, fresh and complex Pinot Blanc Ried Haidsatz 2017 from 70-year-old vines, listening to Georg’s account of how he obtained the small parcel from another family by a chance meeting: “Well, I was a young winemaker, sitting in the pub in the village …” Georg Prieler Pannobile Gols, Burgenland Schiefer Grosspetersdorf, Burgenland Gernot Heinrich, Martin Nittnaus and Gernot Leitner are three winemakers from the Pannobile collective. This association of nine winegrowers was created in 1994 with the aim of highlighting the quality and character of the region’s wines. Every vintage requires members to put forward a new wine to Pannobile for consideration. The approach of “less is more” in the winery evidently doesn’t apply to Pannobile’s hospitality, as we are greeted in a tasting room that’s as sophisticated as can be. Mood lighting: check; cool bar area: check; glass floor affording an impressive view of the cellar: double check. From Nittnaus, The Tochter 2018 wakes up our tired taste buds with its floral, peppery notes and juicy acidity. Chardonnay Joiser Freudshofer 2016 delights with its popcorn and mint flavours and Leitner’s Pinot Blanc, Salzberg 2019 is all refreshing pear drops. It’s the last day of the 2019 harvest when we arrive, so we catch a fleeting glimpse of winemaker Uwe Schiefer and are left in the capable hands of estate manager Mark Matisovits. The vineyards in Eisenberg, Leithaberg and Purbach have been farmed organically since 2007 and all the wines are unfiltered. “Our philosophy is to have elegant wines that are not too heavy,” says Matisovits. The estate exports more than 50% of its output, mainly to Germany, America, ‘I think it’s the death of a wine region when they start to kick out the flora and fauna’ THE WINE MERCHANT november 2019 33 Continues page 34 Mark Matisovits Muster Gamlitz, Südsteiermark From page 33 Russia, and Japan. Currently only a “small selection” is available the UK via FMV. Victoria from Loki points out she stocks the Blaufränkisch Szapary and the Blaufränkisch Eisenberg DAC Reserve. Wachter Wiesler Ratschen, Eisenberg Christoph Wachter took on full responsibility for the winery in 2010 at just 22 years of age. He farms the family’s 14 hectares in the villages of Eisenberg and Deutsch Schutzen. Thanks to his parents “not going too crazy” with replacing their Blaufränkisch with more fashionable Cabernet and Merlot in the early 90s, most of his vineyards are over 35 years old. He tried organic farming in two vineyards in 2009 and now the 2018 vintage is the first to be officially organic. “But,” Christoph says, “I forgot to put it on the label!” He’s battled frosts two years in succession, but is confident enough to trust his instinct when it comes to winemaking – and rightly so, judging by our tasting. “If you trust your soil and your team picking the grapes you can let the wine do what it’s going to do,” he says. He uses old barrels: “This is a very traditional, very authentic way to produce wine,” he explains. “I don’t want any taste of oak; I like freshness and I like drinkability.” We are blown away by the entry-level Handgemenge 2017, a Blaufränkisch-led blend full of black cherries and a touch of dark pepper. “For me that’s one of the nicest and most easydrinking red styles of the trip,” says Simon Parkinson of Vinological in Chester. “It’s so elegant, with real complexity. I could drink this all day, especially if I had a plate of charcuterie.” The wines are available in the UK through Newcomer Wines. Christoph Wachter Katherina Tinnacher Lackner Tinnacher Gamlitz, Südsteiermark It’s hard to imagine this estate was ever anything but cutting-edge design and beautifully manicured grounds (thanks to the robotic lawn mower busying itself in the background), but until Katherina Tinnacher’s great-grandfather took the plunge in the 1920s and moved away from mixed agriculture to focus on wine, the area was poor. “My great-grandfather founded his own nursery for grafting the wines and he did his own vineyard selections,” Katherina explains. “We still have about 80% of our varieties and vines from those selections.” The last of the harvest is just coming in when we arrive and an early morning walk through the vineyard, under the chestnut trees, via the beehives, reveals a few solitary bunches of Sauvignon Blanc. When Katherina started organic farming in 2007, many local winemakers said it wouldn’t work. But now 15% of the vineyards in the area are also farming organically. The extended skin-contact maceration and the use of 100% malolactic fermentation are much the same methods used by Katherina’s grandfather. Her wines, from the beautifully fragrant yet bone dry Muskateller, Weissburgunder and Morillon (Chardonnay), resonate with a sense of place. “Our parents had to focus first on quality management here and in the vineyards, and now we are the first generation who are really into export,” Katherina says. “It’s hard to understand the area with its bunch of different crus, and our different grape varieties, so we need people who can explain this and tell the stories behind the wines. We always find those people in good restaurants and small wine shops and this is what I want to focus our sales on.” THE WINE MERCHANT november 2019 34 Reinhard Muster is a self-confessed perfectionist and as such he won’t be extending his estate much further. He feels it would be impossible to maintain standards if he spreads himself too thinly. “He has such high expectations of the quality and he only trusts himself,” explains his partner Claudia. Reinhard took on responsibility for the vineyard in 2000 when he was 19 years old. He has taken the production from 30,000 bottles to 10 times that amount. “For our Klassic range we try to produce very fruity and typical wines for the variety and Reverenz is a mix of different vineyards, villages and soil types,” says Reinhard. “We blend grapes with higher acid with grapes with high sugar content.” As we admire a number of huge tanks outside, Reinhard tells us that his next task is creating a building to put them in. “Over the last year we have invested in the vineyards and technical things for producing the wines, but the next thing will be to house these – we have too many tanks outside. Sometimes you cannot imagine the problems we have when we work in winter – we have to remove the snow,” he says. The Steiermark wine style very much depends on hot days and cold nights and with the harvest just in, Reinhard is confident that 2019 is a “fantastic” vintage. There is another more undercover project that Josef has been working on and is particularly proud of: a trio of red, white and rose vermouths made from Traminer. “Delicious, citrusy and Christmassy,” is our verdict. Claudia and Reinhard Muster “I was surprised by the amount of producers doing natural and lowintervention wines. They don’t seem to be doing it with crazy philosophies and practices in the vineyard but just for the purity of the wine that they make. They have such a wide range, from everyday easy-drinking to a little bit more sophisticated, bigger, richer wines. “I think a lot of UK consumers are into that freshness and lower alcohol and easy-drinking styles, so we are the same as their domestic market in that respect. “For me the highlight was the Blaufränkisch: the white pepper and the spiciness, combined with the freshness and the fact they served them a little bit chilled.” Emily Silva, The Oxford Wine Company “That Alpine style – lower alcohol, a little bit more mineral, with some real elegance, particularly with the reds – is where the UK market is heading. People are starting to look for something a bit more subtle. “The reclassification has made things much better because Austria aligning itself with the German system, using the Kabinett, Spatlese and Auslese descriptors, is not the right way to go. Ninety per cent of the wines we tried were quite dry, so separating themselves from that type of classification was a smart move.” Victoria Platt, Loki, Birmingham “I reckon I have a lot of customers who would really buy into the Pannobile story and their more funky wines, and I’m more into that kind of thing. They were so hip and cool. “I’m definitely a fan of the Weissburgunders, especially the older ones, to see how they are ageing and developing. And I never thought I’d fall in love with an Austrian Chardonnay – but we’ve had some amazing Chardonnays on this trip. “These are the sorts of wines that customers would fall in love with too, but it’s a matter of educating people and having a tasting; they are most certainly hand-sell wines. “That’s where our Enomatics will come in and it would help if the producers can get represented by a good agency who will support them with tastings and events like meeting the winemaker.” Anthony Borges, The Wine Centre, Great Horkesley “Perhaps the biggest surprise for me was how much I liked the Pinot Blanc wines. Potentially, in my view this grape could be a real winner for Austria. “Blaufränkisch may be a bit niche but put alongside Nebbiolo, Sangiovese and Pinot Noir, it holds its own. My customers who like Burgundy and savoury Nebbiolos will love Blaufränkisch. “There is a whole spectrum of Grüner Veltliner: very serious, long, mineral, quite suave and sophisticated food-type wines to the very succulent and tropical, and I learned a bit more how versatile the grape is. “The limestone-influenced Chardonnay is great. Those we tasted were very slick and stylish, mostly along the citrus spectrum. The minerality of these wines played a significant but not domineering part, and they were textural and delicious. “Although it was clear the Austrians are aiming for a fresh, food-friendly style of Chardonnay – consciously not stirring lees – the evidence was that the wines evolve Burgundyesque richness nonetheless.” THE WINE MERCHANT november 2019 35 © AWMB / Herbert Lehmann Auriane D’Aramon, Friarwood Fine Wines, London Changing cheese an In their homeland, Spanish wines are bes invited to two masterclasses, in Edinburg The Wedgwood restaurant was the venue for the Edinburgh event W ith Rioja casting such a big shadow across the category, it’s sometimes hard to get adequate visibility and recognition on the shelves for Spain’s diversity of other styles and regions. For many customers, Rioja is Spanish wine – the first and last name that crosses their lips. So how to change perceptions, and encourage more experimentation? The Wine Merchant brought together a group of independent retailers in Edinburgh and Manchester to take a fresh look at a selection of winning wines from this year’s Wines from across Spain were included in the tastings Wines from Spain Awards, and consider how to showcase them alongside the best of Spanish foods. If anyone is going to draw a customer into new avenues of Spanish experience, it’s likely to be an independent retailer, who can offer the kind of personalised advice that these regions and styles may need, especially when it comes to Spanish whites. Gordon Polley of Ellie’s Cellar, with seven shops in smaller towns across central Scotland, agrees. “Our customers tend to think of Spain for red wines first,” he says, “but if you can get them to try the whites they are pleasantly surprised. For Goat and sheep products were the stars of the cheeseboard THE WINE MERCHANT november 2019 36 example, Albariño has our best repeat purchase record – once they’ve tried it, they really want to come back.” g the world with nd charcuterie st enjoyed in the company of tapas or a more formal meal. Merchants were gh and Manchester, to explore the culinary versatility of a range of wines James Kelly, of VINo 13 in Kilmacolm, already has around 20 Spanish wines on his shelves, “from the predictable Tempranillo Reserva to Godello and Albariño in whites,” he says. “Lagar de Bouza is a big seller. A wine like the Ribeiro we tasted is a stand-out wine but would definitely be a hand-sell for me.” Clare Kennaway of Edinburgh’s Great Grog, which has more than 30 wines in its Spanish range, is a fan of Godello as a grape, but understands that it doesn’t have strong recognition among many customers: “If you can get them to taste it, they love it,” she maintains. She also sees the value of a good back story in attracting customers: “I do a lot of corporate tastings, and will Here in Scotland, we’ve got 200 years of Yecla. It’s one of those great wines, if you’re story, but we’re not making enough of it.” Our event was focused on matching the connection with Sherry through the whisky industry – all the roots are there to tell that Looking at reds, and options to draw customers somewhere other than Rioja, our indies were impressed with the Vermador Barrica (a blend of Monastrell and Syrah) tasted at the event. “In terms of value,” says Kennaway from Great Grog, “it was absolutely excellent.” For others, Monastrell is already a winner in store. McDiarmid from Luvians says: “If you look at our top-selling Spanish wines, first is a Rioja, and second is a Monastrell from looking for value and a fairly full-bodied red. It flies out the door.” wines with a selection of quality Spanish cheeses and cured meats, and for several of the group, offering wine in this way is already part of their offering. Laura Hope from Edinburgh-based wine bar Smith & Gertrude says: “We already offer cheese and wine flights, which change each week – we have two flights available, each pairing three wines and three cheeses. Continues page 38 often feature unusual grape varieties – and people really respond to the story behind the wines.” Yet sometimes, there’s a powerful story that could be usefully engaged in the promotion of Spanish wine styles that perhaps isn’t being used to its full advantage. Archie McDiarmid of Luvians in St Andrews sells plenty of whisky alongside the shop’s wines, and thinks retailers are missing a trick with one of the trade’s perennial favourites: “With almost every Sherry drinker we have as a customer,” he says, “we were the ones who introduced them to the drink. Miguel Crunia led the Edinburgh masterclass THE WINE MERCHANT november 2019 37 Authentic wine needs authentic food From page 37 It’s all about educating people.” This is particularly important for the range of Spanish wines which the business lists from smaller producers and wines from off the beaten track. Ian Gribbin, of Abbey Fine Wines in Melrose, already directly imports Spanish cheeses which are sold in the shop, and he’s organising an Eat Spain Drink Spain dinner in late October. “As soon as you put food and wine together in front of people”, ‘As soon as you put food and wine together in front of people, they are happy’ he says, “they’re happy. It just makes sense.” Gribbin believes that organising such events T he Manchester event, which took place at the Salut wine bar and shop in the middle of the city, featured a selection of Spanish goodies provided courtesy of Peter Kinsella of Spanish food specialist Lunya. The speaker was wine writer Simon Woods, who also runs the Manchester Wine School. “I thought it was fantastic,” says Jane Taylor of Dronfield Wine World near Sheffield. “Having Simon there to talk through the wines was just brilliant. I thought the matching of the food by Peter from Lunya was really useful and we’re going to jump on board with the Eat Spain Drink Spain initiative. “We do a lot of tapas anyway because it just adds to the experience.” She adds: “I think it will be really nice to get in touch with Peter and use them for our more upmarket tapas evenings. It makes it that extra point of difference – if you’re drinking really good quality wines from small producers then the same goes for the food – it makes it more authentic. “Interestingly we’d tasted a lot of the Boutinot wines at their tasting the week before, and revisiting those wines – that was fab. Actually some of those wines that I thought were too expensive to put on, I’m now going to put on anyway – I’ve re-evaluated them to go with the food pairings. All of the wines were absolutely fabulous.” Sam Jackson of Chester Beer & Wine has around 60 Spanish wines in her range at any one time. “We did have a good taste of the different cheeses with the different wines,” she says. “There’s always a market for food and wine pairing, especially in Chester where every time you turn around a new speciality restaurant or deli has opened up and they’re pairing up with somebody to do a tasting. It’s whether you do a ticketed tasting for a formal sit-down event or you just have a bottle open and some ham on the side and have people wander in and you have a chat with them.” also really helps to focus the mind of a retailer, “and gets them thinking about what else you can achieve in the future.” The matching of the wines with top Spanish cheeses and cured meats proved thought-provoking, with a recognition among the group of the potential for retailers to extend a customer’s views on a wine in this context. Clare Kennaway is one of those with a clear idea of a winner. “The standout food for me was the Iberico Bellota Jabugo, but I think the best pairing was the Ahumado Curado and the Cornelio Dinastia White,” she says. “They both had a sweet, smoky note that I thought married really nicely.” Fernando Muñoz, new director of Foods & Wines from Spain in London, with María Naranjo, global director of Foods & Wines from Spain, Madrid, who came over especially for the event THE WINE MERCHANT november 2019 38 Merchants came from across Scotland for the Edinburgh masterclass THE EDINBURGH MENU White wines Ahumado Curado from Valladolid A semi-hard, raw sheep’s milk cheese, aged • Fraga do Corvo 2018, Fragas do Lecer, for six months and then smoked intensely DO Monterrei with beech wood. Intense aromas, but • Finca Viñoa 2018, Pazo Casanova, subtle flavours with salty and sharp notes. DO Ribeiro Cured meats Iberico Ham Bellota Jabugo Free range Iberico pigs, fed on a 100% acorn diet produce ham with intense rich flavours and a delicate soft texture – slighty • Raimat El Niu de la Cigonya, Raventos Manchego from La Mancha smoky with hints of saltiness. This ham was Codorniu, DO Costers del Segre Made from raw sheep’s milk, and aged matured for 36 months. • Cornelio Dinastia White Barrel Fermented for 12 months, it has a dry and waxy 2017, Bodegas Cornelio Dinastia, texture, and a mild fruity taste with hints DOCa Rioja of flower and pineapple. Great served with • Fernando de Castilla Antique Oloroso NV, membrillo (sweet quince paste). Bodegas Rey Fernando de Castilla, DO Jerez Cheese Red wines • Vermador Barrica 2018, Bodegas Pinoso, Acorn-fed Chorizo de Bellota Not your average chorizo. Made from 100% acorn-fed Black Iberian pigs, the meat is minced and finely sliced and cured with salt and paprika. Full of flavour. Acorn-fed Salchichon de Bellota DO Alicante Similar to the chorizo but without paprika, A lactic, set raw goat’s cheese aged for • Juan Gil Yellow Label 2018, Gil Family and dotted with black peppercorns, and 20 days, with a firm but velvety texture. Estates, DO Jumilla produced with the finest Iberico pork. Lemony citrus notes with a fuller-bodied • Peninsula Cadalso 2017, Peninsula Moluengo from Villamalea aftertaste. Vinicultores, Sierra de Gredos • Contino Reserva 2015, CVNE, DOCa Rioja • Marques de Murrieta Reserva 2015, Marques de Murrieta, DOCa Rioja THE WINE MERCHANT november 2019 39 A way to make Europe European Regional Development Fund THE MANCHESTER MENU White wines Cheese Meat • Pago de los Capellanes O Luar do Sil Payoyo Grazalema 5j Presa Iberica de Bellota Godello on lees 2017, Pago de los Capellanes This strong pasteurised sheep’s milk Iberico is widely revered as one of the best DO Valdeorras cheese is from the Payoyo dairy high in the meats in the world due to its rich, delicious • Cuarenta Vendimias Cuvée 2017, Bodega mountains of the Sierra de Cadiz. It has flavour. The purebred Iberian pigs roam Cuatro Rayas DO Rueda an intense savoury flavour with hints of freely in the dehesas: sparsely wooded • Malvasía Seco Colección 2017, Bodegas El caramel, almonds and subtle spiciness. It pasturelands that can only be found in the Grifo DO Lanzarote is aged for up to 18 months. south west of Spain. • Montes Obarenes ‘Selección Terroir’ 2015, Bodegas y Viñedos Gómez Cruzado Monte Enebro Morcilla Iberica de Bellota DOCa Rioja A pasteurised goat’s cheese log. A gentle, This cured Morcilla Iberica, or blood soft cheese with a lemony taste. sausage, is a traditional Spanish product San Simon de Costa paprika, garlic and pig’s blood. It is cured This lightly smoked cheese from Galicia for a period of 40 days. made using meat from acorn-fed pigs, Red wines • Estola Reserva 2014, Bodegas Ayuso has a smooth buttery texture and a DO La Mancha pleasant, lightly earthy taste. Casa Riera d’Ordeix Salchichon This Salchichon has been produced by Casa • Mineral del Montsant 2017, Castell del Fish Riera d’Ordeix for over 150 years. The main DO Ribera del Duero Cold smoked sardines with some belly pork for flavour, and simply • Rioja Vega Edición Limitada 2016, Rioja Sardine loins with shiny skin, a meaty and salt and black pepper. Vega-Bodegas Clunia DOCa Rioja juicy texture, a delicate and light natural • Voche Crianza 2015, Bodegas Manzanos smoke flavour. Remei DO Montsant ingredient is best quality leg meat, mixed • Parada de Atauta 2015, Dominio de Atauta DOCa Rioja • Finca Valpiedra Reserva 2012, Finca Zamburiñas Valpiedra DOCa Rioja Baby scallops in a traditional Galician mildly spicy tomato sauce from Conservas All food served at our Manchester event at de Cambados of Pontevedra, Rías Baixas. Salut was kindly supplied by Lunya Eat Spain Drink Spain is running a promotion until November 30 showcasing the potential of matching Spanish food and wine in independent wine shops. Promote a selection of your Spanish wines and you will be sent POS material, a Spanish Gourmet Kit, and featured on the Eat Spain Drink Spain website and social media campaign. If you can encapsulate your promotion in a short report, you’ll also be considered for a £1,000 contribution towards the purchase of any wines from the 2019 Wines from Spain Awards line-up. For further details, contact alison@dillonmorrall.com THE WINE MERCHANT november 2019 40 THE WINE MERCHANT BIRMINGHAM We’re only here for the career ROUND TABLE 2019 In association with SANTA RITA ESTATES Our final report on our Birmingham Round Table, organised in partnership with Santa Rita Estates and hosted by Loki, starts with a talk about the thorny issue of recruitment O ne of the perennial problems facing wine merchants is recruiting quality staff – and retaining them. Yet more and more independents are finding ways of bringing new talent on board and helping these recruits to develop their skills as they embark on a career in the wine trade. David Dodd of Tivoli Wines says he is “particularly lucky” to employ one member of staff who has been with the company for 17 years and is “part of the community – Edward Symonds Saxty’s Hereford people come in to speak to her even if they the same language and use the same has thrived as a result of the responsibility start looking at people like bartenders and don’t want to buy wine”. He also employs a team member who that Dodd gives him. “It’s recognition and reward,” Dodd says. “We worked out what he wanted to do and what his career path was and made sure he’s rewarded for the gains that he’s making.” For Dodd, bringing in young people is a way of ensuring that the business can appeal to customers of a similar age. “You’ve got to get people who can speak Chris Connolly David Dodd Tivoli Wines Cheltenham Connolly’s Birmingham technology as them,” he says. “So I am all for bringing in apprentices. You need to mixologists if you want to diversify your range. I don’t think the future of wine retail is going to be old rich guys selling to old rich guys.” Phil Innes of Loki admits to a few recruitment issues at the company’s Edgbaston branch. “But we’ve become Continues page 42 Phil Innes Gosia Bailey The Wine Bank Southwell THE WINE MERCHANT november 2019 41 Nick Underwood Underwood Wines Stratford Loki Birmingham THE WINE MERCHANT ROUND TABLE: BIRMINGHAM © Robert Kneschke / stockadobe.com From page 41 more ruthless with the part-timers,” he says. “If you don’t fit in within the first month: thank you, see you later.” Innes now has an “amazing” team, including a large number of part-timers – he estimates he has received about 150 CVs from people looking for those kinds of shifts. “We’ve got some fantastic students working for us now,” he says. What credentials does he want in new recruits? “We’re just looking for personality. We’ve found that recruiting from the wine-geek population isn’t necessarily the right thing because even young people that are really into their wine tend to have a different outlook to the majority of our customers. “A lot of our customer base is quite young, and they don’t necessarily want this posh toff that’s drunk wine from his daddy’s cellar all his life and that’s how he knows about wine. They want someone who’s younger and more engaging. We do WSET courses here so we can easily put staff through them, at our cost. Three of our students are doing the Level 3.” Gosia Bailey, who runs The Wine Bank with her husband Chris, has also been fortunate with her recruitment. “We have Sarah, who’s the shop manager, but we still have a lot of control, only because it’s our business and we’ve put everything into it,” she says. “She was straight out of university; I think she’d already done the first level of WSET and Give young team members responsibility and reward and they can flourish, argues David Dodd she was part of the wine society at uni. She’d spent time in Champagne as well.” But Bailey says that generally speaking, finding decent staff has been a challenge for most local retailers. “Retail gets a bad press all the time so it’s not an industry that younger people are interested in,” she says. Not surprisingly, smaller retailers are reluctant to commit to employing a candidate they’re unsure about. “In a small independent it costs so much money ‘A lot of our customer base is quite young, and they don’t necessarily want this posh toff that’s drunk wine from his daddy’s cellar all his life’ THE WINE MERCHANT november 2019 42 even to have them on the payroll with the pension and all that, before you even start training them,” Bailey says. Edward Symonds of Saxty’s believes that “the art of delegation is the key to business”, but admits it’s a difficult skill to master. “We run a family business and we treat all our staff like they’re one of the family,” he says. “You go the extra mile to look after them and make sure they’re happy. As long as you’re looking after your staff, hopefully they’ll stay for a long time. “We have a small team in the Saxty’s Wine bit – there are eight of us now. In the bar business and on the events side, we have a few more. “This year it’s been incredibly difficult to find people to work on events. Everyone’s found it hard to recruit staff.” IN ASSOCIATION WITH SANTA RITA ESTATES ‘I can buy it cheaper online’ The internet may have opened doors for ambitious indies looking to seek out new revenue streams. But it’s also ushered in the age of instant price comparisons H ow much is the independent trade being transformed by the internet? Our panellists in Birmingham were broadly sceptical about the potential for web sales to massively boost their bottom line. Edward Symonds of Saxty’s says his business does “a fair bit” online, but urges fellow merchants to approach e-commerce with caution. “It’s a minefield, there’s no two ways about it,” he says. “There’s a lot of poor decisions you can make online that will cost you a lot of money. “You can get websites built for 20 grand, 30 grand and more, depending on what platforms you’re using, and you can get websites built for next to nothing. You can buy templates for £150 now. “There are relatively straightforward solutions now for online retailing but there is a huge amount of con-merchants out there. There’s a lot of fraud going on, still. corner now. That’s going to be a massive why. You’ve taken half an hour of my time, getting quicker. The industry’s got to catch the one that you preferred, and I think game changer in terms of what you can access. Technology is only improving and up pretty quickly.” Phil Innes of Loki feels that Vivino is too impersonal for his customer base. “You can’t talk to someone, yet, and you can’t physically feel the bottle and that sort of thing,” he says. “Most of my customers aren’t looking for the rock-bottom lowest price. They’re looking for an experience and some expertise.” He argues that Vivino has an in-built bias towards big names such as Moët and Veuve Clicquot, which climb the rankings due to their likelihood of being consumed as part of a celebration. He also criticises the app for not having the ability to make recommendations based on consumers’ tastes and buying history. to scan labels and get instant information B a mixed blessing for independents. But I gave her loads of gin samples and I saw It’s a real headache.” The Vivino app, which allows customers about wine – including pricing from online merchants – has proved something of Symonds believes the technology should be embraced. “That’s the future,” he says. “It’s not going to change and there will be other apps.” He adds: “You’ve got 5G around the ut it’s not only Vivino that is having an impact on consumer behaviour. Innes says: “A few weeks ago, we had one lady who spent half an hour of my time. she was on her phone. “She said, this gin is on Amazon for £5 less than you’re selling for – will you honour the price? I just said to her, absolutely not – but I’ll explain to you THE WINE MERCHANT november 2019 43 which is worth a hell of a lot more than £5; you’ve sampled a load of things and chosen that’s worth £5. “She said to me, I have never thought of it in that way, and bought the bottle. I said, you’re well within your rights to buy that from Amazon but if you do that, in five or 10 years’ time there’ll be nowhere for you to go and try these things and to get an expert opinion.” Vivino: it doesn’t talk to you – yet THE WINE MERCHANT ROUND TABLE: BIRMINGHAM What’s the point of retail awards? Some of our Birmingham panelists know what it’s like to be a winner in a national retail competition. The question is, did it make any difference to their business? © asierromero / stockadobe.com Phil Innes: It’s good for profile raising. If I’m honest I’m probably not entering any more now. lt’s a lot of effort and, for certain ones like IWC, a lot of expense. IWC is extortionate. It’s £200-odd just to apply, I think. Gosia Bailey: I don’t see why you should pay money to apply. I think that’s wrong. David Dodd: I had a phone call this year from one of the awards organisers, basically encouraging me to apply for a certain category because only one other person had applied. They’d looked at my website and said, you’ve got quite a strong range. We won a Decanter award last year. I It can cost around £200 to enter an award, and maybe judges won’t even visit the shop spoke to [retailer awards chairman] Peter it did bring something in. But did I feel journalists, the judges. one of the judges had set foot in my shop. It highly subjective and not very transparent. year and this year we won the Newark Richards that night and said, have you been to our shop – what did you think? And not just devalues it straight away. We did see a spike in online sales, so particularly rewarded for it? Not really. I’m not anti-awards but I do think they’re If you’re going to run awards, make retailers, rather than suppliers and wine SUPPORTED BY SANTA RITA ESTATES Gosia Bailey: We won an IWSC award last Business Awards and we had the biggest response from that, because it was local. We saw a direct increase in sales and there were more people congratulating us because it was based within our area. They recognised it; they understand it. To get an award from the IWSC means nothing to the Our Birmingham Round Table event is the fourth in a series of regional disussions featuring independent wine merchants, organised in partnership with Santa Rita Estates. average person buying a bottle of wine. David Dodd: I quite like looking at awards because I want to know who’s best in The company’s principal wines in the independent trade are Carmen from Chile and Doña Paula from Argentina, the latter being distributed by Hallgarten & Novum Wines. class and why they won the award. But when I’ve visited winning shops, I’m quite underwhelmed. It’s all so subjective and that’s what puts people off awards. It all seems to be about Visit. THE WINE MERCHANT november 2019 44 who you know in the industry. IN ASSOCIATION WITH SANTA RITA ESTATES Glass is still top of the class for indies customers were offered the same wine T quality of the wine,” he says. “And I’m really sometimes dismissed as obsolete and environmentally damaging, and likely to lose their dominant market share as consumers buy into cans and boxed wine, and embrace draught dispense. But the Birmingham panellists need some convincing that bottles’ days are numbered. Chris Connolly recently installed a draught wine system within the shop area of his Birmingham business but found that customer interest was minimal. “I don’t think people could quite understand why it was there,” he says. “And also it’s not particularly eco-friendly. It’s a whacking great KeyKeg, which is non- recyclable, underneath the whole thing. We moved the kit into the bar and we’re now doing draught beer from it instead. So all was not lost but it didn’t really work.” David Dodd of Tivoli Wines recently carried out an experiment in which canned product to be worth less. “People can’t get their heads around it at the moment even though they love the for it.” Connolly believes that the craft beer market has helped consumers change their view of canned products. “It just needs a little bit more time,” he says. “I’m sure it will come. Two years ago if you said ‘canned beer’ you’d be thinking of Carling and Stella. Whereas now you’ve got so many craft beers in cans – and in many cases the quality is much better than out of a bottle.” But for Phil Innes of Loki, cans are not a long-term solution. “I don’t see the point because canning is an environmental disaster waiting to happen,” he says. “Although cans are easily recyclable, actually the mining of the raw material is one of the most polluting industries. And still about 40% of cans get thrown in the bin and taken to landfill. “Glass is one of the most widely and most easily recycled products in the world. Why are we suddenly moving away from it?” © Colin & Linda McKie / stockadobe.com raditional wine bottles are How are spirits doing? from bottles and cans. They perceived the Glass has less environmental impact than cans, Innes argues THE WINE MERCHANT november 2019 45 “We’re not doing the big brands; we’re keeping it local. We just can’t compete with the supermarkets. We’re now going direct to gin producers because we will only hold stock for so long. Once it’s gone, it’s gone, and we replace it with a new product. It’s not a repeat purchase.” Gosia Bailey, The Wine Bank “Unfortunately for us, a lot of our local gins are in Waitrose. But it doesn’t really concern me massively because it’s brand building. The amount of people that have gone in and seen these gins in Waitrose and then come to me … it’s almost like the convenience model of a supermarket. They’re happy to spend that little bit more if they’re buying local. “How many times a day do we get asked for Whispering Angel? We’re £3 more expensive than Waitrose, yet we still sell out, every single month. “We’ve seen a spike this year in aperitifs and digestifs. It makes me think about whether we should go into pre-made cocktails.” David Dodd, Tivoli Wines “Spirits are a big part of the business for us. We get involved in the whisky more than we ever have been, which is great. It takes a long time to build up access to the really good rare stuff. A big focus for me personally is to learn more about it and have confidence in what you’re buying. It’s something we stepped away from years ago but it’s something we’re actively involved in now. We’re selling more gin than ever before. The big request is: what’s new?” Edward Symonds, Saxty’s “The type of customer that is buying gin now is not the type of customer that was buying it two or three years ago. It’s kind of the less-cool customer now. All the people who are ahead of the trend are now on vermouth or something else, like rum … and Sherry, again.” Phil Innes, Loki French Connections These 11 artisanal French winemakers were part of the exclusive tasting in London organised by The Wine Merchant and Business France. These are unique wines from producers with stories to tell – and which are aimed at adding a point of difference to the ranges of independent merchants. If you missed the tasting, don’t worry: you can receive samples of wines from any of these producers by emailing claire.prothon@businessfrance.fr. EGIATEGIA Emmanuel Poirmeur travelled the world in his winemaking career before returning to his Basque coast roots in 2007, founding the EGIATEGIA winemaking workshop. It’s a project where new ideas can flourish, including fermenting wines in marine conditions, for which Poirmeur holds a patent. The process takes place in tanks immersed 15 metres deep in the Bay of SaintJean-de-Luz. This stage corresponds to the second alcoholic fermentation, also known as sparkling method or “tirage” or “prise de mousse” in sparkling winemaking production. “Each and every wine from EGIATEGIA is an occasion of discovery,” says Poirmeur. “Wines made for celebrating; a unique palate; the symbiosis of technical know-how, influenced by the ocean, resulting in truly sensorial wines.” Key wines: DELA DELA White (Ugni Blanc/Colombard); DELA DELA Rosé (Cabernet Sauvignon); DELA DELA Red (Cabernet Sauvignon); ARTHA. DOMAINE TURPIN CHARLES FREY The Turpin family have been winemakers since 1620. They have 16 hectares of Frey was a pioneer in organic winemaking in Alsace as early as 1997. While those vineyards in Menetou-Salon in the Loire Valley. around him scoffed at the science behind organic viticulture, he was creeping out In 1991, after graduating in oenology, Christophe Turpin, his wife Grace and his under cover of darkness to collect nettles to make herbal remedies for his vines. brother Thibault invested their energy and enthusiasm into the estate. It remains a Today, three generations work together, with Julien contributing new ideas. The family affair with their parents still heavily involved in the day-to-day running of the terroir is rich and complex; 17 hectares of vines are based on granite, giving finesse business. and minerality to the wine. Every vineyard has its individual personality expressed The estate is located at Morogues, which is one of the 10 villages of MenetouSalon. Vineyards around the village are based on kimmeridgian limestone and clay. The range include three whites, all made from Sauvignon Blanc; two reds, both in the wines. The range is classified variously as AOC Alsace, AOC Alsace Grand Cru Frankstein, Frauenberg, Blettig and Rittersberg. The wines cover red, white, rosé and crémant made with Pinot Noir; and a rosé, also produced with Pinot. styles. Interesting fact: Acacia barrels are used for the ageing of some of Domaine Turpin’s Look out for: Pinot Noir Quintessence (“one of the best quality-price ratio organic white wines. red wines in France”, according to Bettane & Desseauve). THE WINE MERCHANT november 2019 46 CHATEAU DE GAYON DOMAINE FRAISEAU LECLERC Château de Gayon is a boutique producer based in Madiran, south west France, This 9-hectare estate in the heart of Menetou-Salon is run by Viviane and Philippe near the Pyrenees. The property dates back to the 13th century. Fraiseau. Harvesting is done by hand, and fermentation takes place in small state-of-the-art Viviane took over the running of the domaine in the 1990s and has made stainless steel tanks followed by the ageing of the Tannat in French oak barrels. The enormous strides in terms of wine quality, investing in machinery as well viticultural final blending results in a full-bodied red wine described as “big, sweet upfront fruit and vinicultural research and development. Her son Pierre-Emile joined the business with deep tannins … black raspberry, cassis and currants fill the mouth.” in 2008. The Pacherenc du Vic-Bilh, made with Petit Manseng, is a demi-sec wine with concentrated flavours, best served chilled as an aperitif or dessert wine. In the producer’s own words: “Pure citrus, evolving into baked lemon or candied lemon Half the estate is planted with Pinot Noir for the red and rosé wines, with the other half devoted to Sauvignon Blanc, on argillo-calcareous soils. The fruit comes from sites in Menetou-Salon, Parassy, Pigny and Vignoux-sous- peel.” les-Aix. Interesting fact: The estate is at the southern limit of the appellation, quite close to rosé wines. The family works with Sauvignon Blanc and Pinot Noir, crafting white, red and the mountains. Here the weather is different to most of Madiran and harvests tend to be later. “Our unique terroir results in a softer tasting wine,” the producer says. Look out for: Menetou-Salon Blanc Cuvée Trois Frères. DOMAINE DE CAZABAN DOMAINE DES TILLEULS Nestled in the Black Mountains north west of Carcassonne, at the crossing of the Founded in 1905, Domaine des Tilleuls is a family-owned and operated winery east and west winds, Domaine de Cazaban is part of the Cabardès appellation. dating back five generations. “Our biodynamic wines tell more stories than those of the surrounding country,” Located on the western side of the Loire Valley, near the Atlantic, the 35-hectare the producer insists. Cazaban’s artisanal approach to winemaking includes horses vineyard is spread over gentle rolling hills overlooking the village, on an exceptional in the vineyard and the use of indigenous yeasts in the cellar. The emphasis is on terroir of schist-based soils. The domaine is certified as being of High Environmental minimal intervention and as little SO2 as possible. Value and is sustainably run. “While we identify certain of our wines under the Cabardès appellation, we Grapes are grown in Pays Nantais vineyards, where cool maritime influences and maintain a clear choice to release certain other wines as Vins de France to allow as a long growing season provides a unique environment for Melon de Bourgogne, the much liberty and creativity as we need,” the producer says. dominant grape variety, but also varieties such as Chardonnay, Sauvignon Blanc and The wines, made from Merlot, Syrah, Grenache, Carignan, Vermentino, Roussanne, Cabernet Franc. and Marsanne, are certified by Ecocert and Demeter. Look out for: Les Vénérables – Vieilles Vignes, a complex Muscadet made from fruit Interesting fact: The estate has adapted some of its buildings as holiday lets. sourced from some of the best parcels and given extended lees ageing. THE WINE MERCHANT november 2019 47 DOMAINE DE GUILLAMAN Domaine de Guillaman is a 120-hectare wine estate in the hills of Gascony that has been in the Ferret family for six generations. CLOS DE LA COUTALE This 100-hectare family estate in Cahors estate is divided into three terroirs. There’s a gravel-and-clay section based on a meander of the Lot river; a clay- The vineyard area has gradually expanded through a series of acquisitions. Vines benefit from the richness of a typically Gascon clayey soil on a limestone bedrock, while a mild maritime climate helps the fruit to reach a good level of ripeness. The grape varieties are predominantly white: Colombard, Ugni Blanc, Sauvignon Blanc, Gros Manseng and Petit Manseng make up 80% of the vines. The remaining 20%, Merlot and Cabernet Sauvignon, are used to make rosé and red wines. The family has a firm commitment to the environment, opting for natural methods limestone scree, situated on the edge of the old bed of the Lot; and a terrace of deep clay. With a mixture of modern know-how and a traditional approach to his work, Philippe Bernède, a seventh-generation winemaker, has run Domaine de la Coutale for the past 30 years. With releases made from Côt (Malbec), Merlot and Tannat, these wines are made to keep. In 2010 the Wine Spectator awarded the 2007 vintage 76th out of 100 best of combating pests and disease and encouraging native wildlife. wines in the world. Look out for: Frisson d’Automne, a blended sweet white wine made with Gros Look out for: Grand Coutale, a premium blend of Malbec, Merlot and Tannat matured Manseng and Petit Manseng. in a selection of new barrels for two years. VEUVE AMBAL DOMAINE BADILLER A family business established in Burgundy in 1898 in Burgundy, Veuve Ambal claims Domaine Badiller is very much a family affair. The domaine has passed from to be the largest producer of Crémant de Bourgogne. generation to generation since 1789, with Pierre and Vincent taking over from their Aurélien Piffaut is a direct descendant of Marie Ambal, the original founder, and has been in the company since 2010. father in 2015. The brothers’ approach is “informal, humorous and fun” rather than traditional. Its domaines, situated across six different subregions of Burgundy, are managed using sustainable methods. They are in a village in the Loire that isn’t particularly easy to find, but visitors are always assured a glass of something if they do manage to get there. Vines are located in Châtillonnais, the Auxerrois, Côtes de Nuits and Côtes de Beaune as well as the Mâconnais. In order to produce its Crémant de Bourgogne, Veuve Ambal draws on the unique characteristics of each Burgundian terroir. The wines are available to UK independents through Enotria&Coe. The property is nestled on the slopes of the Indre Valley, in the village of Cheillé, where flinty clay helps bring rounded flavours to the wines. Wines are classified as Touraine and Touraine Azay-le-Rideau and include sparkling styles as well as reds, whites and rosés. Badiller works with Cabernet Franc, Chenin and Grolleau. Look out for: Cuvée Maria Ambal, a flagship crémant made from Pinot Noir and Chardonnay and aged in cellar for three years. They say: “Our philosophy becomes clearer after several glasses.” THE WINE MERCHANT november 2019 48 Due to future expansion, award-winning independent wine merchant, Highbury Vintners, are seeking two enthusiastic individuals with original ideas to join our growing company. Recently acquired by JN Wine, this is an exciting time to join the team with plans for growth and increased investment in the months ahead. The Roles Working alongside the management team, you will be involved in all aspects of running a successful wine company, generating wine sales and gaining experience in all areas of the business (stock management, buying, tastings, social media, etc.) You will also be sponsored through your WSET Level 4 Diploma after six months. The Candidates Self-motivated and commercially aware, you will have a deep understanding of excellent customer service, be friendly and approachable. You will have: • Previous experience in retail or sales • Passion for wine and desire to learn • Physically fit and able to carry 12 bottles of wine • Fantastic communication skills – spoken and written • IT literacy (Office and ePOS experience) • WSET Level 2 minimum (WSET Level 3 advantageous) • UK resident and live within a reasonable travel time of Highbury • Full clean driving licence and comfortable driving a small van The roles involve regular evening and weekend shifts. To apply, please send your CV to Mr Tom Hemmingway: tom@highburyvintners.co.uk THE WINE MERCHANT november 2019 49 Sponsored Feature CUVÉES WORTH WAITING FOR Piper-Heidsieck’s premium Essentiel range showcases the benefits of extended ageing and low dosage. It’s a style that’s perfect for Champagne connoisseurs and food lovers, says cellar master Emilien Boutillat I t’s said that every eight seconds, somewhere in the world a bottle of Piper-Heidsieck is popped open. No other Champagne house has won as many awards in the 21st century. So the position of cellar master comes with some degree of pressure, especially if you’re following in the footsteps of the great Régis Camus. Emilien Boutillat seems to take it all in his stride. Born into a family of Champagne growers in 1987, he grew up helping his father in the cellar and in the winery. He studied oenology and agricultural engineering at Montpellier SupAgro University before embarking on a career in winemaking that took him to New Zealand, Chile, South Africa and, closer to home, Domaine de la Solitude in the Rhône and Château Margaux in Bordeaux. He returned to Champagne in 2013, taking the Piper-Heidsieck hotseat in 2018. Piper-Heidsieck may have almost two centuries of heritage to draw upon in its marketing but much of its focus, particularly in the specialist trade, has fallen on a more recent development: its Essentiel range. “Essentiel was born a few years ago,” Boutillat explains. “The first batch was based on the 2008 harvest. It’s a non-vintage Champagne. The idea behind Essentiel Extra Brut is to have a longer ageing than for the Brut and also to use a lower dosage, so it’s quite dry. “For me, Essentiel and Brut are two expressions of the same style. Brut is a very versatile style of Champagne that everybody can enjoy – people that know Champagne but also new consumers of Champagne. “Essentiel is an expression of the style dedicated way more to gastronomy; fine wine shops, fine restaurants, and to the wine connoisseur. Because that ageing brings more complexity – that is what we are looking for.” With Essentiel, Boutillat is aiming for a style that offers “freshness, crispness, vitality of fruit and elegance”. He adds: “When we launched Essentiel we wanted full transparency, so on the label there is plenty of information regarding the winemaking, the cellaring date, the blend and the date of disgorgement as well. “That information is there for the consumer, for sure, but also for the retailer and sommelier. “Today Essentiel is not only one cuvée, it is a range inside the range of Piper-Heidsieck because you have Essentiel Extra Brut and Essentiel Blanc de Blancs which launched at the beginning of 2019. Might there be some other additions to the Essentiel range? A Blanc de Noirs, for example? Boutillat chuckles at the question but is giving nothing away. “We might have some ideas, but it’s too early to talk about that,” he says. “The Blanc de Blancs is doing really well and although it is Cap Boutillat was born in Reims but has worked as a winemaker all over the world quite new, we are selling quite a lot in the UK, Japan and Italy. The range is a huge success so at some point we might create other cuvées.” What about a zero-dosage option? “It depends on the balance of the wines, so at some point, maybe,” he says. “But what is important for me is not really the amount of sugar but the balance between that sugar and the roundness in the wine; the freshness and the acidity. “The ageing is quite long for the Essentiel range and you have different types of ageing. For the Blanc de Blancs you have 35% THE WINE MERCHANT november 2019 50 of reserve wine so already you have a certain roundness. Then “Just as with the wine I like to make, the balance is important,” there’s ageing on lees, and in the bottle, and at disgorgement we he says. “I think it is good to rely on tradition because that gives a add the liqueur and the sugar and then we strong story and the wine excellence is there, wait, which is also important. so it doesn’t make sense to me to change “All the ageing will make a difference, those things. The rules of giving creaminess and generosity – and we “Those are the rules of Champagne and it’s Champagne are there part have to pay attention to that when adding of the story. But within that you need to but you need to be the sugar.” be creative, you need to ask questions. Yes, In his spare time, Boutillat enjoys creative, you need to we have rules, but it is healthy to be critical participating in improvisational theatre. Is and challenge every step of the process to ask questions that an opportunity to break away from the make sure that we make good decisions. You traditions and regulations of Champagne or need to be open to everything, to follow your does he think he can express himself well senses and what you feel. It is a good balance enough in his day job? between being rational and creative and free.” Piper-Heidsieck ‘Essentiel’ Cuvée Réservée Extra Brut NV RRP £47.59 in gift box Piper-Heidsieck ‘Essentiel’ Blanc de Blancs Extra Brut NV RRP £55.99 in gift box Pinot Noir dominates this lustrous and crisp Champagne, which also contains up to 35% Pinot Meunier and 15% to 20% Chardonnay. Reserve wine makes up 10% to 20% of the final product, which has a dosage of 5 to 6 grams per litre. Boutillat works with 50 different terroirs when blending the wine and is looking for vivacity and fruitiness. “There’s the crispness of the fruit and it’s quite generous in the mouth – because of the Pinot Noir and the Meunier you have a certain roundness,” he says. “It is good paired with fish cooked in a nice sauce, or white meat such as poultry, or veal or pork.” A 100% Chardonnay with 30% reserve wines in the blend and a dosage of 4 grams per litre. It’s described as an elegant, fruity and structured Champagne. “The wine is made mainly from fruit from Côte des Blancs,” says Boutillat, “and maybe 20% of Chardonnay from La Montagne de Reims. There is fruitiness but it’s more on the citrus side, so like lemon and lime. Toastiness is present as well, and minerality, so the pairing will be more shellfish and oysters and grilled fish.” Piper-Heidsieck Essentiel is exclusive to independent retailers and restaurants. For more information, contact Liberty Wines on 020 7720 5350 or visit THE WINE MERCHANT november 2019 51 BUYERS’ TRIP TO BURGUNDY B urgundy can be fiendishly complicated, but there are ways of keeping it incredibly simple. Drink the wine, enjoy the food, stand in the vineyards and you seem to absorb centuries of wisdom almost by osmosis. That was pretty much the formula on a flying visit to the region organised by The Wine Merchant in partnership with Joseph Drouhin and its UK importer Pol Roger Portfolio. No saccharine corporate videos; no drawn-out vertical tastings in laboratory conditions; no interminable presentations about uniqueness of terroir. Instead, we were welcomed with surprisingly laid-back Burgundian hospitality and trusted to make our own judgements about the wines that kept arriving in our glasses. Joseph Drouhin is a family-owned négociant that traces its history back to 1822. It has 73 hectares of vineyards in Burgundy and Chablis, from Montrachet Marquis de Laguiche through to Meursault and to Corton Charlemagne in the Côte de Beaune, and Echezaux to Clos de Vougeot in the Côte de Nuits. Organic and biodynamic viticulture has been the order of the day since 1993, and winemaking is kept as low-tech as possible, with indigenous yeasts and judicious use of oak. New barrels are made from trees individually selected by Drouhin which are then weathered for three years to eliminate unwanted coarse tannins. How much time the wine spends in them depends of the appellation and the characteristics of that particular vintage. This year’s harvest has presented challenges for Frédéric Drouhin, the company president whose sister Véronique is head winemaker. “We have had beautiful weather recently: very warm, dry, sunny, breezy,” he says. ‘Every 10 years we have a perfect vintage with no problems. In the nine other vintages there are always issues’ Buyers on tou in the Côte d’O Forget preconceptions about Burgundy being stuffy. Our welcome at Joseph been friendlier or more informal, with the wines – and the vineyards – takin “The crop looks very nice, but the quantity is very limited. It’s one of the smallest crops we’ve had for many years.” The problems started with three April frosts, followed by poor flowering in a June that was cooler and wetter than normal. July and August presented their own issues, with very hot and dry weather. “So the grapes remain very tiny,” says Frédéric. “They taste beautiful, they are perfectly healthy, with no mildew and no rot, but clearly we have yielded very low. When you taste the berries, it is a pure delight.” Vintage variations are par for the course in Burgundy, and part of what makes the region so magical for wine lovers. Frédéric’s view is that “every 10 years we have a perfect vintage with no problems. In the nine other vintages there are always issues somewhere”. Global warming is making its presence felt. Studies are being done to work out which vines are thriving in today’s conditions, with early indications suggesting that older plants are better suited to climatic extremes than is the case with more recent clones. “We have changed the canopy management,” says Frédéric. “In the past we were trying to fight against possible rot for the Pinot Noir. Today, we are trying to protect the grapes from the sunbeams.” But he adds: “Overall, global warming is more good news than bad news for Burgundy because in the past we lacked ripeness; we sometimes had some firm or grainy tannins which is not the case anymore. So the whites are quite enjoyable THE WINE MERCHANT november 2019 52 Sara Bangert does some late harvesting to drink; they have more colour, good depth and roundness. Consumers like to drink whites earlier than in the past, and the wines are now easier to appreciate young.” O ur host for the two-day trip is the genial Christophe Thomas, whose export duties keep him away from home for 200 days a year. He drives us from Lyon airport to Beaune by way of Beaujolais, where we stop for a leisurely lunch and an invigorating glass or two of peachy Pouilly-Vinzelles 2015 and Hospices de Belleville Morgon 2017 – a ripe, spicy accompaniment to the various main courses that are selected. In the evening, we explore Drouhin’s © EcoView / stockadobe.com ur Or Drouhin could hardly have g care of marketing duties warren of cellars, some dating from the 11th century, that spread for an entire hectare under the streets of Beaune. It is, Paola Tich observes, “like a living museum”, and Christophe removes one of the exhibits – a magnum of 1989 Les Baudes Chambolle-Musigny – to enjoy with dinner. Back above ground, the canapes come round and we sample Drouhin-Vaudon Mont de Milieu Premier Cru Chablis 2017 and a soft, rich Puligny-Montrachet Folatières 2017. Also on the menu are Corton-Bressandes Grand Cru 2013, Beaune Clos des Mouches Premier Cru 2016, Beaune Champimonts Premier Cru 2015 and Beaune Cras Premier Cru 2016. It’s an opportunity too to sample some of the excellent Oregon wines that Drouhin produces with the same Pinot Noir clones, and the same oak, that it uses in France. The wines are superb, but the general consensus around the table is that this has been a clear home win for the Burgundies. D ay two is all about driving through the Côte d’Or, often in a quiet mesmeric state as those famous names keep flashing by on road signs: Gevrey-Chambertin, Morey-Saint-Denis, Chambolle-Musigny, Vougeot, VosneRomanée … It’s almost certainly the most expensive farmland on the planet, and today it’s mostly deserted, apart from a few stray pickers, and occasional carloads of Chinese tourists. To Sara Bangert’s horror, some perfectly healthy bunches have been left on the vines at Musigny, so a couple are liberated in the name of education (she has a The Drouhin cellars cover a hectare under the streets of Beaune masterclass to host back in England the following day). The harvest is effectively over and it’s down to the winemakers to make sense of another unpredictable year in Burgundy. For us, the silent vineyards serve as a sort of place of worship, or maybe simply meditation. It’s grey overhead; the vines are not yet wearing their autumn yellows and golds, but there’s a sense that nature has finished its job and the vineyards are in the gradual process of shutting down until spring. You can read as many textbooks as you like, but sometimes you just have to stand in places like this, breathing the damp air and getting some terroir under your fingernails and on the soles of your shoes. Burgundy is special, perhaps the most special wine region of them all. It’s a privilege to spend some time here, on a quiet morning, doing nothing very much at all. Merchants’ feedback: page 54 THE WINE MERCHANT november 2019 53 OUR GUESTS Paola Tich, Vindinista, Acton Sara Bangert, The General Wine Company, Hampshire Coralie Menel, The Grocery Wine Vault & Bar, Shoreditch Louise Peverall, La Cave de Bruno, East Dulwich Matt Wicksteed, Streatham Wine House, London Andrew Taylor, Taylor’s Fine Wines, Richmond upon Thames BUYERS’ TRIP TO BURGUNDY Wines to remember Sara Bangert The General Wine Company Paola Tich Vindinista Andrew Taylor Taylor’s Fine Wines I just love standing in a vineyard and getting the sense of the place – and then to try the wines close by is probably the ultimate for any tasting. You look at a map and think you have the geography of an area in your head, but it changes when you are actually there and therefore your knowledge improves – particularly the distance between each area. Driving it gives you much more of a sense of how a large area is covered by a producer to create their range of wines. The Joseph Drouhin Puligny-Montrachet Les Folatières 2017 was a surprise to me. I would normally enjoy a wine like this a bit older, so it was interesting to try it young. I thought it had a lovely structure but also more minerality than I would have expected. I will look forward to trying some in a few years’ time to compare. My favourite red was the Joseph Drouhin Savigny-lès-Beaune. I was amazed by its depth of flavour and the weight of the wine, which at that time we compared to the Gevrey-Chambertin 2014. It also moved away from the red fruit flavours I expected to a blackberry tone, and it was great with the beef I had chosen. It wasn’t particularly on my radar as an AC before, but it is now, and I shall look forward to trying more in the future. Before the trip I had no idea just how extensive the Drouhin range is and I think that has to be a great advantage for their future. The fact that Pol Roger are shipping so many of those different wines into the UK also makes us very lucky. I thought we tasted some lovely wines. They’re well-made and they’re well packaged and I think they come in comparatively well priced. They deliver what a lot of people are looking for in Burgundy. I think the Beaune Premier Cru Champimonts 2012 that we had with dinner was the sort of wine I would like to put on my shelf. I thought Les Baudes Chambolle-Musigny 2012 was a treat. Corton-Bressandes Grand Cru I liked as well. They had that nice blood and meatiness to them. Blood and roses is the way I think of a lot of Burgundy and these had that lovely lift to them – lots of consumer appeal. The Pouilly-Vinzelles that we had at lunch was a really appealing type of Burgundy. I think Burgundy will always have a place. Yes, the prices are higher than when we started seven years ago, and you have to look carefully. The wines that work best with us are usually from lesserknown areas like Fixin and Savigny-lesBeaune that still come in at a good price. At Christmas we’ll look for a name like Gevrey-Chambertin. I’m always looking for Pinot Noir that delivers a Burgundy experience at a lesser price. But I think it’s hard for anyone in the world to replicate what you get from a fantastic Burgundy. Touring the vineyards and cellars, getting a sense of place, was my highlight of the trip. My favourites were the 1989 Musigny which we had at dinner and I just thought was fantastic, and the CharmesChambertin. The grand crus and premier crus were just fantastic and the one that kicked off that evening, the PulignyMontrachet Folatières, I thought was amazing. It confirmed my feeling that at the top end there’s not any competition for Burgundian Pinot Noir. It’s getting harder and harder to find things that are really good and not ridiculous money, and that’s my constant quest. I have got a lot of Burgundy customers so it’s quite important to try and find things that are going to have a wow factor for a £30 bottle of wine. I got a very good impression of Drouhin. WORKING WITH JOSEPH DROUHIN Most of the Joseph Drouhin range can be sourced from Pol Roger Portfolio. For more information, visit, or call 01432 262800. Email polroger@polroger.co.uk. Visit and feature produced in association with Pol Roger UK. THE WINE MERCHANT november 2019 54 The Drouhin family Louise Peverall La Cave de Bruno I have a particular memory of the Corton-Bressandes 2013 Grand Cru from the dinner on Monday. It had a beautiful nose and structure. I felt like I’d been wrapped in a velvet blanket; so comforting! And, of course, the 1989 magnum of Musigny was a real treat. We have a good customer base for Burgundy and have found that our range of Beaujolais red and white has become increasingly popular over the past few years, offering a slightly cheaper alternative. SPONSORED EDITORIAL TRADITIONALISTS WHO SOMETIMES BREAK THE RULES Sogevinus has a young winemaking team making some of Portugal’s most exciting still and fortified wines in the Douro S ogevinus brings together four major Portuguese brands – names that are well known among UK independents. The history of the houses may date back centuries, but Sogevinus claims the youngest viticulture and winemaking teams in the Port business. Carlos Alves (right) leads the Port winemaking team, while Ricardo Macedo (left) is in charge of production for Sogevinus’ increasingly successful portfolio of DOC Douro wines. Together with Márcio Nóbrega (viticulture), they are a team that has a deep understanding of the traditions of the region – but know that they don’t always have to play exactly by the book. “We’re not afraid to try new techniques to make new, better and more interesting wines,” says Macedo. Alves adds: “While we respect the traditional ethos of those who have been making wines in this region for centuries, it is important for us to experiment and be brave. “A young generation of winemakers is now living in the region – most of our winemaking team lives in Douro. They want to make new wines, using and mixing tradition and innovation to create unique styles along with exclusive single grape varieties that are now catching consumers’ attention. “We are very conscious of the legacy of the years of winemaking tradition and we are lucky to have some of the oldest reserves of tawny Ports in the region, which allow us to maintain quality and continue to offer rare, amazing blends.” The Sogevinus family Kopke 10 Years Old Tawny "We have definitely seen an increased interest in the tawny category in the past five years," says Alves. "The versatility of tawny Ports has caught the attention of top chefs as well as the world’s media and we are seeing increased sales, demonstrating a growing popularity amongst the public as well. "Our 10 Years Old Tawny is an elegant and complex Port with aromas of spice, dried fruit and hints of wood and honey – it's smooth and rounded, with intense flavours of dried fruit." Kopke is the oldest Port house in the world, established in 1638 by Nicolau Kopke. Kopke has a long-established reputation for producing the finest Ports, especially Colheita, a single-harvest Port that is then aged in oak barrels for as long as necessary. Unlike other Ports, Colheitas are only bottled when an order is placed, so many spend years in barrel. Distributor: Hayward Bros. Cálem, established in 1859, is the market leader in Portugal. Its visitor centre in Vila Nova de Gaia receives over 250,000 people each year. Cálem is admired for its diversity and innovation. Kopke Colheita White 2003 Distributor: Amathus. Since the first Kopke portfolio tasting five years ago when Sogevinus poured the 10 Year Old White, this has been a great success in independents. "Having the full range of aged white Ports available – 10, 20, 30 and 40 – and even a limited-production 50 Year White Port has been a real point of difference from our competitors," says Alves. "It has also won multiple awards in this category, in 2019 and in previous years. White Colheita is very versatile when it comes to food; a couple of our favourite pairings are foie gras or Pata Negra jamon." Barros is the youngest of the Sogevinus brands, established in 1913 by Manuel Barros de Almeida. Barros combines tradition, authenticity and modern values in its tawny and ruby Ports. Distributor: Hallgarten & Novum Wines. Burmester, established in 1750, has British roots. The individuality of Burmester is defined by its character. Its Port and DOC Douro wines are elegant, reflecting the essence of the terroir in which they are grown. Kopke Douro Red 2017 The grapes come from vineyards from 200 to 350 metres high at Quinta de São Luiz. It’s a blend of the traditional Douro Valley grapes: Touriga Nacional, Touriga Franca, Tinta Roriz and Tinto Cão. Says Macedo: "It has a lovely velvety texture as well as a long and fresh finish and is a great food wine, ideal with game, red meat and cheese." Sogevinus has been making DOC Douro wines of exceptional quality since 2006. With 360ha of vines spread over three estates (Quinta do Bairro, Quinta de São Luiz and Quinta do Arnozelo), Sogevinus is committed to sustainable practices that seek to preserve a unique terroir. For more information about Sogevinus, visit THE WINE MERCHANT november 2019 55 SMALL BUSINESS MATTERS WITH WBC It’s not pulp fiction WBC has developed a papier-mache transit packaging system that offers the same protection as polystyrene, but at a lower cost to wine shippers – and the environment. Andrew Wilson explains the many benefits of the PulpSafe system A s many of you well know, owning a small business presents many day-to-day (and longer-term) challenges sent to keep you on your toes. We’ve certainly had ours over the last 30 years. Luckily, we’ve managed to survive and grow at the same time, due in no small part to our loyal customer base. Survival has been achieved by finding a tricky balance between coming up with new products and ideas whilst at the same time trying to ensure our core range of products remains not only fit for purpose, but also the best on the market. I will be the first to hold my hands up and say that transit packaging has not had quite as much time invested in it as it probably should have done. It’s plastic-free debate that’s saturating the couple of weeks? Well firstly rather than then it is down to you and your customers will come in three parts and be top-loading, media and consumer psyche. We need to come up with options and alternatives – to decide what works best for you. About 12 months ago we reviewed our range and started prototyping and testing some new materials that ticked all our criteria: cost, practicality and level of protection. I am not embarrassed to say that the final idea came from the products we had seen in use in the United States that simply needed tweaking in terms of design. Rather than reinventing the wheel, the idea and the material had been right under our noses for the last 30 years. What do paper, water, wine bottles, and couriers have in common? PulpSafe! I called it papier-mache at school not the sexiest of products we sell, but it is a hugely important and growing area for us and maybe the success of it has hidden the need for innovation – it does what it says on the tin. However, times are changing, and the purpose of this column is not about WBC shamelessly flogging its own products, but sharing developments that affect us all, particularly in terms of the but it is more commonly known as moulded pulp paper; you may have already used transit packaging made from it. Essentially PulpSafe is 100% recyclable, biodegradable, compostable pulp made from newspaper and complies with all UK and EU statutory regulations and packaging waste legislation. It has an endless lifespan: after use, the pulp products return to the paper recycling chain over and over again. So what is the big difference with the product we are launching in the next THE WINE MERCHANT november 2019 56 being a clamshell design like a suitcase around the bottles, the PulpSafe system! P olystyrene is an important product for us. Like I said, it does what it says on the tin –, which is probably why many opt for an inflatable pouch system (Safe Air) that is cheaper and takes up far less space, although its eco-credentials are worse than polystyrene and it’s made in the Far East, unlike the UK born-and-bred polystyrene. The system is 100% recyclable, compostable and biodegradable Our job is not to tell you what is right or carrying glass). What we want them to do • STOP PRESS – We are delighted to have The new range of PulpSafe packaging standards. contemporary, courier-proof gifting pack for being insured through their networks. details online at wbc.co.uk. wrong, but to offer you choices and options so you can make your own decisions. will tick every box that both polystyrene and Safe Air fall down on. It’s eco-perfect, space-saving, offers excellent levels of protection and is made in the UK, which we are really excited about. It means that there is now a solution out there that you can use cost-effectively with couriers’ hub-based sorting systems. We are in active discussions with the courier companies trying to get them to approve this packaging, but this is meeting with varying degrees of success. It harks back to my last article in that all of the couriers secretly want your business but many of them say they will not carry glass (whilst at the same time is promote the fact that they want your business as long as it is packaged to agreed On that basis, they should then take responsibility for well-packaged parcels started working with those clever guys at Flexi-Hex who have developed a smart, one and two bottles. Another eco-friendly option to add to the range. Watch out for We intend to keep the pressure up and will keep The Wine Merchant posted. The new range of PulpSafe packaging is being produced as we speak in conjunction with our great friends at Cullen Packaging. It will be available in 1, 2, 3, 6 and 12-bottle sizes. If this is floating your boat as much as it is ours, feel free to contact us now for samples and full details and as always with any of our products, we appreciate the usual honest Wine Merchant reader feedback. THE WINE MERCHANT november 2019 57 Andrew Wilson of WBC THE SPIRITS WORLD Nine Elms: “Somewhere between a wine and a vermouth” Ready for Dry January Consumers are cutting down on their intake and looking for alcohol-free alternatives that offer them some of the flavour of the real stuff. There are plenty of options to choose from, says Nigel Huddleston T he no- and low-alcohol spirit category is advancing at such a rate that it’s threatening to become the new gin – not for the volumes that are being sold but just for the sheer numbers trying to get on the bandwagon. If we accept that Diageo-backed Seedlip was first of the tidal wave, in just five years since it launched we’ve witnessed the arrival of: • Pernod Ricard’s alt-gin Ceder’s and its dark spirit take Celtic Soul • Stryyk from the creators of Funkin cocktail mixers, which comes in Not Rum, Not Gin and Not Vodka varieties • William Grant’s spiced citrus and wild blossom pairing Atopia • Colombian-inspired and juniper-based Caleño • Sea Arch made with sea kelp by two Torquay pub owners • Borage-fuelled non-alcoholic gin Borrago • The “enlightened spirit of Persia” Xachoh • Senser, from an ex-City banker who jacked it in to work with plants after an epiphany in a yoga class. Though there’s a tendency to round them all up under the “non-alcoholic spirit” banner, many of them shy away from the description for fear of direct comparison with the real thing. Among the recent entrants is Three Spirit, a trio of drinks whose combined ingredients list comes to more than 60 items. The drinks aim to replace “feelings” GIN whisky tequila the secret's out douro deal pays off Us and russia reach agreement A back story involving William of Orange, a two-year search through the rare books section of the British Library and a recipe whose quantities are written in a secret code sounds like something out of a Dan Brown novel but it’s actually the creative process of Amsterdam Craft Gin’s new 1689 gin. Available through Glasgow-based Distilled Brands. Sweden is an unlikely meeting place for the worlds of wine and single malt but that’s where we find Vintersol, Mackmyra whisky’s latest addition. The whisky is a collaboration with the Douro region’s Quinta Do Vallado and has spent 16 months in Swedish oak casks that previously held its port. Villa One may be the first tequila named after half a football result … or maybe not. It is, however, definitely a collaboration between US pop star Nick Jonas of the Jonas Brothers, menswear designer and record label owner John Varvatos, and the Stoli Group of Russian vodka fame. Cellar Trends imports it to the UK. THE WINE MERCHANT november 2019 58 – the early-evening sharpening cocktail, stress-busting amaro and vermouth occasions, and indulgent late-night whisky moments – rather than replicate spirits per se. Co-founder Tatianna Mercer says: “They are alcohol-free spirits in that they appear or behave like spirits. But the notion of non-alcoholic can be a bit negative – about removing something and creating a lesser version. We wanted to think about what we could put in a drink to offer an alternative. “If you’re not drinking, it often feels like there’s nothing that rivals the real thing, so let’s not try to recreate that.” M ercer recognises that it might be hard for retailers to communicate to their customers the benefits of alcohol-less products that typically cost between £25 and £30 a bottle. “The price point is often the issue for the customers, so you have to make something that justifies that, and for retailers to sell at that price they need to understand why it costs what it does. “Wine stores are very good for us. If people can talk about wines in depth they will be able to educate customers on these products as well. “We are very happy to do training and supply samples and we’ll provide booklets and point-of-sale.” Everleaf is the creation of Paul Mathew, who owns three London bars including The Hide in Bermondsey. He favours the term non-alcoholic aperitif, rather than spirit, for the drink which is flavoured with 18 botanical extracts, inspired by his previous life as a conservation biologist. “We extract differently according to the best way to get flavour out of that particular botanical: some are traditional distillation with alcohol, some are steam distillation, some are maceration, some are vacuum distillation,” he says. The blend of extracts is then cut with a textured base liquid – rather than water as full-strength spirits are – made from gum acacia and a Chinese plant called the voodoo lily. The proportions used of any of the extracts that contain alcohol is low enough to keep the final abv down to 0.3%. “The textured base gives structure and mouthfeel and we build that as a carrier of flavour,” says Mathew. “These products have to be better than their alcoholic relatives to succeed. “Making a non-alcoholic gin isn’t the way to go because, by comparing it with gin, you’ve immediately lost something.” Nine Elms hails from the fresh produce quarter of south London and aims to provide an alternative to wine for food pairing. It’s made from four types of berry and aromatised with herbs, spices and tea to provide tannins, acidity and body. Brand consultant James Morgan says: “Rather than trying to start with wine and take the heart out of it by removing the alcohol we decided to try to build from the ground up. “It sits somewhere between a wine and a vermouth in style.” Co-founder Simon Rucker says it’s the product’s savoury style and lack of overt sweetness that separates it from fancy soft drinks. “There’s the famous quote from the American poet James Whitcomb Riley to the effect that if it looks like a duck, swims like a duck and quacks like a duck, it’s a duck,” he says. “While you could argue that we are technically a soft drink, we’re not because we don’t behave like a soft drink. “It’s a wine bottle and it acts like a wine in the glass.” whisky gin jewel purpose casks grapefruits of their labours More fortified wine cask finishing action in the form of Nectar Grove Batch Strength, from Scotch whisky maker Wemyss Malts. The wine in question is Madeira and the whisky comes in a bottle and box inspired by the island’s jewellery and ceramics. It weighs in at 54% abv and costs around £55 a bottle in retail. It’s certainly been a big month for colliding drinks styles with much-admired Huddersfield craft brewer Magic Rock entering the spirit world with a gin made in collaboration with Adnams, the Suffolk brewer-distiller. High Wire Grapefruit gin is inspired by Magic Rock’s pale ale of the same name. No prizes for guessing the star guest botanical. THE WINE MERCHANT november 2019 59 Led by Baileys Almande, cream liqueurs have magically turned dairy-free for these plant-based times. Besos de Oro is a more offbeat take, a blend of brandy and horchata, a milky Spanish drink made from tiger nuts, which aren’t nuts at all, ticking another allergy box in passing. It’s also gluten-free. This take on the classic Brandy Alexander is an indulgent but lighter-inalcohol festive treat as we’ve double-downed on the 18% abv Besos and snipped out the fullstrength brandy. 50ml Besos de Oro Original 25ml Crème de Cacao Nutmeg Fill a shaker with ice. Add the Besos de Oro and crème de cacao and shake until cold. Strain into a Martini glass. Sprinkle with nutmeg to garnish. MAKE A DATE © dudlajzov / stockadobe.com WineBarn Annual Portfolio Tasting The award-winning German specialist is promising an “interesting day of discovery” at its 19th annual event, which it’s calling Grip the Grape. The event will be attended by winemakers from across Germany, representing a range of terroirs and winemaking styles. There will be around 120 wines on show, including elegant Spätburgunders (Pinot Noirs), dry Rieslings and sparkling Sekts. WineBarn director Iris Ellmann, a native German, will be on hand to advise on wine styles, tasting, food pairings and more. The WineBarn has been described by Steven Spurrier as “the jewel in the crown of German wine merchants”. For the past four years it has been named German Specialist Merchant of the Year at the International Wine Challenge. To register or for more information, visit Vineyards at Bacharach in the Mittelrhein bit.ly/Portfolio-Tasting-2020. Tuesday, January 21 Tuesday, January 21 Monday, January 20, 11am-5pm B1, Southampton Row Wednesday, January 22 Army & Navy Club London WC1B 4DA Grange Tower Bridge Hotel 36-39 Pall Mall London SW1Y 5JN London E1 8GP Monday, January 27, 1pm-5pm The Balmoral Hotel Australia Trade Tasting The “biggest, brightest and most diverse showcase of Australian wine in the UK” returns to London and Edinburgh. Taste crisp vibrant whites, standout sparkling, elegant reds and thrilling alternative varieties, from the rogue to the Princes Street Edinburgh EH2 2EQ French Wine Discoveries Wine 4 Trade continues its event dedicated to French Wines in London with the 18th edition of the tasting. French producers including family Borsa Vini Italiani The latest edition of Borsa Vini Italiani will feature around 60 Italian wine producers, the majority of which are looking for UK representation. The event will also include at least one masterclass. refined. estates, co-ops and associations from Thursday, January 23 wineaustralia.com/att-2020. a.couillabin@gfa.fr. London SW6 1HS details and registration can be found at various wine regions will be represented. Contact Anne-Catherine Vigouroux: THE WINE MERCHANT november 2019 60 Chelsea Football Club Fulham Road SUPPLIER BULLETIN LOUIS LATOUR AGENCIES 12-14 Denman Street London W1D 7HJ 0207 409 7276 enquiries@louislatour.co.uk Vidal-Fleury Festive Promotion Established in 1781 in the Northern Rhône Valley, Vidal-Fleury is the oldest continuously operating winery in the region. Today Vidal-Fleury vinifies and ages wines from across the Rhône Valley, focusing on the choicest terroirs, allowing ample time to age and mature the wines. It has a number of wines on special offer from Louis Latour Agencies for the festive season. Best value is the Côtes-du-Rhône Rouge 2016, a Grenache-led blend, typical of the southern Rhône, which would be an excellent choice for versatile festive drinking. Its strawberry and cherry aromas and palate of chocolate, prunes and violets make it a match for richer dishes. Vidal-Fleury Crozes-Hermitage 2017 and Saint-Joseph 2015 offer more in the way of depth and complexity if you are looking for something more serious. From the northern end of the region, these wines have the darker fruit characteristics of the Syrah grape with its trademark peppery finish. The real delight is the sweet Vidal-Fleury Muscat de Beaumes de Venise 2017 which comes in both 75cl and 37.5cl bottles. This Vin Doux Naturel fuses refreshing acidity with fresh and dried fruit characters to produce an elegant sweet wine that can be enjoyed with fruit-based desserts, cheeses or as an aperitif. buckingham schenk Unit 5, The E Centre Easthampstead Road Bracknell RG12 1NF 01753 521336 info@buckingham-schenk.co.uk @BuckSchenk @buckinghamschenk A top 10 Rioja! The Izarbe Rioja Reserva is another hidden gem in our portfolio which has now been recognised as one of the 10 best wines at the 10 x 10 Wines of Rioja tasting, selected as Chair’s Choice by Sarah Jane Evans MW. Produced by Bodegas Familia Chavarri, this wine is aged in American and French oak for a minimum of two years, followed by three years in bottle. Izarbe Reserva is well balanced with candied red fruits and toasted oak notes. The family-owned Bodegas Chavarri combines tradition and modernity and is one of the oldest wineries in the Rioja Alavesa region. The winery has managed to retain a family atmosphere as well as a cutting-edge style introduced by the new generation spearheaded by Ruth Chavarri, whose passion and enthusiasm are the driving forces behind Bodegas Familia Chavarri. THE WINE MERCHANT november 2019 61 SUPPLIER BULLETIN walker & Wodehouse 109a Regents Park Road London NW1 8UR 0207 449 1665 orders@walkerwodehousewines.com @WalkerWodehouse Walker & Wodehouse Christmas Promotions W&W’s Christmas promotions exclusively for independent merchants are in full swing. Featuring some of our best wines and spirits, we’re bringing you some fantastic offers as we head into the festive season! Ask your Account Manager for more details. 10% off – Llopart Brut Reserva 2016 seckford agencies Old Barn Farm Harts Lane, Ardleigh Colchester CO7 7QQ 01206 231686 julie@seckfordagencies.co.uk @seckfordagency Seckford Agencies Ltd Kalfu: cool-climate Chile in the press © rh2010 / stockadobe.com Organic, traditional method, superb quality sparkling wine. So good that they decided not to call it Cava anymore. Llopart are one of nine producers who broke away from the Cava DO to form their own brand, Corpinnat. Kalfu, meaning blue in the native Mapuche language of southern Chile, is owned by Vina Ventisquero. It offers a range of cool-climate wines from coastal regions which benefit from long slow ripening resulting in exceptional complexity – as the press have noticed: Victoria Moore, Saturday Telegraph 5/10/19 … From Atacama desert … VV makes very good Sauvignon Blanc here. Kalfu Sumpai Sauvignon Blanc 2017, Huasco Valley – which tastes like white asparagus, white currants and Badoit RRP £17.95 – £18.95 Decanter Magazine October 2019 Panel Tasting – Chilean Pinot Noir Kalfu Molu, Casablanca 2017 92pts Highly Recommended Delicate and refined, with red berries and a touch of light oak, and there’s some floral complexity with good freshness and vitality RRP £10.25 – £10.95 Kalfu, Kuda Pinot Noir, Leyda 2017 90 pts Highly Recommended Quite rich, with well integrated oak, some lovely strawberry and herb tones, and a touch of black cherry. Maintains fruit freshness in a hot vintage. RRP £12.95 – £13.99 Tim Atkin MW 2017 Kalfu Sumpai Syrah Leyda Valley One of a handful of brilliant cool-climate Syrahs from Chile, Kalfu hails from a terraced vineyard that sits just 6.5 kilometres from the Pacific. Peppery, meaty and refreshing, with clove, raspberry, red cherry fruit, fine-grained tannins and understated oak. RRP £17.95 – £18.95 THE WINE MERCHANT november 2019 62 Malbec without make-up liberty wines By David Gleave MW 020 7720 5350 From Argentina to Cahors, winemakers are seeking purity over power … order@libertywines.co.uk result, they have been able to capture a more precise and distinct expression of The comprehensive profiling of Mendoza’s diverse soils carried out for Altos Las Hormigas by “terroir hunter” Pedro Parra led them to move away from using oak. As a site in their wines. Co-founder and winemaker Alberto Antonini explains: “Malbec is a fragile variety that is easily overpowered by young toasted oak. Fortunately, there is a growing appreciation for a fresher, more refined and elegant style.” @liberty_wines Using their experience in Argentina, Antonio Morescalchi (also of Altos Las Hormigas) and Pedro Parra were excited by the potential of Cahors’ limestone soils to produce the same distinctively fresh, elegant and textured style of Malbec that has been their focus in Mendoza. This is how Causse du Théron was born. Winemaker Leo Erazo says: “Cahors offers a huge diversity of soils and the sites that we are working with give some structure but also delicacy, which we want to retain in its purest form through to the glass.” 18 IN CH AL AL RNATION TE LEN G E 2 MERCHANT OF THE YEAR 0 Auténtico is Colomé’s sole expression of Salta Malbec with no oak influence. Winemaker Thibaut Delmotte acknowledges that “with unoaked wine, your vineyard management and quality of fruit is exposed – it is a wine with no make-up! Unoaked wines have an honesty and integrity that we think appeal to today’s discerning consumers who are moving towards fresher, more elegant styles of Malbec.” Save the date! FMV 24-34 Ingate Place Battersea London SW8 3NS 020 7819 0360 @fieldsmorrisverdin @fmvwines FM&V will be hosting or participating at the following tastings early in the new year. Please save the date or confirm your place by emailing Sophie McLean and Will Protheroe at fmvmarketing@fmv.co.uk . FM&V’s Burgundy En Primeur Tasting Tuesday 14th January, One Great George Street, London SW1P 3AA 10am-4pm Wine Australia: Australia Trade Tasting Tuesday 21st January, B1, Victoria House, Bloomsbury Square, London WC1B 4DA 10am-5pm Wines of Austria Tasting Monday 3rd February, Illuminate at the Science Museum, 5th Floor, Imperial College Road, London SW7 2DD 10.30am-4.30pm Viñateros! A Spanish wine revolution! Tuesday 25th February, Lindley Hall, Elverton Street, London SW1P 2PB 10.30am-5.30pm. Seven of our producers will be participating: Gramona · Raventós i Blanc · Domaines Lupier · Dominio do Bibei · Rafael Palacios · Telmo Rodríguez · Bodega Mustiguillo. We look forward to tasting with you then! THE WINE MERCHANT november 2019 63 SUPPLIER BULLETIN AWIN BARRATT SIEGEL WINE AGENCIES 28 Recreation Ground Road Stamford Lincolnshire PE9 1EW 01780 755810 orders@abswineagencies.co.uk @ABSWines richmond wine agencies New arrivals for RWA … The Links, Popham Close Hanworth Middlesex TW13 6JE Finca Dinamia is a pioneer in Mendoza for organic and biodynamic wines. 020 8744 5550 info@richmondwineagencies.com @richmondwineag1 Finca Dinamia, Mendoza Founded by Alejandro Bianchi (third generation winemaker from Bodegas Bianchi). Its whole ethos revolves around care for the planet and ensuring that it focuses on responsible production. It crafts sustainable, high quality wines embracing ecological packaging with natural cork and recycled cardboard boxes. Buenalma Malbec 2016 The production of this biodynamic wine starts naturally with wild yeasts followed by a gentle, partial oak ageing. Deep ruby in colour with a rustic nose of brambles, dried herbs and cloves. The palate is full bodied with concentrated black fruits and a slight spicy pepper note on the finish. RRP £20.99 Long Barn Zinfandel 2016, USA With the huge success of Long Barn Pinot Noir, we have extended the range to include the Zinfandel. Aged in French and American oak, this wine expresses powerful aromas, with sweet forward fruit and a mellow finish. RRP £13.99 Email us to receive a copy of our festive offers booklet THE WINE MERCHANT november 2019 64 Famille Helfrich Wines 1, rue Division Leclerc, 67290 Petersbach, France cdavies@lgcf.fr 07789 008540 @FamilleHelfrich Famile Helfrich have a range of Crémants from every region and style across France. The richer, creamy style offers far much more complexity than that “Italian one” and at a fraction of the price of its more famous cousin! To celebrate the festive season we have a selection of our finest cuvées from Alsace; all hand-harvested and produced under the watchful eye of Nicolas Haeffelin – from a family with a winemaking history stretching back to the 1600s. Arthur Metz Cuvée 1904 An expressive blend led by Pinot Blanc, Auxerrois and Pinot Noir, with exclusive parcel selection for maximum quality fruit. Extended lees contact of 24 months gives an unrivalled finesse, with no malolactic fermentation to keep the fresh peach and nectarine characteristics at the fore. Arthur Metz Perle Noire A jewel of the Arthur Metz crown, stylishly clad in its allblack attire! 100% Auxerrois (a cousin of Pinot Blanc); again we have a minimum of 24 months on the lees for a rich mousse with complex buttery, brioche over baked peach and apricot. Aperitif perfection. Metz Extra Brut They’re all smiles to your face Arthur … Minimum 18 months on the lees & residual sugar of just 3g gives a crisp, mineral style of Cremant. Distinctive cuvée of Auxerrois, Chardonnay, Pinots Blanc, Noir and Gris. Complex profile with hints of almond, apricot and delicious toasted notes. hallgarten wines Saint Clair Godfrey’s Creek Noble Riesling, Marlborough | 2016 “A deliciously complex dessert wine, with a bouquet of poached apricot, candied citrus and white clover honey. Opulent and silky on the palate with rich orange, lemon and cocoa notes leading to a long, smooth finish.” Dallow Road Luton LU1 1UR 01582 722 538 Berton Vineyard Reserve, Riverina, Botrytis Semillon | 2017 “A luscious wine with intense and layered aromas of orange rind, apricot and honey. The vibrant palate delights with notes of orange, grapefruit, butterscotch and biscotti which carry through to a beautifully balanced and persistent finish.” RRP: £17.49 RRP: £12.49 sales@hnwines.co.uk FESTIVE @hnwines The festive season is the ideal time for your customers to indulge in something sweet. Once the turkey is out of the way, there is only one way to help wash down the Christmas pudding. Quady Winery, ‘Essensia’, California, Orange Muscat | 2016 “Vibrant orange in colour, this wine delivers luscious sweet oranges and apricots on the palate. The bittersweet orange marmalade notes balance well with the zesty citric acidity.” RRP: £13.99 Michele Chiarlo ‘Nivole’, Moscato d’Asti | 2018 “Floral aromas are seamlessly complemented by peach and apricot notes on the fragrant bouquet. The gently sparkling palate is delicate, light and creamy; with a silky texture and a refreshing finish.” 90pts: THE WINE MERCHANT november 2019 65 SWEETS RRP: £10.99 SUPPLIER BULLETIN fine wine partners Thomas Hardy House 2 Heath Road Weybridge KT13 8TB 07552 291045 info@finewinepartners.co.uk Fine Wine Partners The home of some of Australia’s most iconic, beloved and highest awarded producers. Contact us to continue to spread the message of Australia’s diversity, character and share in these amazing wines. Time to Celebrate hatch mansfield Taittinger Folies de la Marquetterie NV New Bank House 1 Brockenhurst Road Ascot Berkshire SL5 9DL A ‘Domaine’ wine made only from Taittinger’s own vineyards. A sumptuous Champagne with a rich story marking Taittinger’s heritage. 01344 871800 info@hatch.co.uk Oozing style and panache and made with foodies in mind. @hatchmansfield Please contact Hatch Mansfield for further information #TaittingerTime THE WINE MERCHANT november 2019 66 mentzendorff The Woolyard 52 Bermondsey Street London SE1 3UD Bin 27 shares the heritage & style of the great Fonseca Vintage Ports, as well as much of their depth & character. Blended for consistency of character & quintessentially Fonseca in style, this reserve blend provides reliable & affordable value. 020 7840 3600 Pairing Suggestions Fonseca Bin 27 pairs beautifully with desserts, dark chocolate & berry fruit. It makes an excellent match for chocolate truffles or cassis & raspberry flavoured macaroons. It also goes splendidly with the full flavour & rich creaminess of cheeses such as Taleggio, Brie de Meaux, Camembert, Vacherin Mont D’Or or Pont l’Evêque. info@mentzendorff.co.uk “There’s an uninhibited explosive dark cherry and black berry-fruited lusciousness to Fonseca’s Bin 27 that is lovely on its own but next-level gorgeous with chocolate puddings.” David Williams, The Observer - 21st April 2019 For details and pricing please contact your account manager enotria & COE The 12 Wines of Christmas 23 Cumberland Avenue London NW10 7RX Christmas is coming, and now is the time to make sure that your Christmas wine list well as plenty to satisfy those who have their go-to festive favourites! has something for everybody, from the taste traditionalists to the flavour mavericks. Here we have a range which caters for even the most quirky and unusual palates, as Get in touch with your Account Manager to find out more. A customer who purchases a case (6x75cl) of 020 8961 5161 any wine which forms part of the Enotria&Coe Christmas wine offer (‘The Wine Offer’), will @EnotriaCoe have their account credited to the amount of £5.00 in January 2020. The Wine Offer applies to the following wines: Massaccio Verdicchio Classico Superiore, Trimbach Riesling Reserve 2017, Louis Michel Chablis 1er Montee de Tonnerre 2018, Quinta do Crasto Douro Superior White 2017, Kir-Yianni Ramnista Xinomavro 2015, Poliziano Rosso di Montepulciano, Santadi Carignano del Sulcis Riserva, Cruz de Alba Ribera del Duero Reserva 2013, Georges Vigouroux Ch. Haute-Serre Grand Vin, Stag’s Leap Wine Cellars Hand of Time, Peregrine Pinot Noir, Bonterra Young Red. THE WINE MERCHANT november 2019 67 The Wine Merchant issue 86 (November 2019) Published on Nov 13, 2019 The Wine Merchant issue 86 (November 2019)
https://issuu.com/winemerchantmag/docs/the_wine_merchant_issue_86_for_web
CC-MAIN-2020-50
refinedweb
34,648
66.98
On Thu, Feb 2, 2012 at 1:14 AM, Christoph Czurda <hasnoadditives@gmail.com>wrote: > On 02/01/2012 11:58 PM, Alex Karasulu wrote: > >. > > > > > It was like this: > Dn parent = new Dn("ou=system"); > Dn somewhereBelow = new Dn(new Rdn("cn=a,cn=b"),parent); //the problem > was the rdn > > I thought that in this constructor everything before the parent is > simply prepended. So if understand correctly you thought Rdn is not a single name component but one that can have 1 or more name components like for example a relative path in the fs namespace? > The interesting thing is that dn.getName() did what I > actually intended, ie it returns "cn=a,cn=b,ou=system". > > Odd. Thanks for the feedback. -- Best Regards, -- Alex
http://mail-archives.apache.org/mod_mbox/directory-users/201202.mbox/%3CCADwPi+HKVyh0+7jpZAJkBfWPcyLFaZrrhK1y4n=QKQ-+dErSSg@mail.gmail.com%3E
CC-MAIN-2015-14
refinedweb
126
66.64
On 9 Feb 2008, at 17:18, Diego Biurrun wrote: > On Sat, Feb 09, 2008 at 06:13:53PM +0100, Diego Biurrun wrote: >> On Sat, Feb 09, 2008 at 02:45:49PM +0100, Michael Niedermayer wrote: >>> On Sat, Feb 09, 2008 at 12:41:47PM +0000, Patrice Bensoussan wrote: >>>> >>>> On 9 Feb 2008, at 12:22, Reimar D?ffinger wrote: >>>> >>>>>. >>> >>> seconded >> >> #ifdef HAVE_XVMC >> extern int XVMC_field_start(MpegEncContext*s, AVCodecContext >> *avctx); >> extern void XVMC_field_end(MpegEncContext *s); >> extern void XVMC_decode_mb(MpegEncContext *s); >> #endif > > I mean why do we have the above lines in the mentioned file then? > > Diego I was just about to ask the same question... We have some in a lot of files. Patrice
http://ffmpeg.org/pipermail/ffmpeg-devel/2008-February/045325.html
CC-MAIN-2016-50
refinedweb
114
62.72
I've managed to configure PyISAPIe to run Python code (eg, a simple hello world) from a new website running on IIS7, but I can't quite figure out how to get Django up and running in the same environment. Anyone with any tips on how to make that finally link between the two? This is a simple test server so I don't even need to bother with multiple instances. I just want to run one instance of the site at '/'. Here's my entire isapi.py file: isapi.py import os import sys from Http.WSGI import RunWSGI from Http import Env from django.core.handlers.wsgi import WSGIHandler as DjangoHandler sys.path = [ 'c:\parlour\site', 'c:\parlour\site\lib', 'c:\parlour\site\project' ] + sys.path os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings' Base = '/' Exclude = ['/media'] def Request(): PathInfo = Env.PATH_INFO if not PathInfo.startswith(Base): return True for Excl in Exclude: if PathInfo.startswith(Excl): return True return RunWSGI(DjangoHandler(), Base=Base) I think the biggest disconnect I'm having is understanding how PyISAPIe know to execute the file above. With Apache, you need to include WSGIScriptAlias / /path/to/mysite/apache/project.wsgi. I don't see an equivalent for PyIASPIe, although it's likely I'm overlooking something obvious. WSGIScriptAlias / /path/to/mysite/apache/project.wsgi It is impossible to run Django in any fashion that appends .py to the end of your urls. What is your reasoning for avoiding the built in Django development server? It works quite well in most environments and works right out of the box without further configuration? PyASPIe isn't a recommended way to get Django running under IIS, but since it does implement a WSGI interface, I'd say that you should start with that. Have you tried the stuff in the example WSGI config file which includes a bit about django? As a side note, this is probably a bad way to run a dev server, since you will probably have to restart the server every single time you make a change in your python code. This is just one of many reasons to use Django's built in dev server. Edit: The configuration does contain pretty much everything you need to get Django running, as far as I can tell. The lines that do the magic are these: from django.core.handlers.wsgi import WSGIHandler as DjangoHandler os.environ["DJANGO_SETTINGS_MODULE"] = "myapp.settings" You just need to make sure that your project and Django itself are in your PYTHONPATH and that you can import your project's settings. Then you just need to set the PyISAPIe urls to "/" like so: Apps = { "/" : lambda P: RunWSGI(DjangoHandler()), } Then your Django urlconf should work as expected. By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 590 times active
http://serverfault.com/questions/191494/configuring-django-to-run-under-pyisapie-on-iis7/191501
CC-MAIN-2015-06
refinedweb
475
57.77
perltie - how to hide an object class in a simple variable tie VARIABLE, CLASSNAME, LIST $object = tied VARIABLE untie VARIABLE. A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE, and possibly UNTIE and/or... A class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY. FETCHSIZE and STORESIZE are used to provide $#array and equivalent scalar(@array) access. The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are required if the perl operator with the corresponding (but lowercase) name is to operate on the tied array. The Tie::Array class can be used as a base class to implement the first five of these in terms of the basic methods above. The default implementations of DELETE and EXISTS in Tie::Array simply croak. In addition EXTEND will be called when perl would have pre-extended allocation in a real array. For this discussion, we'll implement an array whose elements are a fixed size at creation. If you try to create an element larger than the fixed size, you'll take an exception. For example: use FixedElem_Array; tie @array, 'FixedElem_Array', 3; $array[0] = 'cat'; # ok. $array[1] = 'dogs'; # exception, length('dogs') > 3. The preamble code for the class is as follows: package FixedElem_Array; use Carp; use strict; {ELEMSIZE} field will store the maximum element size $elemsize = shift; if ( @_ || $elemsize =~ /\D/ ) { croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size"; } return bless { ELEMSIZE => $elemsize, ARRAY => [], }, $class; } This method will be triggered every time an individual element the tied array is accessed (read). It takes one argument beyond its self reference: the index whose value we're trying to fetch... This method will be triggered every time an element in the tied array is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something and the value we're trying to put there. In our example, undef is really $self->{ELEMSIZE} number of spaces so we have a little more work to do here: sub STORE { my $self = shift; my( $index, $value ) = @_; if ( length $value > $self->{ELEMSIZE} ) { croak "length of $value is greater than $self->{ELEMSIZE}"; } # fill in the blanks $self->EXTEND( $index ) if $index > $self->FETCHSIZE(); # right justify to keep element size for smaller elements $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value; } Negative indexes are treated the same as with FETCH.. In our example, 'undef' is really an element containing $self->{ELEMSIZE} number of spaces. Observe: sub STORESIZE { my $self = shift; my $count = shift; if ( $count > $self->FETCHSIZE() ) { foreach ( $count - $self->FETCHSIZE() .. $count ) { $self->STORE( $_, '' ); } } elsif ( $count < $self->FETCHSIZE() ) { foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) { $self->POP(); } } }; }. In our example, we'll use a little shortcut if there is a LIST: sub SPLICE { my $self = shift; my $offset = shift || 0; my $length = shift || $self->FETCHSIZE() - $offset; my @list = (); if ( @_ ) { tie @list, __PACKAGE__, $self->{ELEMSIZE}; @list = @_; } return splice @{$self->{ARRAY}}, $offset, $length, . If this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash. whose dot files this object represents where those dot files live whether we should try to change or remove those dot files(my ); } }} } } This is called when untie occurs. See "The untie Gotcha" below.); This is partially implemented now. A class implementing a tied filehandle should define the following methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are used on the handle. this is especially useful when perl is embedded in some other program, where output to STDOUT and STDERR may have to be redirected in some special way. See nvi and the Apache module for examples. When tying a handle, the first argument to tie should begin with an asterisk. So, if you are tying STDOUT, use *STDOUT. If you have assigned it to a scalar variable, say $handle, use *$handle. tie $handle ties the scalar variable $handle, not the handle inside it. In our example we're going to create a shouting handle. package Shout;. As per readline, in scalar context it should return the next line, or undef for no more data. In list context it should return all remaining lines, or an empty list for no more data. The strings returned should include the input record separator $/ (see perlvar), unless it is undef (which means "slurp" mode). sub READLINE { my $r = shift; if (wantarray) { return ("all remaining\n", "lines up\n", "to eof\n"); } else { return "READLINE called " . ++$$r . " times\n"; } } This method will be called when the getc function is called. sub GETC { print "Don't GETC, Get Perl"; return "a"; }.>; You can define for all tie types an UNTIE method that will be called at untie(). See "The untie Gotcha" below. untieGot warnings; use IO::File; sub TIESCALAR { my $class = shift; my $filename = shift; my $handle = IO::File->new( "> ? Prior to the introduction of the optional UNTIE method the only way was the good old -w flag. Which will spot any instances where you call untie() and there are still valid references to the tied object. If the second script above this near the top use warnings 'untie' or; Now that UNTIE exists the class designer can decide which parts of the class functionality are really associated with untie and which with the object being destroyed. What makes sense for a given class depends on whether the inner references are being kept so that non-tie-related methods can be called on the object. But in most cases it probably makes sense to move the functionality that would have been in DESTROY to the UNTIE method. If the UNTIE method exists then the warning above does not occur. Instead the UNTIE method is passed the count of "extra" references and can issue its own warning if appropriate. e.g. to replicate the no UNTIE case this method can be used: sub UNTIE { my ($obj,$count) = @_; carp "untie attempted while $count inner references still exist" if $count; }. module that does attempt to address this. Tom Christiansen>
http://search.cpan.org/~rjbs/perl-5.16.0/pod/perltie.pod
CC-MAIN-2014-23
refinedweb
1,036
61.36
You may have heard that apps for Office use client-side programming when communicating with the Office object-model. You may also have heard that apps for Office are especially well-suited for web mash-up scenarios, and are ideal for calling into web services and interacting with Web content. As a developer, how do you author your own web service? This post will lead you step-by-step through creating your own Web API service and calling into it from client-side app for Office code. Sample code: All relevant code will be shown here. To download a copy of the sample code, see Apps for Office: Create a web service using the ASP.NET Web API. Getting started First, when would you need to author your own web service for an app for Office? Just to be clear, not all web-service scenarios require that you author your own web service. In particular, if your app consumes data from a public service that returns data in JSON-P format, you may not need to write your own web service at all. For purposes of this article, however, we’ll assume that there is some inherent business logic or data transformation that you need to expose to your app by means of writing your own web service. Let’s get started. Using Web API There are several possible choices for server-side technologies. For purposes of this article, I will be demonstrating the use of the ASP.NET Web API. Web API is an excellent framework for building REST applications, and Visual Studio provides first-class tooling support for it. The ability of Web API to communicate across a broad range of platforms makes it a particularly compelling choice for communicating between an app for Office and a corresponding web service. Scenario Let’s take a real-life example: You have an app, and now you want to add a “Send Feedback” page. To send the feedback, you’ll need to either log it to a database or maybe just email it to your development team – but in either case, you have sensitive data (connection string or a username/password combo) that you certainly wouldn’t want to expose via JavaScript. As we saw in the “Getting started” section, this is a canonical example of masking the back-end functionality behind a web service. To make this example match real-world scenarios as closely as possible, let’s send multiple bits of information to the service: for example, an overall rating (an integer on a 1-5 scale) along with a string for the actual feedback. Likewise, the response we’ll get from the service will include both a Boolean status flag to indicate success, and a message back from the server (e.g., “Thank you for your feedback” or an error description). By framing the problem this way, you can see how this sample is analogous to more complex scenarios, like fetching data from a database via a web service (for example, sending a query with certain parameters, returning a data structure that represents the list of results, etc.) Figure 1 shows a screenshot of the app we’re aiming to build. Again, to download the full sample project, see Apps for Office: Create a web service using the ASP.NET Web API. Figure 1. Screenshot of the “Send Feedback” sample app. Create the app project To get the example up and running quickly, let’s just create a new task pane app for Office project, and place the “send feedback” functionality as part of the home screen. Of course, if you have an existing project where you’d like to append this functionality, you could create a SendFeedback folder, add two files called SendFeedback.html and SendFeedback.js within it, and place the functionality there, instead. This example assumes you’re using the latest version of Office Developer Tools. Thus, when you create a new project, you should get a project structure as shown in Figure 2. Figure 2. Visual Studio project structure. Open Home.html, and replace its <div id=”content-main”> section with the following code. <div id="content-main"> <div class="padding"> <p>This sample app demonstrates how an app for Office can communicate with a Web API service.</p> <hr /> <label>Overall rating: </label> <select id="rating" class="disable-while-sending" style="width: inherit"> <option value=""></option> <option value="5">★★★★★</option> <option value="4">★★★★</option> <option value="3">★★★</option> <option value="2">★★</option> <option value="1">★</option> </select> <br /> <br /> <label>Feedback:</label> <br /> <textarea id="feedback" class="disable-while-sending" style="width: 100%; height: 200px" placeholder="What would you like to tell us?"></textarea> <button id="send" class="disable-while-sending">Send it!</button> </div> </div> As you can see, the HTML is very standard, containing a dropdown for the star rating (★ is the Unicode symbol for a star), a textarea for the textual feedback, and a button to send the data. Note that each of those components carries a unique ID, so that it can be easily referenced it via code. I also am applying a class called “disable-while-sending” to each of those three elements – again, just as a way to reference these elements from code – to be able to provide a status indication after the user has clicked “send”. Remember that web service calls are done asynchonrously, so disabling the controls provides both a visual indication, and prevents users from clicking “Send” multiple times while the first call is still underway. Let’s add a corresponding JavaScript file as well, with a placeholder for the sending procedure. If you’re following along with Home.js, replace the entire contents of that file with the following code. /// <reference path="../App.js" /> (function () { "use strict"; // The initialize function must be run each time a new page is loaded Office.initialize = function (reason) { $(document).ready(function () { app.initialize(); $('#send').click(sendFeedback); }); }; function sendFeedback() { $('.disable-while-sending').prop('disabled', true); // Magic happens } })(); Okay, that’s as far as we can get for now. Let’s add our web service. Adding a Web API controller With Web API, anytime you call a method on a server, you’re doing so via a Controller. So, let’s add a Controller to handle our SendFeedback action. You can add a controller anywhere within your web project. By convention, however, controllers go into a “Controllers” folder at the root of the project, so let’s go ahead and create it now. After you create the folder, if you choose it and mouse over the “Add” menu, and you should see the option to add a Web API Controller class. The same option should be available under the “Add” > “New Item…” dialog, as well. Let’s add the Web API controller class now. Figure 3. Adding a Web API Controller Class. By another convention, that is somewhat more strictly enforced, Web API controllers must end with the suffix “Controller” in order to be properly recognized by the routing mechanism. This isn’t to say you can’t change it, but that does require a bit of extra legwork. So for now, let’s appease the Web API plumbing architecture, and name our controller “SendFeedbackController”. We can leave the auto-generated code be for the present, and move onto the next step. We’ll be returning here in a moment. Setting up the Web API routing There is a quick side-step we need to take in order for our Web API Controller to function: we need to register it with the web application. Some flavors of web projects, like MVC, include support for Web API routing by default. The default app for Office does not include this plumbing, but it’s not hard to add. Note that this step is best done after you’ve already added a Controller to the project; otherwise, you need to set up some references manually. This is why this post has you first add the controller, and only then register it. To add the Web API routing registration, right-click on the root your web project, select “Add”, and you should see “Global Application Class” as one of the options. It should also be available under the “Add” > “New Item…” dialog box. The default name of “Global.asax” should suffice. Figure 4. Adding a Global Application class. Once you’ve added Global.asax, the file should automatically open, with empty method stubs filled out. Add the following two “using” statements somewhere at the top of the file. using System.Web.Routing; using System.Web.Http; The only method you need to touch is the Application_Start method. Add the following code into the Application_Start body (the rest of the methods can remain empty). RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); What does this means? In a nutshell, the method registers your controllers to be available under the “api” route, followed by the name of the controller and an optional ID (in case of parameterized queries). The {ID} will not be used for our final SendFeedback controller, but it doesn’t hurt. Note that you can also specify other parameters under routeTemplate, such as “{action}”, to include the name of the action as part of the URL. Refer to "Routing in ASP.NET Web API" for more information on configuring Web API routing, if you’re curious. Filling out the Controller The SendFeedbackController class has some auto-generated code that demonstrates some of the capabilities of Web API, including responding to various HTTP verbs (“GET” vs. “POST”, and so on), routing based on the ID parameter, and so forth. While these capacities are certainly worth exploring on your own (e.g., for an example of how to return a list of values), they are not necessary for our current “Send Feedback” scenario. For our purposes, all we want is a single method that takes in some data (overall rating and feedback text), and returns some data (a status and a message). Data structures Let’s write some data structures to hold the request and response objects. You can write them as inner classes within SendFeedbackController. public class FeedbackRequest { public int? Rating { get; set; } public string Feedback { get; set; } } public class FeedbackResponse { public string Status { get; set; } public string Message { get; set; } } Nothing fancy – we’re using built-in data types (strings, integers) to build up the more complex request and response classes. If you’re curious why Rating is a nullable (int?) type, this is both to demonstrate that you can do this, and to handle the case where the user does not fill out a rating in the dropdown. Method signature Now let’s create the actual SendFeedback method. Go ahead and delete the other method stubs (they’re only there as examples, and you can always re-generate them by creating a new Web API Controller). In their place, let’s put a single SendFeedback method, which takes in a FeedbackRequest, and returns a FeedbackResponse. [HttpPost()] public FeedbackResponse SendFeedback(FeedbackRequest request) { // Magic happens } We will be using the HTML “Post” verb to post data to the controller. (For a discussion of POST versus GET, search the web for “when to use POST versus GET”). Note that you can either put the word “Post” as part of the method name, or you can name the method what you’d like, and annotate it with a “[HttpPost()]” attribute. It’s a matter of personal preference. Try-catch Let’s wrap our method body in a try-catch block, so we can gracefully handle any errors that occur as part of the method. The “catch” is shorter, so let’s fill that out first. try { // Magic moved to here } catch (Exception) { // Could add some logging functionality here. return new FeedbackResponse() { Status = "Sorry, your feedback could not be sent", Message = "You may try emailing it directly to the support team." }; } What’s happening here? Because the controller’s method is the very outer layer of the API, we want to ensure that any exceptions are caught and handled appropriately. Thus, on failing, we will still send a response via the data structure we defined, with an appropriate status text and message. Note that as part of the “catch”, we could instead throw a new HttpResponseException rather than returning a FeedbackResponse, and handle the exception on the client – it’s a matter of preference / convenience. However, performing a try-catch on the server-side code is still be useful for logging or for a potential fallback mechanism. For a more thorough discussion of Web API error handling, see “ASP.NET Web API Exception Handling” on the ASP.NET Blog. The mail-sending functionality Now let’s tackle the body of the “try”. First, if we’re going to send feedback via email, we’ll probably need to gather up some credentials. const string MailingAddressFrom = app_name@contoso.com; const string MailingAddressTo = "dev_team@contoso.com"; const string SmtpHost = "smtp.contoso.com"; const int SmtpPort = 587; const bool SmtpEnableSsl = true; const string SmtpCredentialsUsername = "username"; const string SmtpCredentialsPassword = "password"; For the subject, let’s use the name of the app and the current date, so that it’s easy to distinguish individual feedback items. var subject = "Sample App feedback, " + DateTime.Now.ToString("MMM dd, yyyy, hh:mm tt"); For the body, we will append the rating and the feedback. Notice how we’re using the request object to read these values, just like we would with any normal function parameters. var body = "Rating: " + request.Rating + "\n\n" + "Feedback:\n" + request.Feedback; Now we create the mail message and send it via the SmtpClient class (note that you’ll need to add a “using System.Net.Mail;” statement to the top of the file). MailMessage mail = new MailMessage(MailingAddressFrom, MailingAddressTo, subject, body); // Send as plain text, to avoid needing to escape special characters, etc. mail.IsBodyHtml = false; var smtp = new SmtpClient(SmtpHost, SmtpPort) { EnableSsl = SmtpEnableSsl, Credentials = new NetworkCredential(SmtpCredentialsUsername, SmtpCredentialsPassword) }; smtp.Send(mail); Because we’re using a try-catch block, we know that if the code has reached past the Send command, the feedback was sent successfully. So we can return a FeedbackResponse object back to the user. // If still here, the feedback was sent successfully. return new FeedbackResponse() { Status = "Thank you for your feedback!", Message = "Your feedback has been sent successfully." }; Our controller is now done! Now we just need the client-side piece. Back to JavaScript Let’s return to our sendFeedback() method stub that we left in the JavaScript code in Home.js. We’re just about ready to finish the app. First, we want to disable the “send” button and the other fields while sending is underway. $('.disable-while-sending').prop('disabled', true); Next, prepare the data to send. Note that we create a JavaScript object to hold this data, but with property names (“Feedback” and “Rating”) matching the names of the FeedbackRequest fields from our .NET Controller. var dataToPassToService = { Feedback: $('#feedback').val(), Rating: $('#rating').val() }; Finally, we make a jQuery AJAX call. The URL is relative to the page form which we’re calling the request, hence we go back two levels (to escape “App/Home/”) before turning to “api/SendFeedback”. The data type is “POST”, which matches what the controller expects. For the data, we stringify the above “dataToPassToService” object, and add the appropriate content type. (Tip: While it’s not necessary for POST request, you may want to specify an explicit “cache:true” or “cache:false” for GET requests, depending on whether or not those should be cached). $.ajax({ url: '../../api/SendFeedback', type: 'POST', data: JSON.stringify(dataToPassToService), contentType: 'application/json;charset=utf-8' }).done(function (data) { // placeholder }).fail(function (status) { // placeholder }).always(function () { // placeholder }); Now onto the final stretch of filling out the placeholders above. If the AJAX call succeeds, we’ll display a message to the user, using the Status and Message fields that we get from the controller’s FeedbackResponse object. Let’s substitute that into the “done” placeholder above. app.showNotification(data.Status, data.Message); If the call fails (for example, you are offline), let’s add a similar notification (“fail” placeholder). app.showNotification('Error', 'Could not communicate with the server.'); Finally, regardless of whether the call succeeded or failed, let’s re-enable the controls so that the user can try again, or send another bit of feedback, or copy-paste the feedback and send it via email. Thus, for the “always” placeholder, let’s do. $('.disable-while-sending').prop('disabled', false); Our code is now officially complete. Run it! Let’s have a celebratory run. Press F5 to launch the project, and add some feedback text and a rating in the appropriate fields. Press “Send”. If all is well – and if you have substituted the Controller’s email account constants with appropriate credentials – you should see a notification in the UI that your feedback has been sent, and you should also receive an email with a copy of the feedback. If you’re curious about what is happening behind the covers, you can use a tool like Fiddler to analyze the serialization “magic” that’s happening behind the covers. You can also use Visual Studio to pause on breakpoints, both in the JavaScript code and in the Controller. Figure 5. Fiddler trace showing data passing in and out of the web service The example in this post is just the tip of the iceberg: I am excited to see what apps folks will build, leveraging the flexibility and responsiveness of client-side code, and the power and security of server-side code. Please leave a comment below if you have any questions or comments. ~ Michael Zlatkovsky | Program Manager, Visual Studio Tools for Office & Apps for Office Very nicely written. One of the msdn folks pointed me to this sample. I had seen the sample in the pack but the blog clarifies many subtle aspects. I am currently trying to do a similar async call to a WCF Web service. I created a VS 2012 Office App. I copied simple "int Add(left, right) …" code from the sample app code.msdn.microsoft.com/…/How-to-consume-WCF-service-48b43a79 which has a different directory structure from mine and it also seems to use http: instead of the default https: (produced by VS 2012 Office App template). The sample app's WcfService has url relative to root of application: $.ajax({ type: 'post', url: '/WCFService.svc/Add', … For my OfficeApp I have tried "/WCFService/Add" and url '../../WCFService.svc/Add' relative to the Home.html page In both cases I get Not found. I am wondering if the problem is due to https being the default in VS 2012 unlike in the sample app. I do not see any obvious place where I can change this in my Office App project in VS. If I start with sample app code (and not VS 2012 template dir structure), I can add new methods etc to my WCFService and everything is working well. I would like to stick to the Office App std and I cannot figure out what is the problem. – Jayawanth Hi Michael, Thank you for the article. Too bad that after the admonition to use JSON-P you don't show a GET operation that uses this format. I am using Web API as well and I'm afraid it's returning JSON rather than JSON-P, which then causes my JQuery $.getJSON call (which calls your $.ajax call) to fail with a JavaScript runtime error "Access is denied". When I use Fiddler it shows me JSON data being returned. I don't know if Fiddler knows the difference between the two. -Tom. @Jayawanth: I would recommend that you debug via a browser and Fiddler. E.g., create a regular web page that does not reference Office.js, run it in a browser, and then try to see if you can call the WCF service there. You can try with both the HTTP and HTTPS endpoints, though it really shouldn’t be making a difference. Once you get it working in a browser or see how it fails in the browser and inspect the Fiddler log, it may shed insights into how to fix it for the app for Office case. Hope this helps! – Michael @Tom: To be clear, JSON is *perfectly fine* to use between your web server and your app, provided they’re on the same domain. The restriction for not passing JSON across domains is not Office-specific. See this, from JQuery’s website (api.jquery.com/jQuery.getJSON): "Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol." Web servers, on the other hand, *can* fetch JSON from wherever they want. This means that your web server (C# code) can fetch JSON on your app’s behalf, and then pass it on to your website – avoiding the same-origin issue that you would have otherwise, if the original source is not JSON-P. So I would guess that the “Access is denied” issue is something else. As in my reply to Jayawanth, I would attempt to try to debug in the browser, to see what might be the root cause. Best of luck, – Michael Great post! When I build the example ReSharper complains that the 'disable-while-sending' CSS class isn't defined. However when I run the project the controls are disabled. Just curious where it is? Hi John, Good question 🙂 ReSharper is sort of correct — the class is, in fact, not defined in any CSS. It is only used as a placeholder in the HTML so that JavaScript can grab it and enable/disable the elements as needed — but it actually carries no stylistic effect. There could be other ways to do it (and you could appease ReSharper simply by defining an empty style), but for purposes of this article I wanted to keep things as bare-basic as possible, without the need to create a separate CSS file (hence some of the inline-d styling in the HTML, which would have been in a CSS file otherwise). Makes sense? – Michael Ok so it is not a CSS style but rather JavaScript disables that element labeled with that class because we set its property 'Disabled' as true in the function. That makes sense. Thanks! Hi Michael, It would be really helpful to others who start to develop office app. Great Initiative to build this sample. Hi Michael, Can i use class library without webservice or web api in office app? Hi Keyur, You can certainly include a class library or general C#/VB code in your project, and then use server-side rendering (e.g., asp.net pages or MVC) to render content that invokes the servers-side code as well. But the use of HTML/JS/CSS + a web service makes the application more lightweight and "modern". – Michael Thanks Michael, We are designing our office app for excel. We have add-ins for excel, now we are developing office app for the same add-ins. We are thinking to take as much as reusable code in our Office app. Our lots of code in class library. I am confuse in designing office app. What should i use ? MVC or HTML? Is there a sample app for using MVC5 with apps for office ? Is there any deployment issue with above scenario. ? Hi Keyur, Depending on what your add-in does, you might be able to keep the code that does most of your processing as C#/VB server-side code, and have the app for Office just be a messenger that extracts data from the document, sends it to your Web API service and the class libraries you have today, retrieves the data back via AJAX, and then writes it back to the document using the functionality in Office.js Whether you use HTML + WebAPI or something like MVC is up to you. MVC is (among other things) a tempting engine when you want to create multiple pages that share the same look. Since Office apps interact with Office via client-side code (Office.js), having multiple pages doesn’t make as much sense – keeping the app as a single page (or just a few pages) will likely provide a better user experience, and a better way to keep track of the state. As such, just keeping the app in HTML/JS/CSS and using Web API as the server-code endpoint is probably what I personally would do. But individual scenarios differ… For what it’s worth, I had a discussion with a customer in the past about converting his add-in to an app for Office. If you’re curious, read through the thread on blogs.msdn.com/…/create-a-web-service-for-an-app-for-office-using-the-asp-net-web-api.aspx. Scroll halfway through the thread to get to the relevant part. Hope this helps, – Michael Thanks Michael for reply my post. I have another question for Office App :-). I have a my Office App in Excel and i want to use my office app on web only. Our users doesn't have Office installed in their computer(PC). Users has Office 365 license subscription. Can users use Office app on Web only without installed office in machine? I am not sure if you can insert an app for Office from the Web client — but if you have a document that already has an app for Office in it, yes, that should work for Excel and PowerPoint. Hi, Can i use Office 365 Sharepoint Lists and add/update their item in access web app ? If yes then what we need to do into our web service? I try to use the sample in a Mail App, but I always get the message 'Could not communicate with the server.' Very nicely explained. I tried to implement but I get the error defined in AJAX fail case. I looked at Console of browser and saw that the cause was error '404'. I tried to change the URL in AJAX call but no luck. Please help. I've provided the link for screenshots of my console and VS project directory structure. Console: pasteboard.co/1ZWJhzaO.png VS: pasteboard.co/1ZWKwF5S.png
https://blogs.msdn.microsoft.com/officeapps/2013/06/10/create-a-web-service-for-an-app-for-office-using-the-asp-net-web-api/
CC-MAIN-2017-09
refinedweb
4,406
63.7
04 November 2011 11:40 [Source: ICIS news] By Lauren Williamson SANYA, China (ICIS)--There is a push to bring urea fertilizer into ?xml:namespace> The NBS was introduced in 2010 and only covers phosphate (P) and potassium (K) fertilizers. But at an International Fertilizer Association (IFA) conference in “The NBS has been well received by all stakeholders. It’s good for the country, good for the farmer, good for everyone,” Chander told the crowd. It’s also good for the government, as it allows the state to recoup more money from citizens after it spends a large portion of the state’s budget on securing imports. Essentially, the NBS allows the government to import P and K fertilizers in large quantities but adjust the maximum retail price (MRP), or the subsidised price farmers pay, based on the cost of the imports. Currently, the price for urea is set at rupees (Rs) 1,250/50kg bag ($25/50kg, or $500/tonne), no matter what price the government pays for the imports. The most recent purchase tender closed on 5 October and was issued by Minerals and Metals Trading Corporation of India (MMTC). Though there were initial indications the country would only buy around 800,000 tonnes, The urea price was $522-525/tonne CFR (cost and freight), depending on discharge port. This nets back to around $490/tonne FOB (free on board) for Latest If In the long term, A fertilizer trader close to the situation said, “It’s the minister in power who doesn’t want this change because it’s an election year. He doesn’t want to lose voters. But everyone else wants it so it will happen - it’s just a matter of when.” Chander told conference delegates that he felt confident it would happen before the country began its 2012 imports. But he issued a warning as well. “If the [international] prices go up, then there is going to be demand destruction. Farmers will pay higher prices but only to a certain level.” For more on urea
http://www.icis.com/Articles/2011/11/04/9505430/india-urea-subsidy-changes-may-help-govt-pay-for-costly-ferts.html
CC-MAIN-2014-52
refinedweb
342
60.65
Feature #3202 Parameter set helper methods Description Andrei has created a specialization for the fhicl::ParameterSet::get_if_present templated method that allows us to write code like: CLHEP::Hep3Vector pos = pset.get<CLHEP::Hep3Vector>("position"); to read FHiCL written as: position : [ -3904., 0., 10200. ] The header and implementation are in the Mu2e GeneralUtilities library We think that this code might be of use outside of Mu2e and propose it for inclusion into one of the libraries supported by the art team, cetlib? art? Some other classes that could benefit from this include G4ThreeVector, CLHEP::HepLorentzVector, art::InputTag and perhaps some of the HepRotation/G4Rotation classes. I am sure there are many more that are of general use and that each experiment will find the basic technology useful for their own classes. It's great that this sort of thing was designed into FHICLCPP. What do the other experiments and the art team think of this proposal? We can talk about it at one of the stakeholders' meetings in early 2013. Related issues History #1 Updated by Christopher Green over 6 years ago - Due date set to 09/30/2013 - Category set to Infrastructure - Target version set to 1.09.00 - Estimated time set to 16.00 h - Scope set to Internal - Experiment - added - SSI Package - added We are a little leery of implementing this exactly as specified, because we are unsure of whether it is possible to break the One Definition Rule this way. We would prefer to provide the ability for a user to add to the overload set for a free function, and then implement the facility for this CLHEP object in art to avoid adding a CLHEP dependency to fhicl-cpp. That said, we believe this solution has a simple implementation. #2 Updated by Christopher Green over 6 years ago - Status changed from New to Accepted - Start date deleted ( 12/21/2012) #3 Updated by Christopher Green almost 6 years ago - Target version changed from 1.09.00 to 521 #4 Updated by Kyle Knoepfel about 5 years ago - Related to Feature #6097: Propose that art take over this helper function added #5 Updated by Kyle Knoepfel almost 5 years ago - Project changed from art to cet-is - Category deleted ( Infrastructure) - Target version changed from 521 to 1.14.00 #6 Updated by Kyle Knoepfel almost 5 years ago - SSI Package fhicl-cpp added - SSI Package deleted ( -) #7 Updated by Kyle Knoepfel almost 5 years ago - Assignee set to Kyle Knoepfel - Estimated time changed from 16.00 h to 8.00 h Based on discussion with Rob, the scope of this issue is now confined to support for CLHEP vectors (and possibly matrices). #8 Updated by Kyle Knoepfel almost 5 years ago - Status changed from Accepted to Resolved - % Done changed from 0 to 100 The following statements are now supported: // C++ code // Assumed convention (as specified in FHiCL file) //=========================================================================================== pset.get< CLHEP::Hep2Vector >(...); // vector : [ x, y ] pset.get< CLHEP::Hep3Vector >(...); // vector : [ x, y, z ] pset.get< CLHEP::HepLorentzVector >(...); // vector : [ x, y, z, t ] as well as their corresponding pset.get_if_present functions. To use them, the following must be present in the user's code: #include "art/Utilities/ParameterSetHelpers/CLHEP_ps.h" Support has not been included for any of the CLHEP::Rotation* matrix classes as the matrix classes are constructed with arguments that need to be more carefully specified and understood. Providing a simple pset.get interface does not seem appropriate in this case. Implemented with art:9052b3891782ad211618e2f51fc14fcb71f8384b. #9 Updated by Kyle Knoepfel almost 5 years ago - Status changed from Resolved to Closed Also available in: Atom PDF
https://cdcvs.fnal.gov/redmine/issues/3202
CC-MAIN-2020-10
refinedweb
599
51.28
Responsive Emails in Rails with InkBy Joyce Echessa Why Responsive? These days, a lot of users read their emails through their mobile devices (about 48% according to this statistic) and if you want to provide a good user experience to your subscribers you should consider responsive email design. There are several ways to approach this. You could build the emails yourself from scratch and use media queries to cater for different screens or you could use premium and non-premium templates that are available online and modify them to suit your needs. The problem with these solutions is getting a consistent look of your emails in all email clients. One email client that is especially hard to work with when it comes to responsive emails is Outlook because of its limited CSS support. What is the Solution? Zurb, the same company that came up with the Foundation framework released an Email framework named Ink. According to them, Ink enables you to ‘Quickly create responsive HTML emails that work on any device & client. Even Outlook.’. And that is what we will work with in this tutorial. We are going to create a Rails application that sends an email to a user after they sign up for an account. First we’ll create a new application called rails_ink. rails new rails_ink For demonstration purposes, we won’t be building a large application. I used the scaffold command to generate a User model and its related views and controllers. rails generate scaffold user name:string email:string Migrate the database after that. rake db:migrate Next we’ll generate the mailer. rails generate mailer UserMailer This will create a mailer class, view directory, and a test file. Next, we’ll add a configuration file to the config/initializers directory. This will hold the mailer configuration settings. For testing, we’ll be using Gmail’s smtp server. In production, you might be using another delivery method, like sendmail with your local server. Create a file called mailer_settings inside the config/initializers directory and insert the following code, making changes as necessary. ActionMailer::Base.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :user_name => ENV['GMAIL_USERNAME'], :password => ENV['GMAIL_PASSWORD'], :authentication => "plain" } We need to add a method called registration_email to the app/mailers/user_mailer.rb file. This method will send an email to a user who registers. The method will take in a User object and assign it to an instance variable so that it’s available to our view. Since our email will have an image in the banner, we have to include this as an inline attachment in mailer. class UserMailer < ActionMailer::Base default from: 'example@sitepoint.com' def registration_email(user) @user = user attachments.inline['banner.jpeg'] = File.read("#{Rails.root}/app/assets/images/banner.jpeg") mail(to: user.email, subject: 'Registration Confirmation') end end We now need to create a view file for our email. This will be located in the app/views/user_mailer directory and has to have the same name as the corresponding method in the UserMailer class. Create a file named registration_email.html.erb inside app/views/user_mailer. We are going to use one of the templates on the Ink website. I am using the Basic template for this demonstration. For simplicity, during testing, I prefer just working with the HTML and CSS, running it directly in the browser instead of running it from the Rails application. When I am done, I will then transfer the code to my Rails app. You can link the ‘ink.css’ file in the email but this should only be done for testing purposes. When you are satisfied with the result, copy the css and paste it into the HTML document between style tags. Then you should run your email content through an inliner. An inliner brings all your styles inline, which is important, as some email clients tend to strip out the CSS in the style tag. There are several online inliners, but we’ll use the Ink Inliner. Don’t place any ERB code in the HTML file because the inliner won’t understand it and, thus, won’t output the correct HTML. We’ll have to search for and replace the static text with the necessary variables. Here I will be replacing the banner image and the name of the recipient (Susan Calvin) with the name of the registered user. Once we have the email output, paste this code into the mailer view template app/views/user_mailer/registration_email.html.erb and insert any needed variables. Here, we will search for the string Susan Calvin and replace it with the following: <%= @user.name %> Now, search for the img tag to the image we want to replace and insert the corresponding image_tag. Be sure to include the css styles and attributes that the inliner inserted in the tag. I changed it from this: <img src="" style="outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block;" align="left" /> To this: <%= image_tag attachments['banner.jpeg'].url, :style => "outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block;", :align=>"left" %></td> In the UsersController, after saving the user, we call UserMailer.registration_email and pass it the User object. def create @user = User.new(user_params) respond_to do |format| if @user.save UserMailer.registration_email(@user).deliver format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render action: 'show', status: :created, location: @user } else format.html { render action: 'new' } format.json { render json: @user.errors, status: :unprocessable_entity } end end end The UserMailer.registration_email(@user).deliver sends our email. And that’s it. Register a user and test out the email on different clients. Conclusion If you want to send responsive emails to your users without spending money on a template or writing the code from scratch, give Ink a try. It can be used with any language you choose for your app and it also works well with Email Service Providers like Mailchimp and Campaign Monitor.
https://www.sitepoint.com/responsive-emails-rails-ink/
CC-MAIN-2017-13
refinedweb
1,009
57.47
Server-side image processing with JRuby-on-Rails and the Java 2D API One of the many advantages of creating Rails applications with JRuby is the access that JRuby gives you to the rich set of Java libraries available in the Java platform.. Ruby-bin-1.1.zipfrom jruby.codehaus.org and unpack the zip file. jruby -S gem install rails jruby -S gem install glassfish <JRUBY_INSTALL>/samples. jruby -S rails photo photodirectory you just created. jruby script/generate controller home index <JRUBY_INSTALL>/samples/photo/config/environment.rbfile in a text editor. config.frameworks -= [ :active_record, :active_resource, :action_mailer ] To set up the UI, do the following: <JRUBY_INSTALL>/samples/photo/public/images. <JRUBY_INSTALL>/samples/photo/app/views/home/home.html.erbin a text editor. variable and is passed as a request parameter to the seeimage action of the controller. The action will use this request parameter to execute the appropriate image-processing code. While adding the Ruby code that performs the image processing to the controller, you'll learn the following concepts involved in using Java libraries in a Rails application: java.ioand javax.imageiopackages Graphics2Dobject from the buffered image so that you can draw the processed image. <JRUBY_INSTALL>/samples/photo/app/controllers/hello_controller.rbin a text editor HomeControllerclass declaration: include Java To add the constants you need for this application, do the following:) importstatement: import java.awt.image.BufferedImage ... bi2 = BufferedImage.new(w, h, BufferedImage::TYPE_INT_RGB) include_classstatement: include_class 'java.awt.image.BufferedImage' filename = "#{RAILS_ROOT}/public/images/kids.jpg" file = java.io.File.new(filename). HomeControllerclass declaration and after the constants you added in the previous section, add a seeimageaction: def seeimage end seeimageaction, add an indexaction: def index end parammethod, which returns the parameters in a hash. The operation request parameter has the value the user selected from the menu on index.html.erb. To get the value of operation, do the following: seeimageaction, read the value of the operationrequest parameter into a variable called @data: @data = params[:operation] BufferedImageobject so that you can perform operations on the image. Fileobject. ImageIOclass to store the image file into memory as a BufferedImageobject so that you can perform operations on it. BufferedImagewith the preferred size and bit-depth to facilitate image processing. Graphics2Dobject from the new BufferedImageobject so that the graphics context, or drawing surface, has the proper size. Graphics2Dobject to draw the original buffered image to the graphics context. As you can see, referencing Java classes and methods from Ruby code is not much different from doing it from Java code. Notable differences are the following: biis a BufferedImageobject because that's what the readmethod of ImageIOreturns. nilinstead of nullto represent a null value. TYPE_INT_RGBfield of BufferedImage: BI::TYPE_INT_RGB . op = nil. casestatement uses ColorConvertOpto convert the color model of the image to grayscale, essentially making it a black-and-white image instead of a color image: The Java 2D API provides a set of color spaces, such as CS_GRAY and CS_CMYK. You just need to create a new ColorConvertOp instance and give it your chosen color space. LookupOpclass to create a negative of the original image:: The way you perform convolution with the Java 2D API is by creating a Kernel object and then using it to construct a ConvolveOp object. The photo example uses a kernel that causes a sharpening effect:: dest = op.filter(bi, nil) big.drawImage(dest, 0, 0, nil);The opvariable is the object that represents the image filtering operation from the previous section. The destvariable represents the filtered buffered image.' jruby -S glassfish_rails photo That's all there is to it. For more information on JRuby, Ruby-on-Rails, and the Java 2D API, visit the following links: Posted at 01:15PM May 16, 2008 by jenniferb in Sun | Comments[16] This is a personal weblog, I do not speak for my employer. Today's Page Hits: 98 Posted by Arun Gupta's Blog on May 19, 2008 at 06:31 AM PDT # This entry inspired me to add some methods to image_voodoo (jruby-extras) imaging processing library. I also added a blog entry showing how it could do something similiar to what you did in this entry: -Tom Posted by Thomas E Enebo on May 20, 2008 at 08:14 AM PDT # Hi Thomas, Thanks for your feedback. We writers always like it when we can help improve the quality of software. Jennifer Posted by Jennifer on May 21, 2008 at 05:18 PM PDT # Hi Jennifer, great article! I'm coming from the Ruby side but it's very informative to see what you think needs to be explained to people coming to this from Java. Regarding Rubyisms .. here's a simple way to create the lut table -- I like how it reads better than the for loop. lut = (0..255).to_a.reverse creates this Array: [255, 254, 253, ... 0] You probably know this but I thought some of your readers might enjoy the idea. Explanation: 0..255 is a range object The Range class mixes in all the methods defined in the Enumerable Module including the method to_a (convert to an array). Parens need to be put around the range object in order for the parser to properly recognize the intended receiver for the 'to_a' message. Without parens the parser will assume the receiver is the number object 255. Then the message 'reverse' is sent to the new Array object which reverses the order originally generated when the range object was converted to an Array. Posted by Stephen Bannasch on May 21, 2008 at 08:22 PM PDT # Thanks, Stephen. No, I didn't know about that easier way to create the lut table. I'll have to mention that in the entry when I get a chance. I'm actually very new to Ruby. I owe a great debt to folks on the #jruby IRC channel for helping me out. Posted by Jennifer on May 22, 2008 at 02:51 AM PDT # <a href="">リゾートバイト</a> <a href="">自動車保険</a> <a href="">ヒルズコレクション</a> <a href="">スカルプDシャンプー</a> <a href="">ヒルズダイエット</a> <a href="">パステルゼリー</a> <a href="">ヒルズコレクション</a> <a href="">ヒルズダイエット</a> Posted by ken on June 02, 2008 at 08:29 PM PDT # assas Posted by 59.90.19.42 on August 23, 2008 at 12:01 AM PDT # Good collection and submission! Regards SBL - BPO Services| Posted by BPO Services on October 28, 2008 at 04:19 AM PDT # [ 錦糸眼科の評判・口コミ・うわさ] [ 錦糸眼科] [ 基礎代謝] [ レーシック 失敗] [ FX比較] [ ゴールドカード] [ レーシック] [ ゴールドカード] [ FX初心者] [ 錦糸眼科] [ 神奈川クリニック眼科] [ 錦糸眼科] [ 神奈川クリニック眼科 レーシック] [ 錦糸眼科] Posted by mikkyo on November 13, 2008 at 10:23 PM PST # SE. Posted by SEO on January 28, 2009 at 06:24 PM PST # Posted by yy on January 28, 2009 at 06:25 PM PST # Posted by fdf on March 03, 2009 at 06:02 PM PST # Posted by fdf on March 03, 2009 at 06:02 PM PST # Posted by fdfd@yahoo.com on March 10, 2009 at 12:29 AM PDT # あなたは今の性生活に満足していますか<a href="">セフレ募集</a>満足してみませんか? <a href="">セフレ募集</a>意外と簡単に作れてしまうのです <a href=" ">セフレ募集を</a>作ったことない人は安心してください <a href="">セフレ募集</a>を作れる安心安全無料サイトを紹介したいとおもいます。 Posted by セフレ募集 on March 16, 2009 at 08:30 PM PDT # Posted by fsdf on March 29, 2009 at 10:53 PM PDT #
http://blogs.sun.com/jenniferb/entry/server_side_image_processing_with
crawl-002
refinedweb
1,208
52.8
Hello there, I was just practicing my Linked Lists. I have come out with some code, works well with exception of the first element that I insert. Can anyone please tell me what I did wrong? So far this is my code: Code:#include <iostream> using namespace std; template <class T> class Node { public: T * data; Node<T> * next; Node() { data = NULL; next = NULL; } Node(T * elem, Node<T> * tail) { data = elem; next = tail; } void printList() { Node<T> * current = this; while(current != NULL) { cout << current->data << endl; current= current->next; } } }; template <class T> class Stack { Node<T> * list; int count; public: Stack() { list = NULL; count = 0; } void push(T elem) { Node<T> * temp = new Node<T>(new T(elem), list); list = temp; delete(temp); count++; cout << "Count is now " << count << endl; } T * peek() { if(count > 0) return list->data; else throw (char*)"Cannot peek at an empty list!"; } T * pop() { if(count >= 0) { Node<T> * temp = list; list = list->next; count--; return(temp->data); } else throw (char*)"Cannot pop! List is empty!"; } void printList() { list->printList(); } int getCount(){ return count; } }; int main() { Stack<int> IntStack; IntStack.push(9999); IntStack.push(1); IntStack.push(2); IntStack.push(3); IntStack.push(4); IntStack.push(5); IntStack.push(6); IntStack.push(7); IntStack.push(8); IntStack.push(9); IntStack.push(10); int size = IntStack.getCount(); try{ for( int x = 0; x <= size; x++ ) cout << (int)IntStack.pop()<< endl; } catch(...) { cout << "Exception!" << endl; } return 0; } and this was my output: Why does it not display the first element???Why does it not display the first element???Code:Count is now 1 Count is now 2 Count is now 3 Count is now 4 Count is now 5 Count is now 6 Count is now 7 Count is now 8 Count is now 9 Count is now 10 Count is now 11 0 10 9 8 7 6 5 4 3 2 1 Process returned -1073741819 (0xC0000005) execution time : 6.343 s Press any key to continue. Thanks in advance!
https://cboard.cprogramming.com/cplusplus-programming/121179-help-linked-lists.html
CC-MAIN-2017-34
refinedweb
335
79.09
All MSDN Magazine TopicsAll MSDN Magazine Topics - CLR Inside Out: Extend Windows Forms Apps Using System.AddIn Mueez Siddiqui - July 2008 See how Windows Forms applications can be adapted to use the new .NET Add-in framework (System.AddIn) this month. - Aero Glass: Create Special Effects With The Desktop Window Manager Ron Fosner - April 2007 In this article we introduce the Desktop Window Manager, the new interface that manages how windows are rendered on the Windows Vista desktop. - Team System: Work Item Tracking Brian A. Randell - April 2007 In this column, Brian Randell explains how to build a simple Work Item explorer and demonstrates the core operations needed to add work item support when building your own add-in. - { End Bracket }: Geopegging Joshua Trupin - April 2007 Josh Trupin introduces geopegging--a special technique for storing GPS location data in a JPG. - Graphics To Go: Make A Mobile Imaging App With The .NET Compact Framework 2.0 Rob Pierry - December 2006 This article focuses on developing for Pocket PCs, a skill which can then be transferred to Smartphone application development. - Advanced Basics: TableLayoutPanels Ken Getz - December 2006 This month Ken Getz writes a demo-creation system for Windows-based applications, which he calls a switchboard. - Data Points: RSS Feeds on a Smartphone John Papa - December 2006 John Papa builds a Windows Mobile 5.0 application that reads RSS feeds and loads them into an ADO.NET DataSet. - Peer To Peer: Harness The Power Of P2P Communication In Windows Vista And WCF Justin Smith - October 2006 P2P applications face a number of barriers preventing their wide adoption as a productivity solution. Fortunately Windows Vista improves the situation, as you’ll learn here. - CLR Inside Out: IronPython James Schementi - October 2006 IronPython, the CLR implementation of the dynamic programming language Python is introduced this month. - Smart Clients: New Guidance And Tools For Building Integrated Desktop Applications Christian Thilmany and Jim Keane - September 2006 Integrated Desktop is a loosely coupled hosting architecture and composite UI that runs on the desktop and is supported by a loosely coupled architecture on the back end. It collapses the number of applications a user must deal with when making decisions. -. - Configure This: Parameterize Your Apps Using XML Configuration In The .NET Framework 2.0 Bryan Porter - June 2006 There are a number of ways to configure an application in the .NET Framework 2.0. This article explores the classes of the revamped System.Configuration namespace and explains how to use XML configuration files for your app configuration settings. - Advanced Basics: Setting Word Document Properties the Office 2007 Way Ken Getz - June 2006. - Mix And Match: Integrate Windows Forms Into Your MFC Applications Through C++ Interop Marcus Heege - May 2006 - Analyze This: Find New Meaning In Your Ink With Tablet PC APIs In Windows Vista Markus Egg. - Managed Spy: Deliver The Power Of Spy++ To Windows Forms With Our New Tool Benjamin Wulfe - April 2006 Spy++ displays Win32 information such as window classes, styles, and messages. Now you can get that same functionality for managed code using our ManagedSpy. Get it here. - Winning Forms: Practical Tips For Boosting The Performance Of Windows Forms Apps Milena Salman - March 2006 This article discusses techniques you can use to ensure that Windows Forms-based apps provide optimal performance to match the rich UI responsiveness they're known to provide. -. - Advanced Basics: Set Word Document Properties Programmatically Ken Getz - March 2006 . - Cutting Edge: Windows Workflow Foundation Dino Esposito - March 2006 In the January 2006 issue, Don Box and Dharma Shukla introduced Windows® Workflow Foundation and discussed the overall architecture of the framework and its constituent components (see WinFX Workflow: Simplify Development With The Declarative Model Of Windows Workflow Foundation). -. - Dev Q&A: DataGridView Edited by Nancy Michell - January. - Advanced Basics: The Sound of Music Brad McCabe - January 2006. -. - Visual Basic: Navigate The .NET Framework And Your Projects With The My Namespace Duncan Mackenzie - Visual Studio 2005 Guided Tour 2006 The My Namespace is best described as a speed-dial for the .NET Framework. It provides an intuitive navigation hierarchy that exposes existing .NET functionality through easily understood root objects. Here Duncan Mackenzie explains it all. - Power to the Pen: The Pen is Mightier with GDI+ and the Tablet PC Real-Time Stylus Charles Petzold - December 2005 - UI on the Fly: Use the .NET Framework to Generate and Execute Custom Controls at Run Time Morgan Skinner - December 2005 Creating UI controls on the fly can be accomplished via run-time code generation. And there are lots of reasons to do so. Generating these controls once and then reusing them as needed is more efficient than generating the controls each time. Read on. - Advanced Basics: What's My IP Address? Ken Getz - December 2005. - Advanced Basics: A Match-Making Game in Visual Basic Duncan Mackenzie - October 2005 My four-year-old son has decided that he wants to be like his dad when he grows up. He is planning to work in my office, and write computer programs just like I do. But there is one problem—he thinks I write games. - Spice It Up: Sprinkle Some Pizzazz on Your Plain Vanilla Windows Forms Apps Bill Wagner - September 2005. - . - .NET Matters: Stream Decorator, Single-Instance Apps Stephen Toub - September 2005 - Easy UI Testing: Isolate Your UI Code Before It Invades Your Business Layer Mark Seemann - August 2005. -. - Advanced Basics: Creating A Breadcrumb Control Duncan Mackenzie - July. - .NET Matters: ICustomTypeDescriptor, Part 2 Stephen Toub - May 2005 In last month's . NET Matters column, I answered a question concerning the PropertyGrid control, specifically about using it with classes that expose fields instead of properties. I demonstrated how the ICustomTypeDescriptor interface in the Microsoft® . - Security: Unify Windows Forms and ASP.NET Providers for Credentials Management Juval Lowy - April. - .NET Matters: ICustomTypeDescriptor, Part 1 Stephen Toub - April 2005 - Advanced Basics: Doing Async the Easy Way Ken Getz - March 2005 If you've been following Ted Pattison's excellent series of Basic Instincts columns on multithreading and asynchronous behavior, you should by now be an expert on handling the issues involved in working with multiple threads in Windows®-based apps. - Advanced Basics: Creating a Five-Star Rating Control Duncan Mackenzie - January 2005. -. - Tablet PC: Add Support for Digital Ink to Your Windows Applications Paul Yao - December 2004 Check out the cool new features in Windows XP Tablet PC Edition, including a number of Ink types, and ink that's stored as ink. Here Paul Yao takes you on a tour of everything you need to know to get started. -. - Advanced Basics: Digital Grandma Duncan Mackenzie - November 2004. - Advanced Basics: Building a Progress Bar that Doesn't Progress Duncan Mackenzie - October 2004 In many situations, accurately estimating the length of a certain process (copying a large file, loading data from a server, retrieving files from the Internet) would be both difficult and inefficient. - Security Briefs: Password Minder Internals Keith Brown - October 2004. - Genetic Algorithms: Survival of the Fittest: Natural Selection with Windows Forms Brian Connolly - August 2004. - Advanced Basics: P2P Comm Using Web Services Carl Franklin - August 2004 Iwanted to use my first Advanced Basics column as an opportunity to strike out into new territory, to do something I haven't seen extolled much in the literature, so I've built a Windows® Forms chat program that uses Web services to communicate with other peers. - Test Run: Using Combinations to Improve Your Software Test Case Generation James McCaffrey - July 2004 - Visual Basic: Navigate the .NET Framework and Your Projects with "My" Duncan Mackenzie -. - ClickOnce: Deploy and Update Your Smart Client Projects Using a Central Server Brian Noyes - May. - Advanced Basics: Create a Graphical Editor Using RichTextBox and GDI+ Ken Spencer - May 2004 - Basic Instincts: Updating the UI from a Secondary Thread Ted Pattison - May 2004 - Stress Testing: Custom LoadGenerator Tool Identifies the Issues Your Application Faces Under Stress Brian Otto -. - Advanced Basics: Synchronizing Multiple Windows Forms Ken Spencer - April 2004 - .NET Matters: Const in C#, Exception Filters, IWin32Window, and More Stephen Toub - April 2004 Welcome to . NET Matters. This new column will delve into the ins and outs of the Microsoft® . NET Framework, answering readers' questions on various topics related to its extensive libraries, languages, and the common language runtime. - Bugslayer: .NET Internationalization Utilities John Robbins - April 2004 As you saw in last month's column, . NET internationalization support is excellent and allows you to move your application to a world audience quite easily. Before you jump into this month's discussion, you may want to go back and read the March column. - Advanced Basics: Extracting Data from .NET Assemblies Ken Spencer - March 2004 - Standard I/O: Console Appplications in .NET, or Teaching a New Dog Old Tricks Michael Brook - February 2004 - Advanced Basics: Windows Forms Controls: Z-order and Copying Collections Ken Spencer - January 2004 - .NET Column: Practical Multithreading for Client Apps Jason Clark - January 2004 - Office 2003: Host an Interactive Visio Drawing Surface in .NET Custom Clients Mai-lan Tomsen Bukovec and Blair Shaw - December 2003. - Cutting Edge: Custom Design-time Control Features in Visual Studio .NET Dino Esposito - December 2003 - Advanced Basics: Windows Forms Q&A Ken Spencer - December 2003 - C++ Q&A: Docking the Menu Bar, Abstract Classes vs. Interfaces, and More Paul DiLascia - December 2003 - Cutting Edge: Custom Provider Controls Dino Esposito - November 2003 - Advanced Basics: SQL Server Metadata Ken Spencer - November 2003 - Tablet PC: Achieve the Illusion of Handwriting on Paper When Using the Managed INK API Carlos C. Tapang - October 2003. - Data Points: Exploring the ADO.NET DataRow John Papa - October 2003 - Advanced Basics: Enterprise Services, SQL Script Editing Ken Spencer - October 2003 - Cutting Edge: Managing Your Remote Windows Clipboard Dino Esposito - September 2003 - The XML Files: Introducing the Web Services Enhancements 2.0 Messaging API Aaron Skonnard - September 2003 - Advanced Basics: Creating Text Images On the Fly with GDI+ Ken Spencer - September 2003 - DataGrid: Tailor Your DataGrid Apps Using Table Style and Custom Column Style Objects Kristy Saunders - August. - Cutting Edge: Creating a Multi-table DataGrid in ASP.NET Dino Esposito - August 2003 If you bind a multi-table DataSet to a DataGrid, only the first table is recognized. Here Dino Esposito writes a custom solution the the multi-table problem. - Advanced Basics: Data Binding in Visual Basic .NET Ken Spencer - August 2003 Ken Spencer introduces data binding in Visual Basic .NET. - GDI+: A Primer on Building a Color Picker User Control with GDI+ in Visual Basic .NET or C# Ken Getz - July 2003. - Cutting Edge: Working with Images in the .NET Framework Dino Esposito - July 2003 - Advanced Basics: Adding New Features with User Controls Ken Spencer - June 2003. - Cutting Edge: MyTracer Monitors and Traces ASP.NET Apps Dino Esposito - April 2003 The Microsoft® . NET Framework comes with a rich set of programming tools for debugging and tracing applications. I'm not talking about integrated debuggers; I'm referring to software components that you use in the development cycle. - C++ Q&A: Desktop Location, sscanf Equivalents in C#, and More Paul DiLascia - April 2003 -. - Cutting Edge: Customize Your Open File Dialog Dino Esposito - March 2003. - Advanced Basics: Handling Null Values with Controls Ken Spencer - March 2003 - C++ Q&A: Find Icons, Launch an App from List Control, and More Paul DiLascia - March 2003 - Class Templates: Bring the Power of Templates to Your .NET Applications with the CodeDOM Namespace Adam J. Steinert - February. - BITS: Write Auto-Updating Apps with .NET and the Background Intelligent Transfer Service API Jason Clark - February. - Web-Aware Apps: Build Hyperlinks into Your Client App with the Windows Forms LinkLabel Control Dan Hurwitz - February#. - Web Q&A: Data Shredding, Updating the Status Bar, and More Edited by Nancy Michell - February 2003 - .NET GUI Bliss: Streamline Your Code and Simplify Localization Using an XML-Based GUI Language Parser Paul DiLascia - November 2002. - .NET Remoting: Design and Develop Seamless Distributed Applications for the Common Language Runtime Dino Esposito - October 2002. - Serial Comm: Use P/Invoke to Develop a .NET Base Class Library for Serial Device Communications John Hind - October 2002. - Command Management: Use Design Patterns to Simplify the Relationship Between Menus and Form Elements in .NET Michael Foster and Gilberto Araya - October 2002. - Spider in .NET: Crawl Web Sites and Catalog Info to Any Data Store with ADO.NET and Visual Basic .NET Mark Gerlach - October 2002. - Advanced Basics: Building an Attribute Documenter and Viewer Ken Spencer - October 2002 - Advanced Basics: Reducing Memory Footprints, Gathering Process Info with MSDNMagProcessMonitor Ken Spencer - September 2002 -. - Advanced Basics: Best Practices for Windows Forms Applications Ken Spencer - August 2002 - .NET Zero Deployment: Security and Versioning Models in the Windows Forms Engine Help You Create and Deploy Smart Clients Chris Sells - July 2002. - Cutting Edge: Designing Extensible Windows Forms Applications Dino Esposito - July 2002 -. - Return of the Rich Client: Code Access Security and Distribution Features in .NET Enhance Client-Side Apps Jason Clark - June 2002. - Advanced Basics: How to Use Objects Ken Spencer - June 2002 - Advanced Basics: Handling Transactions Between .NET Components Ken Spencer -. - Data Points: Establishing Relationships Between Rowsets with ADO.NET John Papa - February 2002 - Cutting Edge: Data Binding Between Controls in Windows Forms Dino Esposito - February 2002 - DHTML and .NET: Host Secure, Lightweight Client-Side Controls in Microsoft Internet Explorer Jay Allen - January. - Under the Hood: TypeRefViewer Utility Shows TypeRefs and MemberRefs in One Convenient GUI Matt Pietrek - November 2001 - Advanced Basics: Using Inheritance in Windows Forms Applications Ken Spencer - June 2001 - Serving the Web: Windows Forms in Visual Basic .NET Ken Spencer - April 2001 - Wicked Code: CityView App: Build Web Service Clients Quickly and Easily with C# Jeff Prosise -. -
https://msdn.microsoft.com/en-us/magazine/cc159300.aspx
CC-MAIN-2017-04
refinedweb
2,256
54.63
Folks. XHTML Compliance I've been pushing my team hard over the last few months to come up with a plan whereby we can definitely say that all output generated by the built-in ASP.NET Server Controls is XHTML (and HTML 4.01) compliant by default. Identifying all of the various XHTML rules (and the varying levels of support: XHTML 1.0, 1.1 and strict/transitional) and how these impacted our controls took some time. Thankfully we had the help of Stephen Walther (), who did a great job working with us part-time to come up with a detailed list of issues with our current markup implementations, and in identifying a list of changes necessary to support it. At our meeting on Friday we signed off on making the appropriate code changes. We spent some time debating the level of XHTML we'd end up supporting (I confess I went into the meeting ready to push only for XHTML 1.0 support). In the end we walked away though with a plan that will enable us to output XHTML 1.1 by default. There are about 15 or so classes of changes we need to make throughout the framework. The most interesting/unususal is the requirement to wrap our hidden viewstate tags within a hidden div -- since hidden inputs are apparently no longer allowed immediately under a tag. The good news is that we have time on our schedule to get all of these done in the next few weeks before our final feature milestone ends. To compliment these runtime changes, we are also adding support inside Visual Studio to better validate XHTML markup for static elements. Some of this work is already in the VS Whidbey Alpha (you can change the target schema to XHTML Transitional or Strict). We'll then provide realtime intellisense (red squigglies and task list errors) everytime you try to author non-XHTML compliant markup on the page (along with friendly error messages that help identify how to fix it). Below is a screen-shot of what this looks like on a recent build: In the meeting Friday we also decided to provide new “Add Item” templates that enable developers to add pages to their applications with an XHTML namespace and DOCTYPE value set (we'll probably have this be a drop-down on the new item dialog to enable devs to easily pick between the different standards when adding either dynamic or static pages to their sites). Accessibility Compliance Accessibility compliance is another key feature (and now a requirement for all goverment work) that I've been pushing the team on to make sure we'll be able say “just works” out of the box. In Whidbey, all ASP.NET Server Control will now generate Section 508 compliant markup by default, no coding or config changes required to enable it. Our controls will also support automatically emitting WCAG compliant markup as well. The one issue with making WCAG output the default is the requirement that WCAG has for the site to work without client-scripting. Some of our controls use client-side script for up-level browsers (while optionally emitting script-less downlevel versions for older browsers). Rather than disable script support by default for all browsers, we'll have a WCAG option you can set at either the page or site level which will enable users to turn off uplevel client scripting for accessibility compliance reasons. To further help developers check compliance on a site, we have also built-in a compliance checking tool into Visual Studio that can automatically validate for both 508 and WCAG (level 1 and 2) compliance within a web site. This can be run either manually, or configured to run automatically as part of the Solution Build and/or F5 process. The accessibility checker will verify both static html markup, as well as attributes on ASP.NET Server Controls (for example: if you use an control both don't specify an “AlternateText“ property). Below is a screen-shot of it working in a recent build: Hopefully the net result of both the XHTML and Accessibility work will be a platform and tool that enables web developers to build accessible, standards compliant, web applications easier than ever. Hi Paul, You could modify your CSS to exclude the <div> we create by default immediately underneath the form tag. In general I'd probably recommend having as broad a CSS rule as the one you have above - since it will effect lots of content on the page. Can you instead have it apply to a CSS class only? Thanks, Scott
http://weblogs.asp.net/scottgu/archive/2003/11/25/39620.aspx
CC-MAIN-2014-15
refinedweb
771
56.49
Okay, so i've gotten some help, however i'm still missing some things. In the code below, I have a Bowler's name, and their score. #include <iostream> #include <string> using namespace std; int main() { string names[3] = {"John","Anne","Mary"}; int score[3] = {5,1,2}; //i.e //John's score = 5 //Anne's score = 1 //Mary's score = 2 //sort by score for ( int i = 0; i < 3; i++ ) { for ( int j = 0; j < 3; j++ ) { if( score[i] < score[j] ) { string tmp_string; int temp; temp = score[i]; tmp_string = names[i]; //now swap the names array score[i] = score[j]; names[i] = names[j]; //now swap the names array score[j] = temp; names[j] = tmp_string; //now swap the names array } } } //show them sorted cout << "Sorting by score in ascending order\n"; for ( int k = 0; k < 3; k++ ) { cout << "name:" << names[k] << " score:" << score[k] <<endl; } return 0; } However, I want to change it where the "int score" is, so that the user can input the scores manually. I want the program to have a cout << "Anna's Bowling Score: "; code. Can somebody help me out?
https://www.daniweb.com/programming/software-development/threads/90030/help-with-code
CC-MAIN-2019-04
refinedweb
189
77.91
Делаю валидацию, добавил такие атрибуты к модели: public class Phone { public int Id { get; set; } [Required(ErrorMessage = "Add phone name.")] public string Name { get; set; } [Required(ErrorMessage = "Add phone model.")] public string Model { get; set; } [Required(ErrorMessage = "Add phone memory.")] [Range(0, 512, ErrorMessage = "Memory size must be between 0 and 512!")] public int Memory { get; set; } } Если отправляю ошибочную модель, то сообщения об ошибках у string такие же, как у меня в модели, но у int нет. Вот такое сообщение у пустого свойства Memory: Error converting value {null} to type ‘System.Int32’. Path ‘Memory’, line 1, position 33. Почему сообщение не Add phone!
https://extraproxies.com/%D0%BD%D0%B5%D0%B2%D0%B5%D1%80%D0%BD%D0%BE%D0%B5-%D1%81%D0%BE%D0%BE%D0%B1%D1%89%D0%B5%D0%BD%D0%B8%D0%B5-%D0%BE%D0%B1-%D0%BE%D1%88%D0%B8%D0%B1%D0%BA%D0%B8-%D0%B2-modelstate/
CC-MAIN-2019-09
refinedweb
104
75.81
Hadoop is a general-purpose system that enables high-performance processing of data over a set of distributed nodes. But within this definition is the fact that Hadoop is a multi-tasking system that can process multiple data sets for multiple jobs for multiple users at the same time. This capability of multi-processing means that Hadoop has the opportunity to more optimally map jobs to resources in a way that optimizes their use. Up until 2008, Hadoop supported a single scheduler that was intermixed with the JobTracker logic. Although this implementation was perfect for the traditional batch jobs of Hadoop (such as log mining and Web indexing), the implementation was inflexible and could not be tailored. Further, Hadoop operated in a batch mode, where jobs were submitted to a queue, and the Hadoop infrastructure simply executed them in the order of receipt.. Note: This article assumes some knowledge of Hadoop. See Resources for links to an introduction to the Hadoop architecture and the practical Hadoop series for installing, configuring, and writing Hadoop applications. The core Hadoop architecture A Hadoop cluster consists of a relatively simple architecture of masters and slaves (see Figure 1). The NameNode is the overall master of a Hadoop cluster and is responsible for the file system namespace and access control for clients. There also exists a JobTracker, whose job is to distribute jobs to waiting nodes. These two entities (NameNode and JobTracker) are the masters of the Hadoop architecture. The slaves consist of the TaskTracker, which manages the job execution (including starting and monitoring jobs, capturing their output, and notifying the JobTracker of job completion). The DataNode is the storage node in a Hadoop cluster and represents the distributed file system (or at least a portion of it for multiple DataNodes). The TaskTracker and the DataNode are the slaves within the Hadoop cluster. Figure 1. Elements of a Hadoop cluster Note that Hadoop is flexible, supporting a single node cluster (where all entities exist on a single node) or a multi-node cluster (where JobTracker and NameNodes are distributed across thousands of nodes). Although little information exists on the larger production environments that exist, the largest known Hadoop cluster is Facebook's, which consists of 4000 nodes. These nodes are split among several sizes (half include 8- and 16-core CPUs). The Facebook cluster also supports 21PB of storage distributed across the many DataNodes. Given the large number of resources and the potential for many jobs from numerous users, scheduling is an important optimization going forward. Hadoop schedulers Since the pluggable scheduler was implemented, several scheduler algorithms have been developed for it. The sections that follow explore the various algorithms available and when it makes sense to use them.. The Hadoop implementation creates a set of pools into which jobs are placed for selection by the scheduler. Each pool can be assigned a set of shares to balance resources across jobs in pools (more shares equals greater resources from which jobs are executed). By default, all pools have equal shares, but configuration is possible to provide more or fewer shares depending upon the job type. The number of jobs active at one time can also be constrained, if desired, to minimize congestion and allow work to finish in a timely manner. To ensure fairness, each user is assigned to a pool. In this way, if one user submits many jobs, he or she can receive the same share of cluster resources as all other users (independent of the work they have submitted). Regardless of the shares assigned to pools, if the system is not loaded, jobs receive the shares that would otherwise go unused (split among the available jobs). The scheduler implementation keeps track of the compute time for each job in the system. Periodically, the scheduler inspects jobs to compute the difference between the compute time the job received and the time it should have received in an ideal scheduler. The result determines the deficit for the task. The job of the scheduler is then to ensure that the task with the highest deficit is scheduled next. You configure fair share in the mapred-site.xml file. This file defines the properties that collectively govern the behavior of the fair share scheduler. An XML file—referred to with the property mapred.fairscheduler.allocation.file—defines the allocation of shares to each pool. To optimize for job size, you can set the mapread.fairscheduler.sizebasedweight to assign shares to jobs as a function of their size. A similar property allows smaller jobs to finish faster by adjusting the weight of the job after 5 minutes ( mapred.fairscheduler.weightadjuster). Numerous other properties exist that you can use to tune loads over the nodes (such as the number of maps and reduces that a given TaskTracker can manage) and define whether preemption should be performed. See Resources for a link to a full list of configurable properties.). Queues are monitored; if a queue is not consuming its allocated capacity, this excess capacity can be temporarily allocated to other queues. Given that queues can represent a person or larger organization, any available capacity is redistributed for use by other users. Another difference of fair scheduling is the ability to prioritize jobs within a queue. Generally, jobs with a higher priority have access to resources sooner than lower-priority jobs. The Hadoop road map includes a desire to support preemption (where a low-priority job could be temporarily swapped out to allow a higher-priority job to execute), but this functionality has not yet been implemented. Another difference is the presence of strict access controls on queues (given that queues are tied to a person or organization). These access controls are defined on a per-queue basis. They restrict the ability to submit jobs to queues and the ability to view and modify jobs in queues. You configure the capacity scheduler within multiple Hadoop configuration files. The queues are defined within hadoop-site.xml, and the queue configurations are set in capacity-scheduler.xml. You can configure ACLs within mapred-queue-acls.xml. Individual queue properties include capacity percentage (where the capacity of all queues in the cluster is less than or equal to 100), the maximum capacity (limit for a queue's use of excess capacity), and whether the queue supports priorities. Most importantly, these queue properties can be manipulated at run time, allowing them to change and avoid disruptions in cluster use. Other approaches Although not a scheduler per se, Hadoop also supports the idea of provisioning virtual clusters from within larger physical clusters, called Hadoop On Demand (HOD). The HOD approach uses the Torque resource manager for node allocation based on the needs of the virtual cluster. With allocated nodes, the HOD system automatically prepares configuration files, and then initializes the system based on the nodes within the virtual cluster. Once initialized, the HOD virtual cluster can be used in a relatively independent way. HOD is also adaptive in that it can shrink when the workload changes. HOD automatically de-allocates nodes from the virtual cluster after it detects no running jobs for a given time period. This behavior permits the most efficient use of the overall physical cluster assets. HOD is an interesting model for deployments of Hadoop clusters within a cloud infrastructure. It offers an advantage in that with less sharing of the nodes, there is greater security and, in some cases, improved performance because of a lack of contention within the nodes for multiple users' jobs. When to use each scheduler From the discussion above, you can see where these scheduling algorithms are targeted. If you're running a large Hadoop cluster, with multiple clients and different types and priorities of jobs, then the capacity scheduler is the right choice to ensure guaranteed access with the potential to reuse unused capacity and prioritize jobs within queues. Although less complex, the fair scheduler works well when both small and large clusters are used by the same organization with a limited number of workloads. Fair scheduling still provides the means to non-uniformly distribute capacity to pools (of jobs) but in a simpler and less configurable way. The fair scheduler is useful in the presence of diverse jobs, because it can provide fast response times for small jobs mixed with larger jobs (supporting more interactive use models). Future developments in Hadoop scheduling Now that the Hadoop scheduler is pluggable, you should see new schedulers developed for unique cluster deployments. Two in-process schedulers (from the Hadoop issues list) include the adaptive scheduler and the learning scheduler. The learning scheduler (MAPREDUCE-1349) is designed to maintain a level of utilization when presented with a diverse set of workloads. Currently, this scheduler implementation focuses on CPU load averages, but utilization of network and disk I/O is planned. The adaptive scheduler (MAPREDUCE-1380) focuses on adaptively adjusting resources for a given job based on its performance and user-defined business goals. Conclusion. Hadoop is evolving as its use models evolve and now supports new types of workloads and usage scenarios (such as multi-user or multi-organization big data warehouses). The new flexibility that Hadoop provides is a great step toward more optimized use of cluster resources in big data analytics. Resources Learn - The Apache Hadoop website is the best source for documentation, mailing lists, and where to learn more about Hadoop, including its installation and configuration. - Each of the schedulers offers a large range of configurable properties. You can find these properties through Apache for the fair scheduler and the capacity scheduler. - Distributed computing with Linux and Hadoop (Ken Mann and M. Tim Jones, developerWorks, December 2008) provides an introduction to the architecture of Hadoop, including the basics of the MapReduce paradigm for distributed processing of bulk data. - HADOOP-3412 defines the issue for refactoring the scheduler out of the JobTracker. The original implementation of Hadoop mixed the scheduler algorithm within the JobTracker node. This issue, submitted in 2008, resulted in the removal of the fixed scheduler and the addition of a pluggable scheduler supporting greater flexibility for the varied workloads that Hadoop supports. - You can find a practical introduction to Hadoop in the developerWorks "Distributed data processing with Hadoop" series by M. Tim Jones. Part 1, Getting started (May 2010) provides an introduction to setting up and using a single-node Hadoop cluster. In part 2, Going further (June 2010), you learn how to set up and use a multi-node cluster. Finally, in part 3, Application development (July 2010), you learn how to develop map and reduce applications within the Hadoop environment. - The topic of scheduling is an interesting one in Linux®, and you can find similarities among scheduling jobs in Hadoop and scheduling threads within Linux. You can learn more about Linux scheduling in Inside the Linux Scheduler (M. Tim Jones, developerWorks, June 2006), Inside the Linux 2.6 Completely Fair Scheduler (M. Tim Jones, developerWorks, December 2009), and Linux Scheduler simulation (M. Tim Jones, developerWorks, February 2011). -. - Follow developerWorks on Twitter. You can also follow this author on Twitter at M. Tim Jones. - Watch developerWorks on-demand demos ranging from product installation and setup demos for beginners to advanced functionality for experienced developers. -. Get products and technologies - IBM InfoSphere BigInsights Basic Edition -- IBM's Hadoop distribution -- is an integrated, tested and pre-configured, no-charge download for anyone who wants to experiment with and learn about Hadoop. -.
http://www.ibm.com/developerworks/linux/library/os-hadoop-scheduling/
CC-MAIN-2014-35
refinedweb
1,905
52.39
One key platform feature of Office. GraphQL is one of a family of web-based query and API tools; tools that build on the work done in other RPC and query domains to provide HTTP and JSON tools for handling queries in and across graph databases. It’s not as sophisticated as some RESTful API models, or the more modern gRPC, but it lets you construct relatively complex queries that quickly return JSON data from across the suite of Office 365 tools. While there’s a move to develop a new, more flexible approach to graph query APIs led by the Neo4J development team, it’s still some way from an initial deliverable. The other alternative, the combination of the Gremlin query engine and the Cypher language, is much more complex and more suited to complex graph databases like Neo4J or Microsoft’s Cosmos DB. With control of its own platform, Microsoft has taken a different approach, simplifying things with its own graph query APIs that use REST to access Office 365’s underlying data. While that approach limits the scope of the available queries, it makes working with graph data a lot easier. Querying Microsoft Graph: Graph Explorer makes it easier There’s a single API for the entire Office 365 suite, with one ever-growing namespace for all the various tools and services that make up the platform. That’s currently more than 20 endpoints, counting betas. Although Microsoft has managed to build versioning into the REST URL for its service, it’s important to keep an eye on what’s currently live, what’s coming, and what’s deprecated. That’s where Graph Explorer comes in to play. A tool for trying out graph queries, it’s a useful way of constructing the appropriate calls to the Office 365 APIs, and to experiment with the JSON that’s returned by a query. You don’t even need to give it your credentials while you explore the Graph APIs, because it works against a sample set of Office 365 tenants. Graph Explorer: How to work in the Office 365 sandbox Tools like this, which let you use Microsoft Graph in a sandbox, are an important part of learning a new way of working. By working against a sample tenant, you can be sure that the actions you’re trying out won’t affect your tenant data, especially if you’re experimenting with PUT-based actions, which write data into the graph. By using PUT and GET to handle reads and writes, Microsoft Graph is working with familiar web concepts, making it easier to take the Microsoft Graph API calls and bring them into your code. Sadly, you can only try out GET queries in the sandbox tenant, you’ll need to log into a live tenant to test more complex queries—so you may need to set up a development Office 365 account with sample data to avoid affecting operations. Once you’re able to try out queries against your own data (either live or sample), you can log in to Graph Explorer with a suitable Microsoft account, and then use Graph Explorer to check that queries against your Office 365 tenant return the expected data. If the query works, you can use it in your code, using the Graph SDK to deliver queries and deserialize and parse responses. Microsoft’s next step should be better integration with Visual Studio It’s a pity that there’s no integration between Graph Explorer and development tools. It’s a useful sandbox, but it’s missing an easy way of bringing your graph queries into Visual Studio. Yes, you can cut and paste to save any queries you find useful into to a separate document, but having Graph Explorer as a Visual Studio extension would save time. Microsoft Graph queries can be complex, so it’s a good idea to build a library of useful Microsoft Graph API queries. It’s also worth sharing any queries you develop with colleagues, so you can reuse them across all your applications. Treating the data in all the Office 365 properties as one enormous graph database makes a lot of sense. It’s a complex set of relationships between users, data, devices, and the context in which they’re all working. The result can be powerful, as Microsoft demonstrates in tools like Windows Timeline and new cross-device notifications. However, the tools available for building your own applications, while usable, aren’t sophisticated enough for large-scale development. If Office 365 is to become a successful platform, tools like Graph Explorer need to find their way to Visual Studio and to Visual Studio Code. Otherwise, there’s a good chance that busy developers won’t build it into their workflow.
https://www.infoworld.com/article/3285965/microsoft-graph-explorer-a-good-tool-thats-not-yet-ready.html
CC-MAIN-2021-25
refinedweb
797
54.26
After reading Scott Hansleman’s article on exposing OData for Stack Overflow, I thought it would be nice to update the previous post I did on ADO.NET data services to include the new WCF Data Services. WCF Data Services (formerly called ADO.NET Data Services, and “Astoria”) can expose OData to callers through a very simple interface. LINQPad was not available to query the interface at the time, so I will also discuss how to use LINQPad to write queries against a Data Service. For my example, I am going to expose a VistaDB test database that shows SQL Commands, and examples of their syntax. It is a very simple model, but provides interesting data to query against (other than Northwind!). You can use any Entity Framework provider to perform these steps, they are not specific to VistaDB. Being able to consume data across the web in a rest-ful manner is part of the power of OData, lots of applications that are powered by .NET are going to be able to consume OData services very easily. But the OData protocol is not just for .NET, PHP, Java, Javascript and others also have the ability to consume the data. The Open Data Protocol (OData) is an open web protocol started by Microsoft to expose data using existing web technologies. HTTP, AtomPub (similar to RSS), and JSON are all supported. The protocol matches very closely the way web technologies work, and the URL is the primary operator on the data query. The HTTP verbs match very closely their CRUD operations. The URL has a very descriptive syntax that makes it easy to build queries by hand, or with any programming language. OData is not unique to .NET, although .NET sure makes it easy to expose and consume OData through WCF. To expose OData, we will build a WCF Data Service and expose our VistaDB EF model. I am using Visual Studio 2010 and .NET 4 for this example. The WCF Data Service item template in Visual Studio makes it very easy to expose an Entity Framework model over a service based interface. You don’t have to use Entity Framework, but doing so makes it really easy to build and deploy. I believe you could expose a custom collection through the data service as well, but I have not tried this yet. I first created a Visual Studio 2010 Web Application targeted to .NET 4. Then through right clicking on the project Add - New Item and then choose the ADO.NET Entity Data Model. This is a simple model against a VistaDB 4 database named CommandToolDB.vdb4. We have been using this internally to build up samples of SQL code for VistaDB and SQL Server, then flagging the differences in the database. This is not a completed project, so I am only including a sample of the dataset with this service. We would like to eventually have this service exposed online and queryable through Data Builder. That would allow people to look up snippet examples of SQL Syntax and see the differences between VistaDB and SQL Server. Right click on the project, Add – New Item – WCF Data Service. I named the service VistaDBCommandService.svc. To add any class to be exposed through OData, all you have to do is change the class name in the DataService< ClassNameHere > definition. The default class generated by the template includes a comment in the class definition where you put your class name. DataService< ClassNameHere > public class VistaDBCommandService : DataService< VistaDBCommandsEntities > Since we are exposing the EF Model, I put the name of the entities class as the type to be exposed. public static void InitializeService(DataServiceConfiguration config) { // Give readonly access to all of the entities config.SetEntitySetAccessRule("*", EntitySetRights.AllRead); // Pagesize will change the max number of rows returned config.SetEntitySetPageSize("*", 25); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } Now if you right click the service and say to view in a browser, you will see the following output (well, it will look like an RSS Feed if your browser knows how – so you may need to view source to see this ). <service xml:base="" xmlns:atom="" xmlns: <workspace> <atom:title>Default</atom:title> <collection href="Commands"> <atom:title>Commands</atom:title> </collection> <collection href="Databases"> <atom:title>Databases</atom:title> </collection> <collection href="Statuses"> <atom:title>Statuses</atom:title> </collection> </workspace> </service> The links are all relative, and can be used to query the entities in the database. Pointing by browser to the commands entity ends up looking something like this in my browser. Not very pretty, is it? But now you can write some queries against the data just from the URL parameters. That will give me the First 5 commands (top=5) and only return the SQLCommand, and ExampleSyntax instead of the entire object. SQLCommand ExampleSyntax Ok, but who wants to write queries in the browser? We want LINQ! Grab the most recent LINQPad 4 beta for .NET 4 and follow along. In LINQPad, click the Add Connection at the top of the left panel. The dialog will appear that allows you to choose what type of connection you want, and if you want an automatic data context built for you. Choose the WCF Data Services option from that dialog and click Next. The LINQPad connection dialog then appears. Choose the Data Services radio button, and then enter the local service. In my case, it was the URL listed in the box. I found this by looking the browser window launched when I clicked view in browser for the service item of the website. Clicking test should bring up the Connection OK dialog. Now our data service is in LINQPad and looks like the image show here. The entities are exposed, and so are their relationships. We can now write LINQ queries against our data service and see the results in a nice graphical way inside of LINQPad. LINQPad knows how to query the WCF Data Service and dynamically built up a local model for querying against. The SQL output from LINQPad will now show the URL it used to query the service. This is very similar to how Silverlight loads data exposed on remote servers without knowing anything about ADO.NET. (from c in Commands where c.Status.Description.Equals("Implemented") && c.Database.Description.Equals("VistaDB") select new { c.SQLCommand, c.ExampleSyntax }).Take( 5 ) This command queries the database to find those entries that are flagged as implemented, for the VistaDB Database, and gets the first five entries SQLCommand and ExampleSyntax columns. SQLCommand Notice how I was able to drill down into the entities (c.Status.Description) and interact with the data very much like I would a local EF model. c.Status.Description The results look like this in the Results pane: Viewing the SQL in LINQPad shows the following URL:(Status/Description eq 'Implemented') and (Database/Description eq 'VistaDB')&$top=5&$select=SQLCommand,ExampleSyntax The entire LINQ statement is running on the server through that URL. Consuming the data feed through a .NET application is very easy. In your .NET application, right click and use the Add Service Reference, then point the dialog to your same service. Adding the service reference will actually generate a client side proxy for your application to communicate with that looks like a full blown entity framework model. You can call it using code like a normal EF entities context, but the initialization must point to your URL. I hard coded it in the code below, but in a normal app you would put this in the app.config to allow for easier management of the service endpoint. static void Main(string[] args) { VistaDBCommandsEntities cs = new VistaDBCommandsEntities(new Uri("")); var result = (from c in cs.Commands where c.Status.Description.Equals("Implemented") && c.Database.Description.Equals("VistaDB") select new { c.SQLCommand, c.ExampleSyntax }).Take(5); foreach (var r in result) { Console.WriteLine(r.SQLCommand + " : " + r.ExampleSyntax); } } Note that the entities are not IDisposable, so you cannot put them in a using statement. IDisposable using The combination of WCF Data Services and Entity Framework makes it VERY easy to expose your data in a rest-ful manner over the web. Take a look at the DataService options and you will find a very deep system for controlling who can query data, update, how many rows they can pull at once, etc. DataServ.
http://www.codeproject.com/Articles/86922/Exposing-OData-from-an-Entity-Framework-Model
CC-MAIN-2016-36
refinedweb
1,394
55.74
=encoding utf-8 =head1 NAME libev - a high performance full-featured event loop written in C =head1 SYNOPSIS #include <ev.h> =head2 EXAMPLE PROGRAM // a single header file is required ); Example: Replace the libev allocator with one that waits a bit and then retries., async. =head2 GENERIC WATCHER FUNCTIONS unless documented otherwise. requested events.. =head3 Examples Example: Call C<stdin_readable_cb> when STDIN_FILENO. Example: Try to exit cleanly on SIGINT. sigint_cb (struct ev_loop *loop, ev_signal *w, int revents): C<fork()> a new process and install a child handler to wait for its completion. ev_child cw;; timer_cb (EV_P_ ev_timer *w, int revents) ev_timer_stop (EV_A_ w); /* now it's. =item ev_idle_init (ev_idle *,. =item ev_fork_init (ev_fork *, callback) Initialises and configures the fork watcher - it has no parameters of any kind. There is a C<ev_fork_set> macro, but using it is utterly pointless, really. >. =item ev_cleanup_init (ev_cleanup *, callback) Initialises and configures the cleanup watcher - it has no parameters of any kind. There is a C<ev_cleanup_set> macro, but using it is utterly pointless, I assure you. Example: Register an atexit handler to destroy the default loop, so any cleanup functions are called.); pthread_mutex_unlock (&mymutex); . =head1 OTHER FUNCTIONS There are some other functions of possible interest. Described. Here. Now. > t1_cb (EV_P_ ev_timer *w, int revents) struct my_biggy big = (struct my_biggy *) (((char *)w) - offsetof (struct my_biggy, t1)); t2_cb (EV_P_ ev_timer *w, int revents) ((;
https://git.lighttpd.net/mirrors/libev/src/commit/7606cacefe77ab81ac760dbcb2563e83715662cd/ev.pod
CC-MAIN-2021-17
refinedweb
226
56.76
>>:Javascript is actually a great language (Score:3, Insightful) Or maybe more like Oxygen, poisonous in high concentrations (re: pressures). Better Idea (Score:3, Insightful) Re:My thoughts (Score:4, Insightful) What what most sites use Javascript for... (Score:1, Insightful) ... the browser might just as well support GWBasic. However fancy javascript may be , it doesn't take the worlds most advanced scripting language to to do pop up windows ,mouseover events and selective loading. Instead of trying to makd the browser a cut down OS as both MS and Firefox coders seem to be headed for, they should go back to basics and make the browser a simple reliable graphics display program with some user I/O thrown in. Not some bloated monstrosity that has all the reliability of a 20 year old unserviced Trabant. Having to support an ever more complex OO interpreted language doesn't help this reliability.). Lexical closures "advanced"? (Score:1, Insightful) C'mon. Perl has them. Lua has them. Ruby has them. Sheesh -- even Python has them. I'd guess even PHP has lexical closures these days. Advanced? You just disqualified yourself. Under which kind of rock have you been living the last 30 years? Besides, I'd rather compare Javascript to a Gingko fruit. The stink is similar ;-D [wow: captcha was "discord". This slashcode is developing some prescient intelligence, I fear]:Getting JS out of the browser is a *great* idea :Javascript is actually a great language (Score:3, Insightful) so when is dom2 coming out? Re:Why bother? (Score:4, Insightful) It's a poor Lisp in C's clothing. Give me LET already! Re:My thoughts (Score:4, Insightful) Too educated to learn. Re:Why bother? (Score:3, Insightful) Re:JS needs threads :javascript is good (Score:2, Insightful) I know I shouldn't feed the trolls but... Whether or not current browser implementations of javascript are or are not a resource hog is not at issue here. This article, and thus the discussion, are about a new implementation for the server. Unless you have used and experienced this particular server-side implementation, you cannot say something like when an app is written in JS it is more likely to be a resource hog than the same app written in compiled C Because you don't know. I'm willing to bet that you haven't benchmarked it, and that you can write code in neither language, so in reality you have no idea what you're talking about. Maybe you can come to understand why and learn from that, if you so choose. Re:Why bother? (Score:2, Insightful) Commonly believed fallacy: "the standard desktop has tons of memory/CPU [to spare]" Re:What what most sites use Javascript for... (Score:3, Insightful) Seriously, that isn't what the web is anymore, deal with it. Nothing at all to do with javascript. Re:Why bother? was not meant to be (that is a general purpose language to write medium to large scale applications).:Javascript is actually a great language than runtime checks, however this leads to long startup times and it is still not as efficient as hardware memory protection implemented by modern CPUs. Re:Why bother? (Score:3, Insightful) The javascript hate probably isn't coming from people that have done web development. It's probably coming from people that have done web browsing. Re:Javascript is actually a great language (Score:1, Insightful) what about trimming that input? The offense to the mind that you have to use a USER DEFINED FUNCTION for trimming just boggles the mind. Maybe we're using different terminology, but how exactly is a user-defined function? Sure, there are libraries for this, blah blah but still, the truth remains that there is no trim() function. Why do you need a function to do it when another (well-defined and accepted) method exists?:Javascript is actually a great language investment and needed the language to grow up r at least half way grow up. Shit, I wrote a log analyzer in PHP not because it was a right tool for the job, but because I had some legacy code from a custom CMS that did what I needed, so I could just include it, call some old debugged fucntions, get the job done, and move on to my next TODO. It ain't pretty, and you can bet your ass that n years ago when someone started writing this stuff in PHP, they had no idea what size project it would become. You just never know what projects will blow up into big deals and which ones can survive cheesy tools forever. So I'd say: go ahead and improve javascript implementations, but for fuck's sake, don't ever start a new project, no matter how small you think it is, using javascript (or PHP ;-), unless javascript is just the only choice you have (e.g. you need to run inside a web browser). Even if your project seems small enough -- will it always be? If you use a "grown up" language and then your project evolves/expands, maybe you won't be fucked. Language designers need to think big from the get-go. When they don't, people suffer. And yes, that means namespaces (thank you, Python) and local scopes (good fucking grief, Javascript!!). Re:Why bother? more than 20 lines of javascript. jQuery is NOT for programmers, it's for tools who think they're coding when they lay out HTML. Re:Why bother? : 2px; } .leftthumbnail:hover span{ visibility: visible; left: 120px; } .rightthumbnail span{ position: absolute; top: 0px; right: 10000px; visibility: hidden; text-decoration: none; } .rightthumbnail span img{ border-width: 0; padding: 2px; } .rightthumbnail:hover span{ visibility: visible; right: 120px; } < / style > < div < a < img width="100" src="" border="0" < span >< img width="400" src="" < / a> < a < img width="100" src="" border="0" < span >< img width="400" src="" < / a> < / div> < div < a < img width="100" src="" border="0" < span >< img width="400" src="" < / a> < a < img width="100" src="" border="0" < span >< img width="400" src="" < / a> < / div> What this is doing is taking advantage of the CSS hover selector for the anchor (link) tag to adjust the style of the span tag contained within. That span contains our large images, which are shunted way off to the left of the screen out of sight when you're not hovering over the link and are positioned on screen when you are hovering over the link. You can use this to generate quite a selection of effects if you're creative. Re:javascript is good :Why bother? :Why bother? (Score:3, Insightful) Re:Why bother? actical correctness you can only test by running it with complete code coverage. Even tools like jslint are miserable compared to the compile errors, warnings and other static analysis info you get from a well tooled, typed, compiled language. On at least part of this last part, Brendan Eich agrees with me, although the rest of the world managed to convince him it didn't belong in Ecmascript. [infoworld.com]
http://developers.slashdot.org/story/09/12/01/1548221/Trying-To-Bust-JavaScript-Out-of-the-Browser/insightful-comments
CC-MAIN-2014-52
refinedweb
1,184
70.94
Edge Functions QuickstartBetaLearn how to get started with Edge Functions on Vercel using Vercel CLI, or Next.js In this quickstart guide, you'll learn how to get started with Edge Functions using the Vercel CLI or Next.js. For information on the API and how to use it, see the Edge Functions. When you open the project, notice that it comes with a single API Route ( hello.ts): Add the following code to your function: import { NextRequest, NextResponse } from 'next/server'; export default (req: NextRequest) => { return NextResponse.json({ name: `Hello, from ${req.url} I'm now an Edge Function!`, }); }; export const config = { runtime: 'experimental-edge', }; This code does a couple of important things that you should be aware of: - We're importing a helper from next/server, which extends the native Responseobject. This is not a requirement - We specify the function's runtime with an exported config object: runtime: 'experimental-edge'. This is required to create an Edge Function. - Because the function is using the Edge Runtime, it's signature can follow the same syntax as Edge Middleware Note that you cannot use Node.js APIs in Edge Functions. See the Limitations section for more information. Use the Vercel CLI to deploy your Edge Function: vercel deploy Follow the prompts to deploy your function and once done, open the Production link. From your dashboard click on the deployed project and choose the Functions tab. This tab displays logs from any running functions within your project. Use the dropdown to select the api/hello function. The runtime of the function will read Edge, and the region will be the closest region to you. The Functions tab showing the runtime and region of the hello.ts function. - The signature of an Edge Function matches that of Edge Middleware because they both use the same APIs. - Edge Functions export a custom configobject that specifies which runtime to use. In the case of Edge Functions, the runtime is the Edge Runtime - Unlike Edge Middleware, they can return responses - Helpers that extend the native Response, Event, and Requestobjects can be imported from next/server - You cannot use Node.js APIs in Edge Functions
https://vercel.com/docs/concepts/functions/edge-functions/quickstart
CC-MAIN-2022-33
refinedweb
359
64.91
More factors, more variance…explained Want to share your content on python-bloggers? click here.. Results were interesting, but begged the question why we were applying predominantly equity factors to portfolios of diverse assets: bonds, commodities, and real estate in addition to stocks. The simple answer: it was easy to get the data and the factors are already relatively well known. In our second investigation, we built a risk factor model using economic variables that explained surprisingly little of the four portfolios’ variance. We admit our choice of macro factors wasn’t terribly scientific. But we felt, intuitively, they captured a fair amount of the US economy.1 Unfortunately, the macro factor model did an even worse job explaining portfolio variance than the F-F model. We hypothesized that some of the problems with the macro factor model—besides data issues around timing and frequency—were that not all of the series we used were leading indicators. In this post, we’ll re-run the model, but with putative leading factors and then see what we can do to improve the model, if at all. Let’s begin! We start by pulling the data. In the previous post, we used PMI, the unemployment rate, personal consumption expenditures, housing permits, consumer sentiment, and yield spreads (e.g. ten-year less two-year Treasuries, and Baa-rated less Aaa-rated corporates). In this post, we’ll use PMI, initial unemployment claims, the leading index2, housing permits, monetary base, and yield spreads. If these substitutions don’t match your view of true leading indicators, let us know at the email address below. We’re not economists, nor do we pretend to be experts of the dismal science. The variables we use are based on our search into generally accepted leading indicators. First, here’s the spaghetti graph of the variables transformed to month-over-month sequential changes. We exclude yield spreads since they are not reported as a sequential change, and, if we were to transform them, they would overwhelm the other data. Now, we’ll use that data to run our \(R^{2}\)s analysis on the various asset classes. Pretty disappointing. The high \(R^{2}\) for real estate is odd, but we’re not going to dwell on it. We believe working through a full, normalized data series will prove more fruitful. Nonetheless, we’ll show how this macro factor model explains the variance of the four portfolios. We’re skipping over showing how we calculate factor exposures and idiosyncratic risk; you can find that in the code below and the first post. Here’s the explained variance graph. This is actually worse than the previous data in terms of explanatory power. Perhaps our intuition wasn’t so bad after all! Let’s move on. Next we’ll normalize the macro variables and regress them against forward returns. Not knowing which combination of look back and look forward windows is the best, we perform a grid search of rolling three-to-twelve month look back normalizations and one-to-twelve month forward returns, equivalent to 120 different combinations. We sort the results by the highest \(R^{2}\) for stocks and bonds and show the top five below in a table. We’re not sure why three-to-five month look backs on eight month forward returns produce the highest explanatory power. But lets run with the five-month look back and eight month forward (5-8 model). Next we’ll show the factor \(\beta\)s by asset class. Some of the size effects are reasonable in terms of magnitude and direction: monetary base increasing should be positive for stock returns while corporate yield spreads widening should be negative. But others aren’t so much. An increasing monetary base should suggest rising inflation which should be positive for gold. Yet, it appears to have a negative impact for the yellow metal. However, widening corporate spreads, presaging rising risk, should see some correlation with that gilded commodity. Let’s see how much the 5-8 model explains the variance of the four portfolios. Certainly better than the base model and better than the 9-9 model from the previous post. But can we do better? We’re going to make a broad brush generalization that we won’t try to prove, but we think is generally right. If you think we’re wrong, by all means reach out at the email address below. Here it is. For most investors, most of the time, stocks will be the bulk of the portfolio. They may not be the majority, but they’re likely to be at least a plurality for say 70% of liquid investment portfolios.3 More importantly, unless you’re invested in an alternative asset class or using an arcane investment strategy, stocks will likely produce the bulk of the returns and volatility. Given this gross generalization, perhaps we should include factors that explain stock returns better than the macro variables. Bring back Fama-French! We add the Fama-French factors to the macro variables and run a grid search as above. Note, we’re excluding the market risk premium as well as risk free rate. Hence, as in the foregoing analysis, we’re analyzing raw returns, rather than risk premia. The grid search table is below. The look back period clusters around nine to eleven, with returns five-months in the future dominating the top five spots. We’ll go with the ten-month look back and five-month forward (10-5 model). Explained variance increased more than five-to-seven percentage points on average with the addition of the F-F factors. For a final twist, let’s adjust the assets to a risk premium type return (return less the risk free rate) and include the market risk premium. We have to be careful, however. The F-F market risk premium is highly correlated with our stock risk premium.4 So if we included the market risk premium we’d explain almost all of the variance in our stock returns on a coincident basis. On a lagged basis, we’d be incorporating a autoregressive model for stock returns that wouldn’t be present for the other asset classes. Should we exclude the market risk premium? We think not. Conceptually, the market risk premium is supposed to capture most of the systematic risk not identified by the other factors. This means that even if it is primarily equity market-based, it would likely explain some of the variance of other asset classes, given how much the stock market reflects the overall economy. Hence, it seems reasonable to include the market risk premium in the model, but remove its effect on the stock portion of the portfolio.5 Adding the market risk premium and adjusting asset returns to reflect only the amount in excess of the risk-free rate, improved explained portfolio variance for all but the Max Return portfolio. This is encouraging because we worried that removing the risk-free rate might cause some information loss, and hence explanatory power, from raw returns. We believe the improvement in explained variance for three of the portfolios is due mainly to an increase in the risk model’s power to explain bond returns. While we don’t show it, the \(R^{2}\) for bonds increased about seven percentage points by moving from the raw return to the market risk premium model. Recall that only the Max Return portfolio has a small exposure to bonds, while the others are above 20%. So maybe the market risk premium for equities does confer some information for bonds. Many companies are in both buckets after all. How does this all compare to the original model using only F-F? On first blush, not so well. While the Max Sharpe portfolio saw a huge jump in explanatory power, the remaining portfolios saw modest changes or actual declines. Here’s the graph of that original output. Of course, that original model was on a coincident time scale, so it does little to help us forecast impending risk. Clearly, the addition of macro variables helped the Max Sharpe portfolio because it had a very high weighting to real estate, whose variance in returns was explained best by the macro and macro plus F-F models. Nonetheless, we don’t think we should be discouraged by the results. Quite the opposite. That we were able to maintain the magnitude of variance explained on forward returns, which are notoriously difficult to forecast anyway, may commend the use of macro variables. This isn’t time to take a victory lap, however. Many open questions about the model remain. First, while not a (insert risk factor commercial provider here) 40 factor model, with 11 factors our model isn’t exactly parsimonious. Second, we arbitrarily chose a look back/look forward combination we liked. There wasn’t anything rigorous to it and there’s no evidence, without out-of-sample validation, that the model would generalize well on unseen data. Third, even with all this data wrangling, we still haven’t found a model that explains even half of the variance of the portfolios. True, it’s better than zero, but that begs the question as to which matters more: behavior or opportunity cost. That is, while the simplistic risk measure volatility doesn’t tell us much about the future, it does tell us that returns will vary greatly. The risk factor models tell us that some of the future variance may be explained by some factors we’ve observed today, but the majority of the variance is still unknown. Are you more comfortable knowing that you won’t know or knowing that you’ll know some, but not a lot and it will cost you time (and/or money) to get there? With that open question we’ll end this post. And now for the best part… the code! # Built with R 4.0.3 and Python 3.8.3 #[R code] ## Load packages suppressPackageStartupMessages({ library(tidyverse) library(tidyquant) library(reticulate) }) # Allow variables in one python chunk to be used by other chunks. knitr::knit_engines$set(python = reticulate::eng_python) # [Python code] #') DIR = "C:/Users/user/image_folder" # Whatever directory you want to save the graphs in. This is the static folder in blogdown so we can grab png files instead running all of the code every time we want to update the Rmarkdown file. ## Create save figure function def save_fig_blog(fig_id, tight_layout=True, fig_extension="png", resolution=300): path = os.path.join(DIR, fig_id + "." + fig_extension) print("Saving figure", fig_id) if tight_layout: plt.tight_layout() plt.savefig(path, format=fig_extension, dip=resolution) ## Random portfolios for later # See other posts for Port_sim.calc_sim_lv() function np.random.seed(42) port1, wts1, sharpe1 = Port_sim.calc_sim_lv(df = df.iloc[1:60, 0:4], sims = 10000, cols=4) ## Download and wrangle macro variables import quandl quandl.ApiConfig.api_key = 'your_key' start_date = '1970-01-01' end_date = '2019-12-31' pmi = quandl.get("ISM/MAN_PMI", start_date=start_date, end_date=end_date) pmi = pmi.resample('M').last() # PMI is released on first of month. But most of the other data is on the last of the month start_date = '1970-01-01' end_date = '2019-12-31' indicators = ['ICSA', 'PERMIT','USSLIND', 'BOGMBASE', 'T10Y2Y', 'DAAA', 'DBAA'] fred_macros = {} for indicator in indicators: fred_macros[indicator] = dr.DataReader(indicator, 'fred', start_date, end_date) fred_macros[indicator] = fred_macros[indicator].resample('M').last() from functools import reduce risk_factors = pmi for indicator in indicators: risk_factors = pd.merge(risk_factors, fred_macros[indicator], how = 'left', left_index=True, right_index=True) risk_factors['CORP'] = risk_factors['DBAA'] - risk_factors['DAAA'] risk_factors = risk_factors.drop(['DAAA', 'DBAA'], axis=1) # Transform to sequential change macro_risk_chg = risk_factors.copy() macro_risk_chg.loc[:, ['PMI','ICSA', 'PERMIT', 'BOGMBASE']] = macro_risk_chg.loc[:, ['PMI','ICSA', 'PERMIT', 'BOGMBASE']].pct_change() macro_risk_chg.loc[:, ['USSLIND','T10Y2Y', 'CORP']] = macro_risk_chg.loc[:, ['USSLIND','T10Y2Y', 'CORP']].apply(lambda x: x*.01) ## Remove infinites for OLS macro_risk_chg = macro_risk_chg.replace([np.inf, -np.inf], 0.0) ## Spaghetti graph of macro variables ax = (macro_risk_chg.loc['1987':'1991', macro_risk_chg.columns[:-2].to_list()]*100).plot(figsize=(12,6), cmap = 'Blues') # macro_risk_chg.loc['1987':'1991', macro_risk_chg.columns[-2:].to_list()].plot(ax = ax) # Include only if want yield spreads too plt.legend(['PMI', 'Initial Claims', 'Housing', 'Leading indicators', 'Monetary base']) plt.ylabel('Percent change (%)') plt.title('Macroeconomic risk variables') plt.show() ## Create function to calculate R-squareds, with or without risk premiums, graph them, and do a whole bunch of other stuff that makes analysis and blog writing easier import statsmodels.api as sm ## Load data risk_factors = pd.read_pickle('risk_factors_2.pkl') df = pd.read_pickle('port_const.pkl') df.iloc[0,3] = 0.006 dep_df_all = df.iloc[:,:-1] ## Create RSQ function # Allows one to remove market risk premium from stock regression def rsq_func_prem(ind_df, dep_df, look_forward = None, risk_premium = False, period = 60, start_date=0, \ plot=True, asset_names = True, print_rsq = True, chart_title = None,\ y_lim = None, save_fig = False, fig_name = None): """ Assumes ind_df starts from the same date as dep_df. Dep_df has only as many columns as interested for modeling. """ xs = ind_df[0:start_date+period] assets = dep_df.columns.to_list() rsq = [] if look_forward: start = start_date + look_forward end = start_date + look_forward + period else: start = start_date end = start_date + period if risk_premium: mask = [x for x in factors.columns.to_list() if x != 'mkt-rfr'] for asset in assets: if asset == 'stock': X = sm.add_constant(xs.loc[:,mask]) else: X = sm.add_constant(xs) y = dep_df[asset][start:end].values mod = sm.OLS(y, X).fit().rsquared*100 rsq.append(mod) if print_rsq: print(f'R-squared for {asset} is {mod:0.03f}') else: X = sm.add_constant(xs) for asset in assets: y = dep_df[asset][start:end].values mod = sm.OLS(y, X).fit().rsquared*100 rsq.append(mod) if print_rsq: print(f'R-squared for {asset}label("$R^{2}$") if chart_title: plt.title(chart_title) else: plt.title("$R^{2}$ for Macro Risk Factor Model") plt.ylim(y_lim) if save_fig: save_fig_blog(fig_name) else: plt.tight_layout() plt.show() return rsq # Run r-squared function import statsmodels.api as sm cols = macro_risk_chg.columns[:-2].to_list() ind_df_1 = macro_risk_chg.loc['1987':'1991',cols] dep_df_1 = df.iloc[:60,:4] _ = rsq_func_prem(ind_df_1, dep_df_1, y_lim = None, save_fig = True, fig_name = 'macro_risk_r2_22') ## Create factor beta calculation function ## while allowing for market risk premium exposure def factor_beta_risk_premium_calc(ind_df, dep_df, risk_premium = False): """ Assumes only necessary columns in both ind_df and dep_df data frames. Set risk_premium to True if you include the market risk premium in ind_df and don't want to regress stock returns against i. """ xs = ind_df factor_names = [x.lower() for x in ind_df.columns.to_list()] assets = dep_df.columns.to_list() betas = pd.DataFrame(index=dep_df.columns) pvalues = pd.DataFrame(index=dep_df.columns) error = pd.DataFrame(index=dep_df.index) if risk_premium: mask = [x for x in ind_df.columns.to_list() if x != 'mkt-rfr'] # remove market risk premium from independent variables zero_val = np.where(ind_df.columns == 'mkt-rfr')[0][0] # identify index of market risk premium for asset in assets: if asset == 'stock': X = sm.add_constant(xs.loc[:,mask]) y = dep_df[asset].values result = sm.OLS(y, X).fit() # pad results for missing market risk premium results = np.array([x for x in result.params[1:zero_val+1]] + [0.0] + [x for x in result.params[zero_val+1:]]) for j in range(len(results)): # results and factor names have same length betas.loc[asset, factor_names[j]] = results[j] pvalues.loc[asset, factor_names[j]] = results[j] else: X = sm.add_constant(xs) y = dep_df[asset].values result = sm.OLS(y, X).fit() for j in range(1, len(result.params)): # result.params equals length of factor_names + 1 due to intercept so start at 1 betas.loc[asset, factor_names[j-1]] = result.params[j] pvalues.loc[asset, factor_names[j-1]] = result.pvalues[j] # Careful of error indentation: lopping through assets error.loc[:,asset] = (y - X.dot(result.params)) else: X = sm.add_constant(xs) for asset in assets: y = dep_df[asset].values result = sm.OLS(y, X).fit() for j in range(1, len(result.params)): betas.loc[asset, factor_names[j-1]] = result.params[j] pvalues.loc[asset, factor_names[j-1]] = result.pvalues[j] error.loc[:,asset] = (y - X.dot(result.params)) return betas, pvalues, error ## Create function to plot betas def betas_plot(beta_df, colors, legend_names, save_fig = False, fig_name=None): beta_df.plot(kind='bar', width = 0.75, color= colors, figsize=(12,6)) plt.legend(legend_names) plt.xticks([0,1,2,3], ['Stock', 'Bond', 'Gold', 'Real estate'], rotation=0) plt.ylabel(r'Factor $\beta$s') plt.title(r'Factor $\beta$s by asset class') if save_fig: save_fig_blog(fig_name) plt.show() ## Create function to calculate variance due to risk factors ## Create weight variables to calculate portfolio explained variance]] ## Calculate portfolio variance wt_list = [satis_wt, equal_wt, max_sharp_wt, max_ret_wt] port_exp=[] betas1, pvalues1, error1 = factor_beta_risk_premium_calc(ind_df_1, dep_df_1) for wt in wt_list: out = factor_port_var(betas1, ind_df_1, wt, error1) port_exp.append(out[0]/(out[0] + out[1])) port_exp = np.array(port_exp) ## Create function to plot portfolio explained variance def port_var_plot(port_exp, port_names=None, y_lim=None, save_fig=False, fig_name=None): if not port_names: port_names = ['Satisfactory', 'Naive', 'Max Sharpe', 'Max Return'] else: port_names = port_names plt.figure(figsize=(12,6)) plt.bar(port_names, port_exp*100, color='blue') for i in range(4): plt.annotate(str(round(port_exp[i]*100,1)) + '%', xy = (i-0.05, port_exp[i]*100+0.5)) plt.title('Original four portfolios variance explained by Macro risk factor model') plt.ylabel('Variance explained (%)') plt.ylim(y_lim) if save_fig: save_fig_blog(fig_name) plt.show() # Graph portfolio variance based on macro model port_var_plot(port_exp, y_lim = [0,22]) ## Run grid search based on look back normalization and look forward returns dep_df_all = df.iloc[:,:-1] # Grid search for best params ## Sort data scaled_sort = scale_for.sort_values(['Stocks','Bonds'], ascending=False).round(1).reset_index() # [R] ## Print table py$scaled_sort %>% as.data.frame(check.names=FALSE) %>% select(-index) %>% slice(1:5) %>% knitr::kable('html', caption = "Top 5 combinations by $R^{2}$ for stocks and bonds") ## Build model based on grid search model using 5-8 look back/look forward scale_5_8 = risk_factors.apply(lambda x: (x - x.rolling(5).mean())/x.rolling(5).std(ddof=1))['1987':] scale_5_8.replace([np.inf, -np.inf], 0.0, inplace=True) _ = rsq_func_prem(scale_5_8, dep_df_all, look_forward = 8, y_lim = [0,35],save_fig=False) betas_scale, _, error_scale = factor_beta_risk_premium_calc(scale_5_8['1987':'1991'],df.iloc[8:68,:-1]) beta_colors = ['darkblue', 'darkgrey', 'blue', 'grey','lightblue', 'lightgrey', 'black'] beta_names = ['PMI', 'Initial claims', 'Housing','Leading indicators', 'Monetary base', 'Treasury', 'Corp'] betas_plot(betas_scale, beta_colors, beta_names, save_fig=True, fig_name = 'factor_betas_5_8_22') ## Graph portfolio explained variance based on 5-8 grid search model_scale, scale_5_8['1987':'1991'], wt, error_scale) port_exp.append(out[0]/(out[0] + out[1])) port_exp = np.array(port_exp) port_var_plot(port_exp, y_lim=[0,30], save_fig=True, fig_name='four_port_var_exp_5_8_22') ## Load Fama-French Factors try: ff_mo = pd.read_pickle('ff_mo.pkl') print('Data loaded') except FileNotFoundError: print("File not found") print('Loading data yo...') ff_url = "" col_names = ['date', 'mkt-rfr', 'smb', 'hml', 'rfr'] ff = pd.read_csv(ff_url, skiprows=3, header=0, names = col_names) ff = ff.iloc[:1132,:].set_index('date', inplace=True) ff_mo = ff_mo*.01 # Convert percentages to decimal. IMPORTANT FOR RISK PREMIUM!! # Create total factors model total_factors = pd.merge(risk_factors, ff_mo, how='left', left_index=True, right_index=True) ## Grid search for best params # Prepare data dep_df_all = df.iloc[:,:-1] # Risk factor data keep = [x for x in total_factors.columns.to_list() if x not in ['mkt-rfr', 'rfr']] risk_factors_1 = total_factors.loc[:, keep]_1 scaled_sort = scale_for.sort_values(['Stocks', 'Bonds'], ascending=False).round(1).reset_index() [R] ## Print table from Python data frame py$scaled_sort %>% as.data.frame(check.names=FALSE) %>% select(-index) %>% slice(1:5) %>% knitr::kable('html', caption = "Top 5 combinations by $R^{2}$ for stocks and bonds of combined risk factor model") ## Build grid search model and graph portfolio variance scale_10_5 = risk_factors_1.apply(lambda x: (x - x.rolling(10).mean())/x.rolling(10).std(ddof=1))['1987':] scale_10_5.replace([np.inf, -np.inf], 0.0, inplace=True) betas_10_5, _, error_10_5 = factor_beta_risk_premium_calc(scale_10_5['1987':'1991'],df.iloc[5:65,:-1]), scale_10_5['1987':'1991'], wt, error_10_5) port_exp.append(out[0]/(out[0] + out[1])) port_exp = np.array(port_exp) port_var_plot(port_exp, y_lim=[0,40], save_fig=True, fig_name = 'four_port_var_exp_10_5_22') ## Run gird search for risk premium and market-risk premium factor model ### Grid search for best params ## Prepare data # Risk premium data dep_df_all = df.iloc[:,:-1].apply(lambda x: x - total_factors.loc['1987':'2019','rfr'].values) # Risk factor data risk_factors_3 = total_factors.loc[:, total_factors.columns.to_list()[:-1]] ## Create data frame scale_for = pd.DataFrame(np.c_[np.array([np.repeat(x,12) for x in range(3,13)]).flatten(),\ np.array([np.arange(1,13)]*10).flatten(),\ np.array([np.zeros(120)]*4).T],\ columns = ['Window', 'Forward', 'Stocks', 'Bonds', 'Gold', 'Real estate']) ## Iterate count = 0 for i in range(3, 13): risk_scale = risk_factors_3.apply(lambda x: (x - x.rolling(i).mean())/x.rolling(i).std(ddof=1))['1987':] risk_scale.replace([np.inf, -np.inf], 0.0, inplace=True) for j in range(1,13): out = rsq_func_prem(risk_scale, dep_df_all, risk_premium = True, look_forward = j, plot=False, print_rsq=False) scale_for.iloc[count,2:] = np.array(out) count+=1 scale_10_5 = risk_factors_3.apply(lambda x: (x - x.rolling(10).mean())/x.rolling(10).std(ddof=1))['1987':] scale_10_5.replace([np.inf, -np.inf], 0.0, inplace=True) _ = rsq_func_prem(scale_10_5, dep_df_all, look_forward = 5, risk_premium = True, y_lim = [0,60],save_fig=False) betas_10_5a, _, error_10_5a = factor_beta_risk_premium_calc(scale_10_5['1987':'1991'],dep_df_all.iloc[5:65,:], risk_premium=True)a, scale_10_5['1987':'1991'], wt, error_10_5a) port_exp.append(out[0]/(out[0] + out[1])) port_exp = np.array(port_exp) port_var_plot(port_exp, y_lim=[0,42], save_fig=True, fig_name='four_port_var_10_5_rp_22') We apologize to our non-US readers. The US-bias is data-driven not philosophical. If any kind soul knows of easy to procure international data of sufficient length and frequency (i.e., more than 30 years and at least monthly), please let us know at content at optionstocksmachines.com. We’ll be happy to incorporate it into a post or three!↩︎ From the FRED perspicuous reader will note that there is some double counting since we also include housing permits in the model. However, when we used only the leading index, we didn’t find much to commend the model. Hopefully, the impact of permits in the leading index is modest.↩︎ Around 70% of the world’s population lives in developed countries and this is the main investing population. Of the more developed countries over 50% of the population is in the 25-64 years old range, which represents say 90% of investors. And if the most often recommended portfolio is some combination of 80/20 to 60/40 stocks/bonds, then 50-70% of portfolios will be overweight stocks.↩︎ We’re using the Wilshire 5000 total return index.↩︎ This is, of course, easy enough to do if we were just writing procedural code; writing functional code, with proper evaluators to ensure successful matrix multiplication is where it becomes a bit more gnarly!↩︎ Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2021/01/more-factors-more-variance-explained/
CC-MAIN-2021-10
refinedweb
3,771
51.04