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
Created on 2008-08-29 04:19 by gideon, last changed 2010-11-12 05:26 by terry.reedy. This issue is now closed. The attached example crashes python. The crash is caused by an evil iterator that removes its own next function. Good catch! Here is a patch for 3.0. Maybe do a s/"object is no more an iterator"/"is no longer an iterator" New patches, with the suggested spelling. For 3.0 and 2.6. It would be a damned shame to slow down the entire language to save code that is intentionally shooting itself in the foot. EVERYONE will pay a cost -- NO ONE will benefit. My two cents. Here are some timings, on winXP, vs2008 release build: # t.py def f(l=range(5000)): for x in l: pass # before the patch > python -m timeit -s "from t import f" "f()" 10000 loops, best of 3: 159 usec per loop # after the patch > python -m timeit -s "from t import f" "f()" 10000 loops, best of 3: 160 usec per loop and these figures are pretty stable on my machine. Is it too much to pay? Some may consider that potential crashes are more expensive. Go" The same approach can be used to segfault many more places. See . This patch fixes Armin's list of crashers for trunk. Looking for others like them. Hopefully the right patch this time :/ Amaury, if you decide to go forward with this, please clean-up the patches to eliminate common subexpressions. Wonder if there is an alternate solution that keeps the next slot filled with something that raises an Attribute error. I.) Raymond, I think a different solution would be great, as the performance penalty might become nasty in tight loops if we miss some detail. Regarding the possible impact, I hope we can get a better estimate since the other examples of segfaulting that look like Armin's I've found are in itertools. I imagine you have the right tests to check the effect of any changes there. It's not just performance -- the patch code is grotesque. Lots of code would need to be changed just before the release candidate (usually a bad idea). And the underlying problem doesn't seem to be one that has *ever* affected a real user since 2.2. I have a hard time caring much about this problem. The minor performance hit only bugs me because it affects the inner- loops of just about every piece of real python code -- everyone will pay a cost for this change. Since the "problem" has existed so long with no ill effect, am unmarking the "release blocker" priority. Would rather have a thoughtful discussion on alternatives along with a careful, thorough, efficient patch for a bug release version. > Ama) It was the ajaksu2 patches that needed clean-up. The next-nevernull patch is much cleaner than I expected. Nice work. The assertion in abstract.c can be changed to: assert(iter==PyObject_NextNotImplemented || PyIter_Check(iter)); Armin, are you happy with the new approach? Though "del obj.next" isn't doing exactly what you would expect, that seems harmless to me. Hacking at typeobject.c should always be done extremely carefully. I don't have time to review this patch as thouroughly as I think it needs to be. (A quick issue is that it seems to break PyIter_Check() which will always return true now, but I'd recommend a much more thourough review.) Did) Maybe the file 'next-nevernull.patch' is not complete? I don't see any change in the definition of PyIter_Check(). Oops, sorry. I have too many files opened at the same time. Here is an updated patch. I removed all the "assert(PyIter_Check(it))", our evil iterator used to make them fail anyway in debug mode; and in the case of a null function pointer, the C stack gives the same information. I think PyObject_NextNotImplemented should be renamed to _PyObject_NextNotImplemented. Aside from that, I think the patch is ready for committing. Any? Fixed in r68560 (trunk) and r68561 (py3k). Difficult to backport: extensions compiled with 2.6.x would not run on 2.6.0. Yes,... nice. I'm okay with that hack for 2.6 and 2.5. The fix works for 3.1.2, giving TypeError: iter() returned non-iterator of type 'BadIterator' Too late to patch 2.5. Is there any intention of patching 2.6 before its final bug-fix release, in a couple of months? Too late for 2.6.6 ;-)
https://bugs.python.org/issue3720
CC-MAIN-2019-09
refinedweb
757
75.91
I posted a similar question and the problem could not be replicated. I also though it might have been the workstation and all the libraries, controls, et. al. installed on the machine. Problem exists with a new Windows 10 workstation. Using Infragistics ASP.NET 2017.2; controls used in set Infragistics45.Web.v17.2, Version=17.2.20172.2095 This is the problem (see image) - created a web application in VS 2017. Open a new Web Form and place a WebTab on the form. Expand the webtab to almost the size of the screen and you can see a blank footer / empty space at the bottom of tab. Nothing done removes or resizes this dead area. Environment : Windows 10 Professional .NET Code 2.0.8 Windows Hosting .NET Core Runtime - 2.0.7 (x64) .NET Core Runtime - 2.0.7 (x32) .NET Framework 4.5 Multi-Targeting Pack .NET Framework 4.5.1 Multi-Targeting Pack .NET Framework 4.5.2 Multi-Targeting Pack Visual Studio 2008 Professional - ENU Visual Studio 2017 Visual Studio Tools for Application 2015 Visual Studio Tools for Application 2015 Language Support Hello Mark, Thank you for posting in our community. I noticed that the service release that you are using is not the latest one for version 17.2. At this point, the latest SR available for download is 20172.2123. Can you please try downloading the latest version and let me know whether you are still experiencing the same behavior? The latest version can be downloaded from our web site. You need to log in with your credentials and navigate to "My Keys &Downloads" section. Click the product of your choice and under "Service Releases" tab you will find all service releases for this product If you need any assistance do not hesitate to contact me. Looking forward to hearing from you. Hello Vasya, I had a production release and was holding off on upgrading until the next dev cycle, but will try the update and see. Will post back with results. Mark Upgrade to the latest version and the results are exactly the same. Instead of using the existing application, created an empty project and added to web tabs (inside a DIV and another outside); the results are the same and there is still a footer - I cannot get the tab to be the size of the actual tab container. Here is the source for the form: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %> <%@ Register assembly="Infragistics4.Web.v17.2, Version=17.2.20172.2123, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" namespace="Infragistics.Web.UI.LayoutControls" tagprefix="ig" %> <!DOCTYPE html> <html xmlns="">"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <ig:WebTab <tabs> <ig:ContentTabItem </ig:ContentTabItem> <ig:ContentTabItem </ig:ContentTabItem> </tabs> </ig:WebTab> </div> <ig:WebTab <tabs> <ig:ContentTabItem </ig:ContentTabItem> <ig:ContentTabItem </ig:ContentTabItem> </tabs> </ig:WebTab> </form></body></html> Designer View with the footer: Vasay, Posted 2 hours ago new results - same as before. You will have to wait for you over over the top content filters to see the results. Thank you for getting back to me. Take your time, test with the latest service release and let me know whether the described behavior still persists. Please feel free to contact me if you need any further assistance.
https://www.infragistics.com/community/forums/f/ultimate-ui-for-asp-net/119293/footer-dead-space-bottom-of-webtab
CC-MAIN-2019-04
refinedweb
557
59.09
The Joblib Python Library handles frequent problems – like parallelization, memorization, and saving and loading objects – in almost no time, giving programmers more freedom to push on with their core tasks. A Library for Many Jobs In recent years, new programming concepts have enriched the computer world. Instead of increasing processor speed, the number of processors have grown in many data centers. Parallel processing supports the handling of large amounts of data but also often requires a delicate transition from traditional, sequential procedures to specially adapted methods. The Joblib Python library saves much error-prone programming in typical procedures such as caching and parallelization. A number of complex tasks come to mind when you think about parallel processing. The use of large data sets, wherein each entry is independent of the other, is an excellent choice for simultaneous processing by many CPUs (Figure 1). Tasks like this are referred to as “embarrassingly” parallel. Where exactly the term comes from is unclear, but it does suggest that converting an algorithm to a parallelized version should not take long. Experienced developers know, however, that problems can occur in everyday programming practice in any new implementation and that you can quickly get bogged down in the implementation details. The Joblib module, an easy solution for embarrassingly parallel tasks, offers a Parallel class, which requires an arbitrary function that takes exactly one argument. Parallel Decoration To help Parallel cooperate with the function in question (I’ll call it f(x)), Joblib comes with a delayed() method, which acts as the decorator. Listing 1 shows a simple example of an implementation of f(x) that returns x unchanged. The for loop shown in Listing 1 iterates over a list l and passes the individual values to f(x); each list item in l results in a separate job. Listing 1: Joblib: Embarrassingly Parallel 01 from joblib import Parallel, delayed 02 03 def f(x): 04 return x 05 06 l = range(5) 07 results = Parallel(n_jobs=-1)(delayed(f)(i) for i in l)) The most interesting part of the work is handled by the anonymous Parallel object, which is generated on the fly. It distributes the calls to f(x) across the computer’s various CPUs or processor cores. The n_jobs argument determines how many it uses. By default, this is set to 1, so that Parallel only starts a subprocess. Setting it to -1 uses all the available cores, -2 leaves one core unused, -3 leaves two unused, and so on. Alternatively n_jobs takes a positive integer as a counter that directly defines the number of processes to use. The value of n_jobs can also be more than the number of available physical cores; the Parallel class simply starts the number of Python processes defined by n_jobs, and the operating system lets them run side by side. Incidentally, this also means that the exchange of global variables between the individual jobs is impossible, because different operating system processes cannot directly communicate with one another. Parallel bypasses this limitation by serializing and caching the necessary objects. The optimum number of processes depends primarily on the type of tasks to be performed. If your bottleneck is reading and writing data to the local hard disk or across the network, rather than processor power, the number of processes can be higher. As a rule of thumb, you can go for the number of available processor cores times 1.5; however, if each process fully loads a CPU permanently, you will not want to exceed the number of available physical processors. See How They Run Additionally, the Parallel class offers an optional verbose argument with regular output of status messages that illustrate the overall progress. The messages show the number of processed and remaining jobs and, if possible, the estimated remaining and elapsed time. The verbose option is by default set to 0; you can set it to an arbitrary positive number to increase the output frequency. Note that the higher the value of verbose, the more intermediate steps Joblib outputs. Listing 2 shows typical output. Listing 2: Parallel with Status Reports Parallel(n_jobs=2, verbose=5)(delayed(f)(i) for i in l)) [Parallel(n_jobs=2)]: Done 1 out of 181 | elapsed: 0.0s remaining: 4.5s [Parallel(n_jobs=2)]: Done 198 out of 1000 | elapsed: 1.2s remaining: 4.8s [Parallel(n_jobs=2)]: Done 399 out of 1000 | elapsed: 2.3s remaining: 3.5s [Parallel(n_jobs=2)]: Done 600 out of 1000 | elapsed: 3.4s remaining: 2.3s [Parallel(n_jobs=2)]: Done 801 out of 1000 | elapsed: 4.5s remaining: 1.1s [Parallel(n_jobs=2)]: Done 1000 out of 1000 | elapsed: 5.5s finished The exact number of interim reports varies. At the beginning of execution, it is often still unclear how many jobs are pending in total, so this number is only an approximation. If you set verbose to a value above 10, Parallel outputs the current status after each iteration. Additionally, the argument offers the option of redirecting the output: If you set verbose to a value of more than 50, Parallel writes status reports to standard output. If it is lower, Parallel uses stderr – that is, the error channel of the active shell. A third, optional argument that Parallel takes is pre_dispatch, which defines how many of the jobs the class should queue up for immediate processing. By default, Parallel directly loads all the list items into memory, and pre_dispatch is set to 'all'. However, if processing consumes a large amount of memory, a lower value provides an opportunity to save RAM. To do this, you can enter a positive integer. Convenient Multiprocessing Module With its Parallel class, Joblib essentially provides a convenient interface for the Python multiprocessing module. It supports the same functionality, but the combination of Parallel and delayed() reduces the implementation overhead of simple parallelization tasks to a one-liner. Additionally, status outputs and configuration options are available – each with an argument. In Memory The previous example made use of a small and practically useless f(x) function. Some functions, however, regardless of whether they are parallelized, perform very time- and resource-consuming computations. If the input values are unknown before starting the program, a function like this might process the same arguments multiple times; this overhead could be unnecessary. For more complicated functions, therefore, it makes sense to save the results (memorization). If the function is invoked with the same argument, it just grabs the existing result, rather than figuring things out again. Here, too programmers can look to Joblib for help – in the form of the Memory class this time. Joblib provides a cache() method that serves as the decorator for arbitrary functions with one or more functional arguments. The results of the decorated function are then saved on disk by the memory object. The next time the function is called, it checks to see whether the same argument or the same arguments have been processed and, if so, returns the result directly (Figure 2). Listing 3 shows an implementation, again with a primitive sample function f(x). Listing 3: Store Function Results 01 from joblib import Memory 02 03 memory = Memory(cachedir='/tmp/example/') 04 05 @memory.cache 06 def f(x): 07 return x The computed results are stored on disk in the JOBLIB directory below the directory defined by the cachedir parameter. Here again, each memorized function has its own subdirectory, which, among other things, contains the original Python source code of the function in the func_code.py file. Memory for Names A separate subdirectory also exists for each different argument – or, depending on the function, each different combination of several arguments. It is named for a hash value of the arguments passed in and contains two files: input_args.json and output.pkl. The first file shows the input arguments in the human-readable JSON format, and the second is the corresponding result in the binary pickle format used by Python to serialize and store objects. This structure makes accessing the cached results of the memory function pleasantly transparent. The Python pickle module, for example, parses the results in the Python interpreter: import pickle result = pickle.load(open("output.pkl")) Memory does not clean up on its own at end of the program, which means the stored results are still available the next time the program starts. However, this also means you need to clean up the disk space yourself, if necessary, which is done either by calling the clear() method of the Memory object or simply by deleting the folder. Additionally, you should note that Memory bases its reading of the stored results exclusively on the function name. If you change the implementation, Memory might erroneously return the results previously generated by the old version of the function the next time you start it. Furthermore, Memory does not work with lambda functions – that is, nameless functions that are defined directly in the call. As a general rule, use of the Memory class is recommended for functions whose results are so large they stress your computer’s RAM. If a frequently called function only generates small results, however, creating a dictionary-based in-memory cache makes more sense. A sample implementation is shown on the ActiveState website. Fast and Frugal On request, the Memory class uses a procedure that saves a lot of time for large stored objects: memory mapping. The core idea behind this approach is to write a file as a bit-for-bit copy of an object from memory to the hard disk. When the software opens the object again, it copies the relevant part of the file into contiguous memory so that the objects it contains are directly available. This approach keeps the system from having to allocate memory, which can involve many system calls. Joblib uses the memory mapping method provided by the NumPy Python module. The constructor in the Memory class uses the optional mmap_mode parameter to accept the same arguments as the numpy.memmap class: r+, r, w+, and c. Memory Mapping Under normal circumstances, mmap_mode='r+' is recommended for enabling memory mapping. This value opens an optionally existing file and appends new data. In the other modes, Memory does not write any new data but only reads from the existing file (r) or overwrites the existing data (w+). The c (copy-on-write) mode tells Memory to treat the file on the disk as immutable, as with r, but it does keep new assignments in memory. If you need to save disk space rather than time, you can initialize the memory object with the argument compress=True. This option tells the Memory function to compress results when saving to disk; however, it rules out the option of memory mapping. Finally, the Memory class also allows you to issue status messages. Its verbose constructor argument defaults to 1, which means that cache() outputs a status message every time a memorized function is called when computing the results from scratch. If you substitute verbose=0, the potentially very numerous status reports are suppressed. Substituting the default value for something higher tells Memory to report on each call of the function, whether the result was in a file or is recomputed. Finally, cache() uses the ignore parameter to accept a list of function arguments that it ignores during memorization. This functionality is useful, if individual function arguments only affect the screen output but not the function result. Listing 4 shows the f(x) function with the additional verbose argument, whose value is irrelevant for the return value of the function. Listing 4: Ignoring Individual Arguments 01 from joblib import Memory 02 03 memory = Memory() 04 05 @memory.cache(ignore=['verbose']) 06 def f(x, verbose=0): 07 if verbose > 0: 08 print('Running f(x).') 09 return x On Disk Joblib also provides two functions for saving and loading Python objects: joblib.dump() and joblib.load(). These functions are also used in the Memory class, but they also work independently of it and replace the Python pickle module’s mechanisms for serializing objects with what are often more efficient methods. In particular, Joblib stores large NumPy arrays quickly and in a space-saving way. The joblib.dump() function accepts any Python object and a file name as arguments. Without other parameters, the object ends up in the specified file. Calling joblib.load() with the same file name then restores this object: import joblib x = ... joblib.dump(x, 'file') ... x = joblib.load('file') Like Memory, dump() also supports the optional compress parameter. This parameter is a number from 0 to 9, indicating the compression level: 0 means no compression at all; 9 uses the least disk space but also takes the most time. In combination with compress, the cache_size argument also determines how much memory Joblib uses to compress data quickly before writing to disk. The specified value describes the size in megabytes, but that is merely an estimate that Joblib exceeds if needed, such as when handling very large NumPy arrays. The dump() complement load() also optionally uses the memory mapping method – like Memory. The mmap_mode argument enables this with the same parameters and possible values as for Memory: r+, r, w+, and c are used for reading and writing, exclusive reading, overwriting, or read-only and in-memory completion. Prestigious Helper The value of the Joblib library is hard to overstate. It solves some common tasks in a flash with an intuitive interface. The problems – simple parallelization, memorization, and saving and loading objects – are those programmers often encounter in practice. What you find here is a convenient solution that gives you more time to devote to genuine problems. Joblib is included in most distributions and can otherwise easily be imported with the Python package management tools, Easy Install and Pip, using easy_install joblib or pip install joblib. This process is quick, because – besides Python itself – Joblib does not require any other packages.
http://www.admin-magazine.com/HPC/Articles/Parallel-Python-with-Joblib/(tagID)/664
CC-MAIN-2019-18
refinedweb
2,323
53.1
68919/import-error-no-module-name-urllib2 Here's my code: import urllib2.request response = urllib2.urlopen("") html = response.read() print(html) Any help? As stated in the urllib2 documentation: The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool(""). Thank You!! Hello, Open Cmd or Powershell as Admin. type pip ...READ MORE Hi, If you successfully installed opencv in your ...READ MORE Run with Python 3 from the command ...READ MORE To overcome this issue, you need to .. Hello, I had numpy installed on the same ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/68919/import-error-no-module-name-urllib2
CC-MAIN-2022-33
refinedweb
124
71.41
I need to get a stack trace object in Ruby; not to print it, just to get it to do some recording and dumping for later analysis. Is that possible? How? For Ruby 2.0+, you can use Kernel#caller_locations. It is essentially the same as Kernel#caller (covered in Sven Koschnicke's answer), except that instead of returning an array of strings, it returns an array of Thread::Backtrace::Location objects. Thread::Backtrace::Location provides methods such as path, lineno, and base_label, which may be useful when you need access to specific details about the stack trace, and not just a raw string. Returns the current execution stack—an array containing backtrace location objects. See Thread::Backtrace::Location for more information.. Usage example: def a caller_locations(0) end def b a end def c b end c.map(&:base_label) #=> ["a", "b", "c", "<main>"]
https://www.dowemo.com/article/70315/in-ruby,-how-to-get-stack-trace-objects
CC-MAIN-2018-26
refinedweb
144
58.28
Thanks. We are exploiting an inter-procedural k-layer escape analysis, which are not dependent on inlining. So we will do some cross-procedure type propagation ourselves. :-) Could you give us some advices on it according to your experiences? --clara ----- Original Message ----- From: "Mikhail Fursov" <mike.fursov@gmail.com> To: <dev@harmony.apache.org> Sent: Monday, July 02, 2007 8:15 PM Subject: Re: [drlvm][jitrino]Are there any static type checking and type propagation? > My 2 cents: > > Clara, > in your example the type of collection is known at compile time (Tree) so no > devirtualization is required and 'virtual' call must be replaced with > 'special' (or direct) call by JIT. > If inliner inlines 'bodies' method - the type of 'bodyTab' is also known at > compile time and 'elements' method is also can be inlined. > > Right after method inlining you can see in log that there are operations > like 'copy o1(type MyMap), o2(type java.util.Map)' that are used to join > args and return values of inlinee and inliner methods. Use simplification > pass ('simplify','uce','dce') to remove redundant copy instructions and > propagate operand types. > > Hope it helps. > > On 02 Jul 2007 10:37:42 +0400, Egor Pasko <egor.pasko@gmail.com> wrote: >> >> On the 0x307 day of Apache Harmony Xiao-Feng Li wrote: >> > On 7/2/07, clara <clarazhang@gmail.com> wrote: >> > > Each operand has type info in JIT IR, and I think the type is decided >> > > according to the declarations. >> > > However, the runtime type of some operands can be decided in >> compilation. >> > > Are there any optpasses which do some type inference or analyzing? >> > > >> > > For example, the below are 3 classes, according to analyzing the code, >> we >> > > know the runtime type of e is Body$Enumerate. >> > > >> > > public class BH >> > > { >> > > Tree root = new Tree(); >> > > ... >> > > public static final void main(String args[]) >> > > { >> > > for (Enumeration e = root.bodies(); e.hasMoreElements(); ) >> > > ... >> > > } >> > > } >> > > class Tree >> > > { >> > > ... >> > > private Body bodyTab; >> > > final Enumeration bodies() >> > > { >> > > return bodyTab.elements(); >> > > } >> > > ... >> > > >> > > } >> > > final class Body extends Node >> > > { >> > > final Enumeration elements() >> > > { >> > > // a local class that implements the enumerator >> > > class Enumerate implements Enumeration { >> > > private Body current; >> > > public Enumerate() { this.current = Body.this; } >> > > public boolean hasMoreElements() { return (current != >> null); } >> > > public Object nextElement() { >> > > Object retval = current; >> > > current = current.next; >> > > return retval; >> > > } >> > > } >> > > return new Enumerate(); >> > > } >> > > >> > > } >> > >> > Clara, now I understand what you meant. It is about cross-procedure >> > type propagation. I guess this should be done with IPA. I do not know >> > about how Jitrino deals with it. In Open64 (ORC) for speculative >> > analysis, we used inlining to propagate the information automatically. >> >> Yep, Jitrino loves to inline final methods. And here it would know the >> exact type. If there are several variants of a type on some call site, >> then the target type can be 'predicted' using profile information and >> then devirtualized (with a 'guard') upto the exact type. This >> optimization is limited and per-callsite. >> >> So, Jitrino does not perform inter-procedural type prediction >> optimization except one: the "Lazy Exception" optimization that allows >> to bypass constructing exception if it is not used in catch blocks of >> other methods. (In this case I would also prefer to aggressively >> inline the hottest throw-catch paths with partial inlining, to make >> code less bloated) >> >> >> -- >> Egor Pasko >> >> > > > -- > Mikhail Fursov >
http://mail-archives.apache.org/mod_mbox/harmony-dev/200707.mbox/%3C00cd01c7bd27$4d965320$3701a8c0@SUNUSTC%3E
CC-MAIN-2015-48
refinedweb
527
57.37
funvas 0.0.3+1 funvas: ^0.0.3+1 funvas: ^0.1.0-nullsafety.0 Package for creating canvas animations based on time and math functions. Fun + canvas -> funvas :) funvas # Flutter package that allows creating canvas animations based on time and math functions. The name "funvas" is based on Flutter + fun + canvas. Let me know if you have any better ideas :) Concept # The idea of the package is to provide an easy way to create custom canvas animations based only on time and some math functions (sine, cosine, etc.) - like this one. Inspired by Dwitter (check it out). This is also the reason why the following shortcut functions and variables are available; they might be expanded upon in the future given that there are a lot more possibilities: u(t) is called 60 times per second. t: Elapsed time in seconds. S: Shorthand for sin from dart:math. C: Shorthand for cos from dart:math. T: Shorthand for tan from dart:math. R: Shorthand for Color.fromRGBA, usage ex.: R(255, 255, 255, 0.5) c: A dart:ui canvas. x: A context for the canvas, providing size. You can of course use all of the Canvas functionality, the same way you can use them in a CustomPainter; the above is just in homage to Dwitter :) Usage # You create funvas animations by extending Funvas and you can display the animations using a [FunvasContainer]. Note that you have to size the animation from outside, e.g. using a [SizedBox]. import 'package:flutter/material.dart'; import 'package:funvas/funvas.dart'; /// Example implementation of a funvas. /// /// The animation is drawn in [u] based on [t] in seconds. class ExampleFunvas extends Funvas { @override void u(double t) { c.drawCircle( Offset(x.width / 2, x.height / 2), S(t).abs() * x.height / 4 + 42, Paint()..color = R(C(t) * 255, 42, 60 + T(t)), ); } } /// Example widget that displays the [ExampleFunvas] animation. class ExampleFunvasWidget extends StatelessWidget { @override Widget build(BuildContext context) { return SizedBox( width: 420, height: 420, child: FunvasContainer( funvas: ExampleFunvas(), ), ); } } See the example package for a complete example implementation. Exporting animations # In the example package, there is also an exporter that can be used to export funvas animations directly to GIF. See the example/README.md file for an explanation.
https://pub.dev/packages/funvas
CC-MAIN-2020-50
refinedweb
376
52.66
package idraw; import colors.*; import geometry.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.*; import java.util.*; import javax.swing.*; /** * Copyright 2007, 2008 Viera K. Proulx * This program is distributed under the terms of the * GNU Lesser General Public License (LGPL) */ /** * A buffered panel to hold the drawings. */ public class CanvasPanel extends JPanel { ///////////////// // Member Data // ///////////////// /** The buffered image that maintains the persistent graphics state. */ protected BufferedImage buffer = null; /** The internal painter panel. */ protected CanvasPanel.Painter painter = null; /** The width and height for this buffered panel. */ protected int WIDTH; protected int HEIGHT; /** * Constructs a BufferedPanel containing a buffered image * with the given width and height, * and the given background color or Paint * for the image. If the given width or height is less than 1 pixel, * that value is set to 1 pixel.* * Though the component itself may grow arbitrarily large, * the buffered image painted to the buffer will * remain the size specified in this constructor * unless the size is reset using the * setBufferSize method. Returns a Graphics2D object that permits * painting to the internal buffered image for this panel. The user should always use this object to paint to the * buffer and thus indirectly modify this buffered panel.* * To make painting changes to the buffer visible, the * repaint() method must explicitly be called. * This allows a number of painting operations to be done * prior to screen repaint. Sets the size of the buffered image * to the given height and width.* * If the given width or height * is less than 1 pixel, it is set to 1 pixel.* * Any image area gained by an size increase in either direction * will be painted with the current background color.* * Any image area lost by a size decrease in either direction * will be clipped on the right and/or bottom of the image.* * For a short time both the image of the previous size * and an image of the new size are maintained in memory.* * @param width the new width for the image * @param height the new height for the image */ public synchronized void setBufferSize(int width, int height) { // ensure positive width and height width = (int)Math.max(width, 1); height = (int)Math.max(height, 1); // save current buffer so we can later paint onto new buffer BufferedImage oldBuffer = buffer; // build the new buffered image buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // clear the new buffered image clearPanel(); // paint the old image to the new buffer if necessary if (oldBuffer != null) { Graphics2D g2 = getBufferGraphics(); g2.drawImage(oldBuffer, 0, 0, this); } // refresh the enclosing window to account for the new buffer size //refreshComponent(); Refresh.packParentWindow(this); } /** Returns the width of the buffered image. */ public synchronized final int getBufferWidth() { return buffer.getWidth(); } /** Returns the height of the buffered image. */ public synchronized final int getBufferHeight() { return buffer.getHeight(); } /** Returns the internal buffered image for this panel.*/ public final BufferedImage getBuffer() { return buffer; } /** * Returns the internal panel for this buffered panel, * that is, the panel that paints the buffered image * and handles the mouse and key adapters.* * This panel may be used when access to the panel on * which the graphics is drawn is needed.* * Do not set a border on this internal panel. Set a * border on the outer BufferedPanel object. Fills this buffered panel * with its background color or Paint. Draws a circle* * @param center the center of this circle * @param radius the radius of this circle * @param color the color of this circle */ public void drawCircle(Posn center, int radius, Color color) { if (radius <= 0) return; if (color == null) color = new Color(0, 0, 0); this.drawShape(new Ellipse2D.Double(center.x - radius, center.y - radius, 2 * radius, 2 * radius), color, false); } /** * Draws a disk* * @param center the center of this circle * @param radius the radius of this circle * @param color the color of this circle */ public void drawDisk(Posn center, int radius, Color color) { if (radius <= 0) return; if (color == null) color = new Color(0, 0, 0); this.drawShape(new Ellipse2D.Double(center.x - radius, center.y - radius, 2 * radius, 2 * radius), color, true); } /** * Draws a rectangle* * @param nw the NW corner of this rectangle * @param width the width of this rectangle * @param height the height of this rectangle * @param color the color of this rectangle */ public void drawRect(Posn nw, int width, int height, Color color){ if (width < 0 || height < 0) return; if (color == null) color = new Color(0, 0, 0); this.drawShape(new Rectangle2D.Double(nw.x, nw.y, width, height), color, true); } /** * Draws a line* * @param p1 the starting point of this line * @param p2 the ending point of this line * @param color the color of this line */ public void drawLine(Posn p1, Posn p2, Color color){ //this.drawShape(new Line2D.Double(p1.x, p1.y, p2.x, p2.y), // color, true); this.drawShape(new Line2D.Double(p1.x, p1.y, p2.x, p2.y), color, false); } /** * Draws a String* * @param p the bottom right edge of the String* s the Stringto draw */ public void drawString(Posn p, String s){ if (s == null) s = ""; Graphics2D g = getBufferGraphics(); Paint oldPaint = g.getPaint(); g.setPaint(new Color(0, 0, 0)); g.drawString(s, p.x, p.y); g.setPaint(oldPaint); repaint(); } /** *(). Override this paintOver method to add additional * painting actions after the default buffer repaint is done during * a repaint() call. The intention of this facility is to enable algorithmic * painting to be done via the paintOver method on * top of the default painting of the buffer image on the panel. * This makes the buffer appear to be the background and what is * painted via the paintOver method to be painted in * the foreground. The default implementation of the paintOver * method is to do nothing. This enables overrides as desired. As of 2.4.0, this method is called after both the painting of * the buffer and the painting of the internal paintable sequence. * Given the power inherent in painting both the buffer bitmap and * the internal paintable sequence, it is rare that this method * will need to be overridden.* * @param g2 the Graphics2Dcontext for the buffer * repaint operation * @since 1.0.1 */ public void paintOver(Graphics2D g2) { // intentionally left empty to allow for overrides } /////////////////// // Inner classes // /////////////////// /* THE CODE BELOW HAS BEEN ADAPTED AND MODIFIED FROM THE FOLLOWING: * * @(#)BufferedPanel.java 2.6.0e 19 November 2007 * * Copyright 2007 *. */ /** * Panel that paints the internal buffered image that * maintains the persistent graphics state of the buffered * panel.* * @author Jeff Raab * @author Richard Rasala * @author - adapted by Viera K. Proulx * @version 2.4.0 * @since 1.0 */ protected static class Painter extends JPanel { /** * Reference to the CanvasPanelthat created this * Painter. */ protected CanvasPanel panel = null; /** * Contructor that should only be called by a * CanvasPanel. * * @param panel the CanvasPanelused to construct * this Painter*/ protected Painter(CanvasPanel panel) { this.panel = panel; } /** * Returns the size of the buffer as the size of this panel.* * Ignores any calls to setPreferredSize. Paints the image buffer of the buffered panel in this panel * * As of 2.6.0c, is synchronized on the enclosing buffered panel.* * @param g the standard graphics state for this panel */ protected void paintComponent(Graphics g) { synchronized (panel) { Insets in = getInsets(); int x = in.left; int y = in.top; g.drawImage(panel.getBuffer(), x, y, this); g.translate( x, y); //panel.paintablesequence.paint(g); g.translate(-x, -y); } } /** * Paints the component and then adds the work done by the * paintOver function.* * As of 2.6.0c, is synchronized on the enclosing buffered panel.* * @param g the standard graphics state for this panel */ public void paint(Graphics g) { synchronized (panel) { // this call will call paintComponent to paint the buffer super.paint(g); Graphics2D g2 = (Graphics2D) g; Insets in = getInsets(); int x = in.left; int y = in.top; g2.translate( x, y); panel.paintOver(g2); g2.translate(-x, -y); } } } /** * Class Refresh encapsulates methods for graphics refresh. Class Refresh cannot be instantiated. Revalidates the given component, packs its parent window, and then * repaints the component.* * As of 2.3.3, prevents indirect recursive calls to this method that * attempt to pack the same window object.* * As of 2.6.0c, makes the parent window invisible, then packs, and * then makes the parent window visible.* * @param component the component whose parent window should be packed */ public static void packParentWindow(JComponent component) { if (component == null) return; component.revalidate(); JRootPane pane = component.getRootPane(); if (pane != null) { Object parent = ((JRootPane) pane).getParent(); if (parent instanceof Window) { synchronized(windowHashtable) { Window window = (Window) parent; if (! windowHashtable.containsKey(window)) { windowHashtable.put(window, window); window.setVisible(false); window.pack(); window.setVisible(true); windowHashtable.remove(window); } } } } component.repaint(); } } /** * A helper class to consolidate paining of different shapes. * @author Viera K. Proulx */ class ColorShape{ Shape s; IColor c; Color col; // a useless constructor, allowing the definition of a fake subclass ColorShape(){} ColorShape(Shape s, IColor c){ this.s = s; this.c = c; this.col = c.thisColor(); } ColorShape(Shape s, Color col){ this.s = s; this.col = col; } public void draw(Graphics2D g){ g.setPaint(col); g.draw(s); } } /** * A helper class to consolidate paining of a Stringshape. * @author Viera K. Proulx */ class StringShape extends ColorShape{ String s; Posn p; StringShape(String s, Posn p){ this.s = s; this.p = p; this.col = new Color(0, 0, 0); } public void draw(Graphics2D g){ g.setPaint(col); g.drawString(s, p.x, p.y); } }
http://www.ccs.neu.edu/javalib/Sources/v1.0/idraw/CanvasPanel.java
crawl-003
refinedweb
1,546
57.87
- 問題 Problem 46:Goldbach's other conjecture It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? - 解答例 def isPrime(num): if num <= 1: return False elif num == 2 or num == 3: return True if num % 2 == 0 or num % 3 == 0: return False if not(num % 6 == 1) and not(num % 6 == 5): return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False i += 6 return True ansList = [] num = 9 while len(ansList) < 1: isFound = False if isPrime(num): num += 2 isFound = True continue i = 1 while (num - 2 * i * i) > 0: if isPrime(num - 2 * i * i): isFound = True break i += 1 if not isFound: ansList.append(num) num += 2 print(ansList)
http://blog.muchance.jp/entry/2017/07/03/233000
CC-MAIN-2019-09
refinedweb
195
61.94
Inferring DataSet Relational Structure from XML The relational structure, or schema, of a DataSet is made up of tables, columns, constraints, and relations. When loading a DataSet from XML, the schema can be predefined, or it can be created, either explicitly or through inference, from the XML being loaded. For more information about loading the schema and contents of a DataSet from XML, see Loading a DataSet from XML and Loading DataSet Schema Information from XML. If the schema of a DataSet is being created from XML, the preferred method is to explicitly specify the schema using either the XML Schema definition language (XSD) (as described in Deriving DataSet Relational Structure from XML Schema (XSD)) or the XML-Data Reduced (XDR). If no XML Schema or XDR schema is available in the XML, the schema of the DataSet can be inferred from the structure of the XML elements and attributes. This section describes the rules for DataSet schema inference by showing XML elements and attributes and their structure, and the resulting inferred DataSet schema. Not all attributes present in an XML document should be included in the inference process. Namespace-qualified attributes can include metadata that is important for the XML document but not for the DataSet schema. Using InferXmlSchema, you can specify namespaces to be ignored during the inference process. For more information, see Loading DataSet Schema Information from XML.
http://msdn.microsoft.com/en-us/library/3b4194wc.aspx
CC-MAIN-2014-10
refinedweb
231
56.69
Here in this part of the HBase tutorial you will learn the basics of client API, CRUD operations, KeyValue Class, application for inserting data into database, application for retrieving data from database, row locks and more.. void put(Put put) throws IOException It expects one or a list of Put objects that, in turn, are created with one of these constructors: Put(byte[] row) Put(byte[] row, RowLock rowLock) Put(byte[] row, long ts) Put(byte[] row, long ts, RowLock rowLock) You need to supply a row to create a Put instance. A row in HBase is identified by a unique row key and—as is the case with most values in HBase—this is a Java byte[] array. Once you have created the Put instance you can add data to it. This is done using these methods: Put add(byte[] family, byte[] qualifier, byte[] value) Put add(byte[] family, byte[] qualifier, long ts, byte[] value) Put add(KeyValue kv) throws IOException Each call to add() specifies exactly one column, or, in combination with an optional timestamp, one single cell. Note that if you do not specify the timestamp with the add() call, the Put instance will use the optional timestamp parameter from the constructor (also called ts) and you should leave it to the region server to set it. If you want to learn about Operations using Java API, refer to this insightful Blog! From your code you may have to deal with KeyValue instances directly. These instances contain the data as well as the coordinates of one specific cell. The coordinates are the row key, name of the column family, column qualifier, and timestamp. The class provides a plethora of constructors that allow you to combine all of these in many variations. The fully specified constructor looks like this: KeyValue(byte[] row, int roffset, int rlength, byte[] family, int foffset, int flength, byte[] qualifier, int qoffset, int qlength, long timestamp, Type type, byte[] value, int voffset, int vlength) The client API has the ability to insert single Put instances, but it also has the advanced feature of batching operations together. This comes in the form of the following call: void put(List<Put> puts) throws IOException There is a special variation of the put calls that warrants its own section: check and put. The method signature is: boolean checkAndPut(byte[] row, byte[] family, byte[] qualifier, byte[] value, Put put) throws IOException This call allows you to issue atomic, server-side mutations that are guarded by an accompanying check. If the check passes successfully, the put operation is executed; otherwise, it aborts the operation completely. It can be used to update data based on current, possibly related, values. Example – Application inserting data into HBase import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class PutExample { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); 1. HTable table = new HTable(conf, "testtable"); 2. Put put = new Put(Bytes.toBytes("row1")); 3. put.add(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1"), Bytes.toBytes("val1")); 4. put.add(Bytes.toBytes("colfam1"), Bytes.toBytes("qual2"), Bytes.toBytes("val2")); 5. table.put(put); 6. } } } 5.1.2 Get Method The next step in a client API is to retrieve what was just saved. For that the HTable is providing you with the Get call and matching classes. The operations are split into those that operate on a single row and those that retrieve multiple rows in one call. First, the method that is used to retrieve specific values from an HBase table: Result get(Get get) throws IOException Similar to the Put class for the put() call, there is a matching Get class used by the aforementioned get() function. As another similarity, you will have to provide a row key when creating an instance of Get, using one of these constructors: Get(byte[] row) Get(byte[] row, RowLock rowLock) When you retrieve data using the get() calls, you receive an instance of the Result class that contains all the matching cells. It provides you with the means to access everything that was returned from the server for the given row and matching the specified query, such as column family, column qualifier, timestamp, and so on. Another similarity to the put() calls is that you can ask for more than one row using a single request. This allows you to quickly and efficiently retrieve related—but also completely random, if required—data from the remote servers. The method provided by the API has the following signature: Result[] get(List<Get> gets) throws IOException Example . Application retrieving data from HBase Configuration conf = HBaseConfiguration.create(); 1. HTable table = new HTable(conf, "testtable"); 2. Get get = new Get(Bytes.toBytes("row1")); 3. get.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1")); 4. Result result = table.get(get); 5. byte[] val = result.getValue(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1")); 6. System.out.println("Value: " + Bytes.toString(val)); 7. 5.1.3. Delete method This method is used to delete the data from Hbase tables. The variant of the delete() call that takes a single Delete instance is: void delete(Delete delete) throws IOException Just as with the get() and put() calls you saw already, you will have to create a Delete instance and then add details about the data you want to remove. The constructors are: Delete(byte[] row) Delete(byte[] row, long timestamp, RowLock rowLock) You need to provide the row you want to modify, and optionally provide a rowLock, an instance of RowLock to specify your own lock details, in case you want to modify the same row more than once subsequently. The list-based delete() call works very similarly to the list-based put(). You need to create a list of Delete instances, configure them, and call the following method: void delete(List<Delete> deletes) throws IOException There is an equivalent call for deletes that gives you access to server-side, read-and-modify functionality: boolean checkAndDelete(byte[] row, byte[] family, byte[] qualifier, byte[] value, Delete delete) throws IOException You need to specify the row key, column family, qualifier, and value to check before the actual delete operation is performed. Should the test fail, nothing is deleted and the call returns a false. If the check is successful, the delete is applied and true is returned. Example:. Application deleting data from HBase Delete delete = new Delete(Bytes.toBytes("row1")); 1. delete.setTimestamp(1); 2. delete.deleteColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1"), 1); 3. delete.deleteColumns(Bytes.toBytes("colfam2"), Bytes.toBytes("qual1")); 4. delete.deleteColumns(Bytes.toBytes("colfam2"), Bytes.toBytes("qual3"), 15); 5. delete.deleteFamily(Bytes.toBytes("colfam3")); 6. delete.deleteFamily(Bytes.toBytes("colfam3"), 3); 7. table.delete(delete); 8. table.close(); 5.1.4 Row Locks Mutating operations—like put(), delete(), checkAndPut(), and so on—are executed exclusively, which means in a serial fashion, for each row, to guarantee row-level atomicity. The region servers provide a row lock feature ensuring that only a client holding the matching lock can modify a row. In practice, though, most client applications do not provide an explicit lock, but rather rely on the mechanism in place that guards each operation separately. When you send, for example, a put() call to the server with an instance of Put, created with the following constructor: Put(byte[] row) Which is not providing a RowLock instance parameter, the servers will create a lock on your behalf, just for the duration of the call. In fact, from the client API you cannot even retrieve this short-lived, server-side lock instance. Learn more about Hbase in this insightful blog now! Course Schedule Leave a Reply Cancel reply Your email address will not be published. Required fields are marked * Comment Name * Browse Categories Bangalore Chennai Delhi Hyderabad London Sydney United States
https://intellipaat.com/blog/tutorial/hbase-tutorial/client-api-the-basics/
CC-MAIN-2022-21
refinedweb
1,327
50.87
Flashing a Windows CE 5.0 Device Without Using Platform Builder Rob Baynes Koko Fitness, Inc. April 2006 Applies to Windows CE 5.0 Summary: This article describes how to build a Windows CE Device that flashes without using Platform Builder. I work at a small startup, Koko Fitness, Inc., that builds fitness equipment. We built a custom Windows CE 5.0 device for our gym that uses a customized Windows CE operating system and drivers. We outsourced the manufacture and assembly of the device and we needed a simple way for an assembly line worker to flash the device without using Platform Builder. To run the code in this article, you will need the following bits installed on your machine: - Platform Builder with Windows CE 5.0 and your BSP (board support package) - Visual Studio 2005 with C# - A network analyzer, such as windump (which is free) These are the manual steps involved in flashing a custom CE device: 1. Connect a null modem serial cable from your PC to the devices serial port. Run the download program that comes with your BSP. Use it to program the MAC address and serial number into EEPROM. Typically it's used like this: a. Run:download -a 0016EF000001 -n C12303001 b. Hold down a boot switch and turn on the device. c. Turn the device off after downloading is complete. 2. Run the download program again to download the Ethernet boot loader. Typically it's used like this: a. Run:download EBOOT.nb0 b. Hold down a boot switch and turn on the device. c. Turn the device off after downloading is complete. 3. These are the steps to flash the image to the device: a. Connect an Ethernet cable to the device. b. Start Platform Builder and open your workspace project. c. Turn on the device. d. In Platform Builder, click Target, click Connectivity Options, and then click Settings. You should see your devices IP address (assigned by DHCP) under the Active Devices list. e. Click Target, and then click Attach Device, which will download the image and flash the device. f. Wait a few minutes for the flashing to complete then turn the device off and on to see your image boot. If I worked on an assembly line, I don't think I could do those steps a hundred times in a day without making a mistake. So I looked for a way to simplify the process. My first step was to figure out how Platform Builder discovered the device's IP address. I went back to my board and did step 1 above. Then I ran the network analyzer and looked for traffic from the board. I narrowed down the packets on my network, and saw some interesting UDP packets that were unicast to port 980. Here is a dump of a packet the Ethernet boot loader unicasts: windump -i 2 -X port 980 1 c. 4:01:25.525684 IP 192.168.1.107.980 > 255.255.255.255.980: UDP, length 64 0x0000: 4500 005c 0600 0000 4011 b27e c0a8 016b E..\....@..~...k 0x0010: ffff ffff 03d4 03d4 0048 bd19 4544 4247 .........H..EDBG 0x0020: ff01 0400 0100 0016 ef00 0001 c0a8 016b ...............k 0x0030: 4b6f 6b6f 2d43 3100 0000 0000 0000 0000 Koko-C1......... 0x0040: 004b 6f6b 6f2d 4331 3233 3033 3030 3100 .Koko-C12303001. 0x0050: 0000 .. Digging into the packet reveals the following data: From the information above, I can tell that Platform Builder must be listening for these UDP packets on port 980 to get the device's IP address. Now, how does Platform Builder download the CE operating system image to the device over Ethernet? For clues I looked at the Ethernet boot loader source code. If you navigate to where you installed the Windows CE 5.0 files (usually under the same directory where your platform builder project is), you should be able to find this: file: public\common\oak\ethdbg\eboot\ebsimp.c On about line 300, you will see a call to a function called EbootInitTftpSimple(…) which starts a TFTP server, but on a non-standard port (980). A few lines further down you can also see where the packet above is unicast. There is a t client that comes with Windows XP and later, but it operates on the standard port of 69. So, it's trivial to modify the call to the function to use port 69, instead of using the define EDBG_DOWNLOAD_PORT (which is 980). Here is the original code in ebsimp.c: if( !EbootInitTftpSimple( pEdbgAddr, htons( EDBG_DOWNLOAD_PORT ), htons( EDBG_DOWNLOAD_PORT ), EDBG_DOWNLOAD_FILENAME )) { return FALSE; } Here is my modified version: // rbaynes: change port EDBG_DOWNLOAD_PORT to 69, to allow // windows command line t to send us an image (also prevents // Platform Builder from sending image) if( !EbootInitTftpSimple( pEdbgAddr, htons(69), htons(69), EDBG_DOWNLOAD_FILENAME )) { return FALSE; } A few things to note: - I didn't change the port that the packet is unicast on (its still 980). All the above change does is make the TFTP server in the boot loader listen on the standard TFTP port of 69. - The TFTP server is waiting for a file named " boot.bin" (defined as EDBG_DOWNLOAD_FILENAME), it won't accept any other file names. So, you will have to rename the file that platform builder creates ( NK.bin) to " boot.bin." - You may want to save your old boot loader, in case you still want to download images to your device using Platform Builder. That is why I named the custom boot loader we created " EBOOT.nb0.tftp_port_69." Use Platform Builder to rebuild your project, which should also rebuild the boot loader. You can find the boot loader ( EBOOT.nb0) and Windows CE image ( NK.bin) in a similar directory when the build is complete: OS\PBWorkspaces\Koko\RelDir\ep93xx_ARMV4I_Release. Now that we know how everything works, it's time to write a simple-to-use application that will: - Run download.exe to program the MAC address and serial number, prompting the user to press the boot switch and turn the board power on and off. - Run download.exe to download our modified boot loader, prompting the user to press the boot switch and turn the board power on and off. - Prompt the user to turn the board on. - Capture the UDP packet that is unicast to port 980, and extract the IP address from it. - Run t to send the CE image to the boards IP address. In the screen shot, you can see what my application looks like. The two text fields are filled in using a scanner that the assembly line worker scans from a work order sheet for this device. In the output window at the bottom, you can see that the program did not find the three files it needs. The application prompts the user through the three steps. Screenshot of the customized Windows CE device UI I wrote the application above in C#. I'm only going to cover the difficult parts of the application, since writing Windows Forms applications is already well documented in MSDN. The difficult parts are capturing and decoding the UDP packet and spawning the processes which run the command line programs. This is the code I use to spawn a process and capture its output (I look at the output to see if the program worked): using System.Threading; try { // run: download -a 0016EF000001 -n C12303001 // expect: "Successfully programmed the Ethernet MAC address." Process p = new Process(); p.EnableRaisingEvents = false; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = downloadApp; p.StartInfo.Arguments = " -a " + MACadxBox.Text + " -n " + SNBox.Text; p.Start(); string stderr = p.StandardError.ReadToEnd(); string stdout = p.StandardOutput.ReadToEnd(); p.Close(); if( 0 > stdout.IndexOf( "successful", StringComparison.CurrentCultureIgnoreCase )) { MessageBox.Show( "Error: please review the messages and " + "try again." ); return; } } catch( Exception ex ) { Utils.Log( "Exception: " + ex.Message ); } Here is the complete listing for the class which captures and decodes the packet the boot loader sends: // copyright (c) 2006, Koko Fitness, Inc. // read the UDP BOOTME packet our Windows CE bootloader unicasts // to 255.255.255.255 port 980 using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using System.Net.Sockets; using System.Net; namespace Imager { class UDPclient { private int listenOnPort = 980; // port boot loader unicasts on private int messageCount = 1; // just read 1 packet private int listenWait = 60; private const int bufSize = 32 * 1024 - 40; private byte[] receiveBuffer1 = new byte[ bufSize ]; private int receivedBuffers = 0; private bool success = false; private string errorMsg = ""; private Socket socketA1 = null; EndPoint bindEndPointA1 = null; private string MAC_adx = ""; private string IP_adx = ""; private string board_name = ""; //------------------------------------------------------------- public bool Success { get { return success; } } public string ErrorMsg { get { return errorMsg; } } public string MAC { get { return MAC_adx; } } public string IP { get { return IP_adx; } } public string Name { get { return board_name; } } //------------------------------------------------------------- public UDPclient() { try { // init our buffer for( int i = 0; i < bufSize; i++ ) { receiveBuffer1[ i ] = 0; } AsyncCallback onReceiveFrom1 = new AsyncCallback( OnReceiveFrom ); if( null == socketA1 ) { socketA1 = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); bindEndPointA1 = new IPEndPoint( IPAddress.Any, listenOnPort ); // bind for listening to unicast. socketA1.Bind( bindEndPointA1 ); } // start listening ReceiveFromData rfd = new ReceiveFromData( ref receiveBuffer1, receiveBuffer1.Length, ref bindEndPointA1, ref onReceiveFrom1, ref socketA1, null ); rfd.BeginReceiveFrom(); WaitReceivedMessages( messageCount + 1 ); // clean up socketA1.Disconnect( true ); socketA1.Close(); } catch( Exception ex ) { errorMsg = "Exception: " + ex.ToString(); socketA1.Disconnect( true ); socketA1.Close(); } } ~UDPclient() { try { socketA1.Disconnect( true ); socketA1.Close(); } catch( Exception ) { } } //------------------------------------------------------------- private void OnReceiveFrom( IAsyncResult result ) { ReceiveFromData rfd = (ReceiveFromData) result.AsyncState; Socket receiveSocket = rfd.socket; EndPoint remoteEndPoint; remoteEndPoint = new IPEndPoint( 0, 0 ); // hack int bytesRead = 0; try { bytesRead = receiveSocket.EndReceiveFrom( result, ref remoteEndPoint ); } catch( SocketException e ) { errorMsg += "SocketException: " + e.ErrorCode; switch( e.ErrorCode ) { case 995: break; // thread terminated, expected default: errorMsg += "SocketException: " + e.ErrorCode + " " + e.ToString(); break; } } catch( Exception e ) { errorMsg += "Exception: " + e.ToString(); } // now see if this is the 64 byte packet we expect: // // description windump buffer data (hex) translated // ----------- ------------ ------- ----------- ---------- // packet name 0x1C to 0x1F 0 - 3 45444247 EDBG // MAC address 0x26 to 0x2B 10 - 15 0016ef000001 00-16-ef-00-00-01 // IP address 0x2C to 0x2F 16 - 19 c0a8016b 192.168.1.107 // board name 0x41 to 0x4E 37 - 50 4b6f6b6f2... Koko-C12303001 if( 64 == bytesRead && // expected packet size 0x45 == rfd.buffer[ 0 ] && // E 0x44 == rfd.buffer[ 1 ] && // D 0x42 == rfd.buffer[ 2 ] && // B 0x47 == rfd.buffer[ 3 ] ) { // G success = true; MAC_adx = ""; IP_adx = ""; board_name = ""; MAC_adx += System.Convert.ToInt32( rfd.buffer[ 10 ] ).ToString( "X2" )+ "-"; MAC_adx += System.Convert.ToInt32( rfd.buffer[ 11 ] ).ToString( "X2" )+ "-"; MAC_adx += System.Convert.ToInt32( rfd.buffer[ 12 ] ).ToString( "X2" )+ "-"; MAC_adx += System.Convert.ToInt32( rfd.buffer[ 13 ] ).ToString( "X2" )+ "-"; MAC_adx += System.Convert.ToInt32( rfd.buffer[ 14 ] ).ToString( "X2" )+ "-"; MAC_adx += System.Convert.ToInt32( rfd.buffer[ 15 ] ).ToString( "X2" ); MAC_adx += ""; IP_adx += System.Convert.ToInt32( rfd.buffer[ 16 ] ).ToString() + "."; IP_adx += System.Convert.ToInt32( rfd.buffer[ 17 ] ).ToString() + "."; IP_adx += System.Convert.ToInt32( rfd.buffer[ 18 ] ).ToString() + "."; IP_adx += System.Convert.ToInt32( rfd.buffer[ 19 ] ).ToString(); IP_adx += ""; board_name += System.Convert.ToChar( rfd.buffer[ 37 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 38 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 39 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 40 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 41 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 42 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 43 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 44 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 45 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 46 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 47 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 48 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 49 ] ); board_name += System.Convert.ToChar( rfd.buffer[ 50 ] ); board_name += ""; } else { // get another packet rfd.BeginReceiveFrom(); Interlocked.Increment( ref receivedBuffers ); } } //------------------------------------------------------------- private class ReceiveFromData { public AsyncCallback onReceiveFrom; public byte[] buffer; public int length; public EndPoint endPoint; public Socket socket; public Socket ForwardSocket; public ReceiveFromData( ref byte[] buffer, int length, ref EndPoint endPoint, ref AsyncCallback onReceiveFrom, ref Socket socket, Socket ForwardSocket ) { this.onReceiveFrom = onReceiveFrom; this.buffer = buffer; this.length = length; this.endPoint = endPoint; this.socket = socket; this.ForwardSocket = ForwardSocket; } public void BeginReceiveFrom() { socket.BeginReceiveFrom( buffer, 0, length, SocketFlags.None, ref endPoint, onReceiveFrom, (object) this ); } } //------------------------------------------------------------- private bool WaitReceivedMessages( int messages ) { for( int i = 0; i < listenWait * 10; i++ ) { Thread.Sleep( 100 ); if( receivedBuffers == messages ) break; } return ( receivedBuffers == messages ); } } }
http://msdn.microsoft.com/en-us/library/aa446908.aspx
CC-MAIN-2013-48
refinedweb
2,020
60.11
getting output without creating object ? Nipun Devlekar Greenhorn Joined: Dec 07, 2005 Posts: 9 posted Dec 19, 2005 01:35:00 0 I tried to execute the following code from SCJP book //Good.java public class Good{ Good (){ System.out.println("Constructor"); } void Bad(){ System.out.println("Method"); } public static void main(String[] args){ new Good().Bad(); } }? Can one write a method inside a constructor and execute it as we do it for object?I wrote the following code which reported the following errors //Good.java public class Good{ Good (){ System.out.println("Constructor"); void Bad(){ System.out.println("Method"); } } public static void main(String[] args){ new Good(); } } errors were devtest$ javac Good.java Good.java:5: '}' expected. System.out.println("Constructor"); ^ Good.java:7: Statement expected. void Bad() { ^ Good.java:14: Identifier expected. public static void main( String [] args) { ^ Good.java:14: 'class' or 'interface' keyword expected. public static void main(String[] args) { ^ 4 errors Can anyone solve my doubt Thanks in advance NIPUN. [ December 19, 2005: Message edited by: Nipun Devlekar ] Harshil Mehta Ranch Hand Joined: Mar 17, 2005 Posts: 64 posted Dec 19, 2005 02:10:00 0 Hi Nipun,? Object of class Good is created. There is nothing wrong in this code. Even from constructor it's legal to call any method, however it's not a good practice. Can one write a method inside a constructor and execute it as we do it for object?I wrote the following code which reported the following errors You can not declare or define any method inside a constructor. hth, Harshil Nipun Devlekar Greenhorn Joined: Dec 07, 2005 Posts: 9 posted Dec 19, 2005 06:16:00 0 looking at the code i posted earlier above; i tried to incorporate the coding technique in the following codes.Theere are 3 codes one is super class,one is subclass and one is mainline.I found that i am not able to execute a method of subclass eg new PrintableCharStack(10).input() but am able to do so for super class eg; new PrintableCharStack(10).getInstanceCount().following are the codes //CharStack.java //import java.util.*; public class CharStack { //fields public static char[]stackArray; public static inttopOfStack; public static intcounter; public static inti; //Constructor CharStack (int n){ stackArray = new char [n]; topOfStack = -1; counter++; System.out.println("Hi");//statements in constructor System.out.println(getInstanceCount());//method call in constructor //System.out.println(input()); } /;} public static int getInstanceCount(){System.out.println("gobaby");return counter;} } //PrintableCharStack.java /*public*/ class PrintableCharStack extends CharStack { /*by default everything is public*/ //fields public static int i; //method 1 public void printStackElements(){ for ( i = 0; i <= topOfStack; i++) System.out.println(stackArray[i]); } //method 2 public static int input(){ System.out.println("JAVA IS COMPLEX"); stackArray[1] = 'J'; stackArray[2] = 'A'; stackArray[3] = 'V'; stackArray[4] = 'A'; for ( i = 0; i <= topOfStack; i++) System.out.println(stackArray[i]); return 0; } //constructor PrintableCharStack(int capacity) { super(capacity); System.out.println(input()); } } //MainLinePrintable.java //import java.util.*; /*public*/ class MainLinePrintable { /*public*/ static void main(String[] args) { //CharStack stack1 = new CharStack(10); PrintableCharStack stack2 = new PrintableCharStack(10); stack2.push('N'); stack2.push('I'); stack2.push('P'); stack2.push('U'); stack2.push('N'); stack2.printStackElements();//will print Hi gobaby 1 NIPUN stack2.push('X'); stack2.printStackElements(); //stack2 = null; new PrintableCharStack(10).getInstanceCount();//constructor call followed by method call //will print Hi GOBABY 2 //WILL PRINT METHODS ONLY FROM CHARSTACK ONLY NOT //FORM PRINABLECHARSTACK!!! //method will only print gobaby bcos counter is not //under system.out.println new PrintableCharStack(10).input();//why is the method input() not executing here??? //stack2.printStackElements();//will print X //System.out.println(stack2.peek()); if ( stack2.isFull()) System.out.println("STACK IS FULL"); System.out.println("The number of objects are" + stack2.getInstanceCount());//will print //go baby //the number of objects are 2 } } I agree. Here's the link: subject: getting output without creating object ? Similar Threads Changing public static void main to public void static main , Is it Possible to execute the program? null reference to string objects Overloading doubt newbie question about method overloading need clarification on this code ! All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/401815/java/java/output-creating-object
CC-MAIN-2014-41
refinedweb
700
52.36
Wu Fengguang <wfg@mail.ustc.edu.cn> wrote:>> Define some helpers on struct file_ra_state.> > +/*> + * The 64bit cache_hits stores three accumulated values and a counter value.> + * MSB LSB> + * 3333333333333333 : 2222222222222222 : 1111111111111111 : 0000000000000000> + */> +static int ra_cache_hit(struct file_ra_state *ra, int nr)> +{> + return (ra->cache_hits >> (nr * 16)) & 0xFFFF;> +}So... why not use four u16s?> +/*> + * Submit IO for the read-ahead request in file_ra_state.> + */> +static int ra_dispatch(struct file_ra_state *ra,> + struct address_space *mapping, struct file *filp)> +{> + enum ra_class ra_class = ra_class_new(ra);> + unsigned long ra_size = ra_readahead_size(ra);> + unsigned long la_size = ra_lookahead_size(ra);> + pgoff_t eof_index = PAGES_BYTE(i_size_read(mapping->host)) + 1;Sigh. I guess one gets used to that PAGES_BYTE thing after a while. Ifyou're not familiar with it, it obfuscates things.<hunts around for its definition>So in fact it's converting a loff_t to a pgoff_t. Why not call itconvert_loff_t_to_pgoff_t()? ;)Something better, anyway. Something lower-case and an inline-not-a-macro, too.> + int actual;> +> + if (unlikely(ra->ra_index >= eof_index))> + return 0;> +> + /* Snap to EOF. */> + if (ra->readahead_index + ra_size / 2 > eof_index) {You've had a bit of a think and you've arrived at a design decisionsurrounding the arithmetic in here. It's very very hard to look at this lineof code and to work out why you decided to implement it in this fashion. The only way to make such code comprehensible (and hence maintainable) isto fully comment such things.-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/2006/5/26/283
CC-MAIN-2016-44
refinedweb
255
59.7
Choosing between different courses of action makes a program much more useful and flexible. Decision making constructs allow for many different logical branches of code to be incorporated into a single program. One of the fundamental properties of a programming language is the ability to repetitively execute a sequence of statements. These looping capabilities enable programmers to develop concise programs containing repetitive processes that could otherwise require an excessive number of statements. The if-else statement allows conditional execution of a group of statements. The general form of an if-else statement is if(expression) { statement-block-1; } else { statement-block-2; } where expression can be a combination of logical and relational operators and their operands, a function call, or a mathematical expression. If the expression is true, then statement-block-1 is executed otherwise statement-block-2 is executed. Only expressions evaluating to zero(0) are considered to be false in C and C++. Statements subordinate to if and else clauses can be compound statements; meaning several statements grouped together and bounded by opening and closing curly braces. It is recommended that subordinate statements be indented to indicate the subordination. Most programmers indent from three to five spaces, some use as many as eight spaces. It is also recommended that code not be placed after column seventy-two (72), this makes all the code on a line visible on the display and usually makes for a readable printout. A: if(x == y) a = b + c; B: if(c >= 10) { cout << "\nC is over 10"; ++a; } else { cout << "\nNot yet!"; c++; } Notice that the first example, A, does not use an else clause. The else clause is optional and is only used if needed. Also, note that curly braces are not used on example A because there is only a single statement subordinate to the if. if-else statements can be nested. There is no reasonable limit imposed by the compiler to the number of nested if-else statements, although there should be a practical limit. It is recommended that if nested if-else statements are used, that the nest not go over four deep. This limit is more a matter of readability and not anything imposed by the compiler. For example, the following shows nested if-else statements. Notice how quickly the code progresses toward the right edge of the display, even with short variable names. Also, this example has a major error in logic. See if you can find it. if( a > 10 ) if( b < 5 ) b = a * 10; else if( a < 5 ) if ( b > 10 ) b = a * b; else if( c > 5 && b == 10 ) if( c < 10 ) c = b * a; else c = a * c; In nested if-else statements, the else is associated with the nearest if, unless bracketed within curly braces which form a compound statement. The error in the above sample is at the very beginning where if( a > 10 ) if( b < 5 ) b = a * 10; else The else is associated by the compiler with the if( b < 5 ) statement not with if( a > 10 ). The intention of the programmer was to associate the else with if( a > 10 ). In order to accomplish the correct association, the code block should appear as if( a > 10 ) { if( b < 5 ) b = a * 10; } else Notice the use of the curly braces to limit the scope of the if( b < 5 ) statement. Many errors in logic occur because of incorrect else statement association. Use the curly braces if there is any doubt about how the compiler will associate if with else statements. The switch allows the conditional execution of one of a number of groups of statements based on the value of an expression. The general form of a switch statement is: switch( expression ) { case constant-value-1: statement-block-1; break; case constant-value-2: statement-block-2; break; . . . default: statement-block-n; break; } Where expression must produce an integer or character result and each of the constant values must be an integer or character value that could be a possible value of the expression. The expression in the switch statement is evaluated and compared to each of the case constant values in order. If a match is found, execution is started at that case statement. If no match is found, control is transferred to the default statement, if one has been coded. #include <iostream.h> ing main() { int day; cout << "\nEnter a number for" << "the day of the week:"; cin >> day; switch( day ) { case 0: cout << "Sunday"; break; case 1: cout << "Monday"); break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; default: cout << "No Such Day"; break; } return 0; } The break statement causes an immediate exit from the switch. Without the break, the execution will fall thru to the next case and will continue to fall thru until a break statement is reached. Sometimes the desired logic is to have multiple case statements cause one code block to be executed. For example, assume that the keyboard is being read and that when a newline character or a carriage return character is read a null byte is to placed at the end of an array of characters. #include <iostream.h> int main() { char buffer[80]; int ch, idx = 0, lgth = sizeof( buffer) -1; cout << "\nEnter a string of characters: "; while ( idx < lgth && ch != '\n' && ch != '\r' ) { cin >> ch; switch( ch ) { case '\n': case '\r': buffer[idx] = '\0'; break; case '\b': --idx; if( idx < 0 ) idx = 0; putchar( '\b' ); putchar( ' ' ); putchar( '\b' ); break; default: buffer[idx] = ch; ++idx; break; } } return 0; } The while loop allows for the repeated execution of a group of statements as long as a condition is true. The condition is checked each time before the code is executed. The general form of the loop construct is: while (expression) { statement-block; } If statement-block comprises a group of statements, then the group must be bracketed by opening and closing curly braces. The statement or group of statements inside the while loop will be executed until the expression is false The for loop is a specialized form of the while loop, which includes an initialization statement, a conditional expression and a third expression, referred to as the increment expression, which is executed at the end of the loop before control is transferred back to the conditional expression test at the loop beginning. The general form of the for loop is: for(init-expression; conditional-expression; increment-expression) { statement-block; } All three expressions composing the for loop are optional. The expressions can be any legal expression, function call, or mathematical statement. The statements are executed as follows: init-expression; loop: if conditional-expression is true begin statement-block; increment-expression end else exit the loop; end of loop: The following example prints the character set being used on the current machine. The program prints character, the ASCII value, the hexadecimal value and the octal value of the character. #include <iostream.h> #define MAX_LINES 23 int main() { char ans; int ch, lines, stop = 0, maxchars; // // how many characters in current character set // cout << "\nHow many characters in the character set: "; cin >> maxchars; // // print the ASCII and extended ASCII characters // for(ch = 0, lines = 0; ch < maxchars && !stop; ++ch) { cout << "\nCHAR: " << char( ch ) << " ASCII: " << ch << " HEX : " << hex << ch << " OCT : " << oct << ch ; if( ++lines > MAX_LINES ) { cout << "\nContinue(Y/N)?"; cin >> ans; if(ans == 'N' || ans == 'n') { stop = 1; break; } lines = 0; } } return 0; } This loop is like the while loop, except that the condition is checked after the loop is executed. The general form is as follows: do { statement-block; } while(expression); The statement or statement-block are executed at least once, even if the expression is false on the first test. The break terminates execution of a loop or switch-case and transfers execution to the first statement following the loop or the switch-case. If the break statement is within a loop that is nested within another loop, the break statement only exits the loop the holds the break statement, not the outer loop. The continue causes execution to pass to the end of the current loop. For example: C++ allows declarations within blocks after code statements. This allows a programmer to declare an entity closer to its first point of application. For example, an index can be declared within a loop, as follows: for( int i = 0; i < 12; i++ ) The new operator :: is used to resolve name conflicts. For example, if the automatic variable vector_sum is declared within a function and there exists a global variable vector_sum, the specifier ::vector_sum allows the global variable to be accessed within the scope of the automatic variable vector_sum. The reverse is not true. It is not possible for the automatic variable vector_sum to be accessed from outside its scope. The scope qualifier :: is also used in connection with classes. // **::** scope resolution operator example int i = 1; // external or global i #include <iostream.h> int main() { int i = 2; // redeclares i locally to main { // an inner block within a function cout << "Enter inner block" << endl; int n = i; // the global i is still visible int i = 3; // hides the global i which can only be // referenced by using the :: operator // print the local i and the global i cout << i << " i << ::i " << ::i << endl; cout << "n = " << n << endl; } // end of inner block cout << "Enter outer block" << endl; // print the current local i and the global i cout << i << " i ** ::i " << ::i << endl; return 0; } ** The output of this code is: Each identifier or name has a scope that indicates the region of the program where that identifier can be used. C++ supports the notion of the following types of scope: #. Local: Names appearing inside a block statement (enclosed in a pair of curly braces {...}) have local scope. You can use these only within that block and only after the actual declaration. Note that you cannot define a function in a local scope. (This means you cannot define one function inside the body of another.) #. File: Names appearing outside all blocks and class declarations have file scope. These can be used within that file anywhere after the point where they are declared. #. Class: Names of data and function members of a class (or struct) have class scope.
https://docs.aakashlabs.org/apl/cphelp/chap05.html
CC-MAIN-2020-45
refinedweb
1,723
57.1
Объект "Part::Feature" Вступление A Part Feature object, or formally a Part::Feature, is a simple element with a topological shape that can be displayed in the 3D view. The Part Feature is the parent class of most 2D (Draft, Sketcher) and 3D (Part, PartDesign) objects, with the exception of meshes, which are normally based on the Mesh Feature, or the FEM FemMeshObject for FEM objects. Simplified diagram of the relationships between the core objects in FreeCAD Применение The Part Feature is an internal object, so it cannot be created from the graphical interface, only from the Python console as described in the Scripting section. The Part::Feature is defined in the Part Workbench but can be used as the base class for scripted objects in all workbenches that produce 2D and 3D geometrical shapes. Essentially all objects produced in the Part Workbench are instances of a Part::Feature. Part::Feature is also the parent class of the PartDesign Body, of the PartDesign Features, and of the Part Part2DObject, which is specialized for 2D (planar) shapes. Workbenches can add more properties to this basic element to produce an object with complex behavior. Свойства See Property for all property types that scripted objects can have. The Part Feature ( Part::Feature class) is derived from the basic App GeoFeature ( App::GeoFeature class) and inherits all its properties. It also has several additional properties. Notably a ДанныеShape property, which stores the Part TopoShape of the object. This is the geometry that is shown in the 3D view. Other properties that this object has are those related to the appearance of its TopoShape. These are the properties available in the property editor. Hidden properties can be shown by using the Show all command in the context menu of the property editor. Данные Base - Данные (Hidden)Proxy ( PythonObject): a custom class associated with this object. This only exists for the Python version. See Scripting. - Данные (Hidden)Shape ( PartShape): a Part TopoShape class associated with this object. - ДанныеPlacement ( Placement): the position of the object in the 3D view. The placement is defined by a Basepoint (vector), and a Rotation(axis and angle). See Placement. - ДанныеAngle: the angle of rotation around the ДанныеAxis. By default, it is 0°(zero degrees). - ДанныеAxis: the unit vector that defines the axis of rotation for the placement. Each component is a floating point value between 0and 1. If any value is above 1, the vector is normalized so that the magnitude of the vector is 1. By default, it is the positive Z axis, (0, 0, 1). - ДанныеPosition: a vector with the 3D coordinates of the base point. By default, it is the origin (0, 0, 0). - ДанныеLabel ( String): the user editable name of this object, it is an arbitrary UTF8 string. - Данные (Hidden)Label2 ( String): a longer, user editable description of this object, it is an arbitrary UTF8 string that may include newlines. By default, it is an empty string "". - Данные (Hidden)Expression Engine ( ExpressionEngine): a list of expressions. By default, it is empty []. - Данные (Hidden)Visibility ( Bool): whether to display the object or not. View Most objects in FreeCAD have what is called a "viewprovider", which is a class that defines the visual appearance of the object in the 3D view, and in the Tree view. The default viewprovider of Part Feature objects defines the following properties. Scripted objects that are derived from Part Feature will have access to these properties as well. Base - Вид (hidden)Proxy ( PythonObject): a custom viewprovider class associated with this object. This only exists for the Python version. See Scripting. Display Options - ВидBounding Box ( Bool): if it is true, the object will show the bounding box in the 3D view. - ВидDisplay Mode ( Enumeration): Flat Lines(regular visualization), Shaded(no edges), Wireframe(no faces), Points(only vertices). - ВидShow In Tree ( Bool): it defaults to true, in which case the object will appear in the Tree view; otherwise, the object will be hidden in the tree view. Once an object in the tree is invisible, you can see it again by opening the context menu over the name of the document (right-click), and selecting Show hidden items. Then the hidden item can be chosen and ВидShow In Tree can be switched back to true. - ВидVisibility ( Bool): if it is true, the object appears in the 3D view; otherwise it is invisible. By default this property can be toggled on and off by pressing the Space bar. Object style - ВидAngular Deflection ( Angle): it is a companion to ВидDeviation. It is another way to specify how finely to generate the mesh for rendering on screen or when exporting. The default value is 28.5 degrees, or 0.5 radians. This is the maximum value, the smaller the value the smoother the appearance will be in the 3D view, and the finer the mesh that will be exported. - ВидDeviation ( FloatConstraint): it is a companion to ВидAngular Deflection. It is another way to specify how finely to generate the mesh for rendering on screen or when exporting. The default value is 0.5%. This is the maximum value, the smaller the value the smoother the appearance will be in the 3D view, and the finer the mesh that will be exported. - Вид (hidden)Diffuse Color ( ColorList): it is a list of RGB tuples defining colors, similar to ВидShape Color. It defaults to a list of one [(0.8, 0.8, 0.8)]. - ВидDraw Style ( Enumeration): Solid(default), Dashed, Dotted, Dashdot; defines the style of the edges in the 3D view. - ВидLighting ( Enumeration): Two side(default), One side; the illumination comes from two sides or one side in the 3D view. - ВидLine Color ( Color): a tuple of three floating point RGB values (r,g,b)to define the color of the edges in the 3D view; by default it is (0.09, 0.09, 0.09), which is displayed as [25,25,25]on base 255, almost black . - Вид (hidden)Line Color Array ( ColorList): it is a list of RGB tuples defining colors, similar to ВидLine Color. It defaults to a list of one [(0.09, 0.09, 0.09)]. - Вид (hidden)Line Material ( Material): an App Material associated with the edges in this object. By default it is empty. - ВидLine Width ( FloatConstraint): a float that determines the width in pixels of the edges in the 3D view. It defaults to 2.0. - ВидPoint Color ( Color): similar to ВидLine Color, defines the color of the vertices. - Вид (hidden)Point Color Array ( ColorList): it is a list of RGB tuples defining colors, similar to ВидPoint Color. It defaults to a list of one [(0.09, 0.09, 0.09)]. - Вид (hidden)Point Material ( Material): an App Material associated with the vertices in this object. By default it is empty. - ВидPoint Size ( FloatConstraint): similar to ВидLine Width, defines the size of the vertices. - ВидShape Color ( Color): similar to ВидLine Color, defines the color of the faces. It defaults to (0.8, 0.8, 0.8), which is displayed as [204, 204, 204]on base 255, a light gray. - Вид (hidden)Shape Material ( Material): an App Material associated with this object. By default it is empty. - ВидTransparency ( Percent): an integer from 0to 100(a percentage) that determines the level of transparency of the faces in the 3D view. A value of 100indicates completely invisible faces; the faces are invisible but they can still be picked as long as ВидSelectable is true. Selection - ВидOn Top When Selected ( Enumeration): it controls the way in which the selection occurs in the 3D view if the object has a Shape, and there are many objects partially covered by others. It defaults to Disabled, meaning that no special highlighting will occur; Enabledmeans that the object will appear on top of any other object when selected; Objectmeans that the object will appear on top only if the entire object is selected in the Tree view; Elementmeans that the object will appear on top only if a subelement (vertex, edge, face) is selected in the 3D view. - ВидSelectable ( Bool): if it is true, the object can be picked with the pointer in the 3D view. Otherwise, the object cannot be selected until this option is set to true. - ВидSelection Style ( Enumeration): it controls the way the object is highlighted. If it is Shape, the entire shape (vertices, edges, and faces) will be highlighted in the 3D view; if it is BoundBoxa bounding box will appear surrounding the object and will be highlighted. Angular deflection and deviation Angular Deflection and deviation parameters; d < linear deflection, α < angular deflection. The deviation is a value in percentage that is related to the dimensions in millimeters of the bounding box of the object. The deviation in millimeters can be calculated as follows: deviation_in_mm = (w + h + d)/3 * deviation/100 where w, h, d are the bounding box dimensions. Scripting See also: FreeCAD Scripting Basics and scripted objects. A Part Feature is created with the addObject() method of the document. import FreeCAD as App doc = App.newDocument() obj = App.ActiveDocument.addObject("Part::Feature", "Name") obj.Label = "Custom label" For Python subclassing, you should create a Part::FeaturePython object. import FreeCAD as App doc = App.newDocument() obj = App.ActiveDocument.addObject("Part::FeaturePython", "Name") obj.Label = "Custom label" Name See also: Object name for more information on the properties of the Name. The addObject method has two basic string arguments. - The first argument indicates the type of object, in this case, "Part::FeaturePython". - The second argument is a string that defines the Nameattribute. If it is not provided, it defaults to the same name as the class, that is, "Part__FeaturePython". The Namecan only include simple alphanumeric characters, and the underscore, [_0-9a-zA-Z]. If other symbols are given, these will be converted to underscores; for example, "A+B:C*"is converted to "A_B_C_". Label If desired, the Label attribute can be changed to a more meaningful text. - The Labelcan accept any UTF8 string, including accents and spaces. Since the Tree view displays the Label, it is a good practice to change the Labelto a more descriptive string. - By default the Labelis unique, just like the Name. However, this behavior can be changed in the preferences editor, Edit → Preferences → General → Document → Allow duplicate object labels in one document. This means that in general the Labelmay be repeated in the same document; when testing for a specific element the user should rely on the Namerather than on the Label. - Ядро: App DocumentObject - Базовые: App FeaturePython, App GeoFeature, Part Feature, Mesh Feature, Fem FemMeshObject - Внутренние формы: Part TopoShape, Mesh MeshObject, Fem FemMesh - Структура: App DocumentObjectGroup (Std Group), App Part (Std Part), App Link - Производное: Part Part2DObject, Sketcher SketchObject, PartDesign Body, PartDesign Feature -
https://wiki.freecadweb.org/index.php?title=Part_Feature/ru&oldid=1103335
CC-MAIN-2022-33
refinedweb
1,783
56.05
Especifications: - Server: Weblogic 9.2 fixed by customer. - Webservices defined by wsdl and xsd files fixed by customer; not modifications allowed. Hi, In the project we need to develope a mail system. This must ... I am facing this problem for over than one month , so i would be realy pleased by your help , in fact i am asking about a way that can ... Am using an implementation of MessageBodyWriter to marshall all my objects to a file(XML). MessageBodyWriter @XmlRootElement(name="root") @XmlAccessorType( XmlAccessType.FIELD ) class Myclass implements MyInterface{ // some private fields } interface MyInterface{ //some methods } List<MyClass> This has been a thorn in my side for the last 2 days. We have a Ear and EJB project that uses xml/xsd to configure our beans, but for some reason we are getting errors when we try to unmarshall our xml. Here is the error: DefaultValidationEventHandler: [FATAL_ERROR]: unexpected element (uri:"", local:"appConfiguration"). Expected elements are <{}appConfiguration> Location: line 12 The log ... Iam using JAXB1.6 to convert the below xml to java object. After unmarshalling when I print the contents for ErrorMsg element, JAXB doesn't do any conversion for & and the character mentioned in ENTITY in the xml. It just prints as such what is in the xml. Where as i need the output as like " Inhalt des Feldes ung >ig ... Hi all, I'm trying to unmarshal an xml schema. I used the tool XJCFacade provided under JaxB package com.sun.tools.xjc. After running the tool the autogenerated classes wont havesetters methods to corresponding properties. My question is how am I supposed to set properties in respective instances of those autogenereated classes. Should i add my own setter method or is there any other ... If I got your probelm correctly , you have changed the package name of the classes generated by your wsdl-2-java tool and you are getting a binding error while running the service. Generated class's package name is mapped to the namespace in the wsdl schema by default. So if you change the package name, those mappings will won't work. I think ...
http://www.java2s.com/Questions_And_Answers/Java-Enterprise/jaxb/marshall.htm
CC-MAIN-2018-39
refinedweb
351
57.37
> Maybe Scott is interested in the sitemap generation stylesheet? I want to stress that I'm very interested in doing whatever it takes over the next couple of weeks to get Xalan 2 running well in Cocoon 2. You should write a note to me directly for any issues. You might try prepending something like [xalan2-cocoon2] to email subject lines to make sure I don't miss the mail. I will try and be extra responsive. As I said in the other note, sitemap.xsl should be working by tomorrow, once I address the extensions issue. -scott Giacomo Pati <Giacomo.Pati To: cocoon-dev@xml.apache.org @pwr.ch> cc: (bcc: Scott Boag/CAM/Lotus) Sent by: Subject: Re: C2 status giacomo@lotus .com 07/29/2000 03:41 PM Please respond to cocoon-dev "N. Sean Timm" wrote: > > "Giacomo Pati" <Giacomo.Pati@pwr.ch> wrote: > > Sean Timm will try to get Xalan 2.0 working with this release (trax). I > > personaly had no luck with Xalan 2.0 transforming a sitemap to java code > > using the stylesheet I've written > > > (src/org/apache/cocoon/components/language/markup/sitemap/java/sitemap.xsl). > > Yes...unfortunately, the current version of Xalan 2 doesn't seem to work at > all converting that sitemap, so I can't test any of my code changes until > that starts working. I fired a message off to Scott to see if I could get > some assistance on the Xalan end of things. I believe the changes I've made > are correct, however, so it should be good to go as soon as we can get Xalan > usable. I haven't created the TraxTransformer yet, but I've modified the > necessary files to make Cocoon2 use (and compile with) Xalan 2. DOMUtils > has been modified to utilize JAXP and TRaX, so there isn't a hard-coded > dependency on Xerces and Xalan anymore. (Although Xalan is currently the > only TRaX implementation that I know of...) To make C2 using Xalan 2 at all the sitemap generation stylesheet should be the test case for it. It uses the java namespace for XSLT extensions and this must be working. Until then C2 will remain on Xalan 1.x because I think we can't mix these Xalan versions. Maybe Scott is interested in the sitemap generation styles:
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200007.mbox/%3COF8F6FB38C.EDB20A7D-ON8525692C.007B462D@lotus.com%3E
CC-MAIN-2016-22
refinedweb
388
66.94
Creating PHP Classes. Do one of the following: Choose PHP Class. The Create New PHP Class dialog opens. In the Name field, type the name of the class to be created. PhpStorm automatically fills in the specified name in the File name field. Additionally, PhpStorm sets the Template value automatically in case the provided class name follows the standard convention (that is, NameClassfor classes, NameInterfacefor interfaces, and NameTraitfor traits). Specify the namespace to create the class in. By default, the Namespace field shows the namespace that corresponds to the folder from which the class creation was invoked. You can choose <global namespace> from the list, specify the template from which to create the file. The available options are as follows: The set of PhpStorm bundled templates: Your own set of manually created file templates having the PHP file extension. To set such a template as a default, select the Use as a default template checkbox. The default template will be selected automatically the next time you invoke the creation of a new class. Refer to File templates for details. Choose the file extension from the list. If you are creating a class or an interface, optionally choose the parent classes for it in the Parent classes area. In the Extends field, type the name of the parent class that the current class extends. To use code completion, press Ctrl+Space. In the Implements area, choose the interfaces that the created class implements (or the created interface extends): To add an interface, click or press Alt+Insert. In the Choose Class dialog that opens, search for the desired interface either by name or by using the project tree view. To remove an interface, click or press Delete. When you click OK, a new class is created according to the selected template, with the specified namespace declaration added automatically.
https://www.jetbrains.com/help/phpstorm/creating-php-classes.html
CC-MAIN-2022-21
refinedweb
307
65.22
2017 update A lot has changed in the world of JavaScript and D3 since this post was written. Check out the d3fc project to see what some of the ideas in this post have evolved into! An open-high-low-close (OHLC) chart is a type of financial chart used to show price movements and help identify trends in a financial instrument over time. For each unit of time, a vertical line is plotted showing the highest and lowest prices reached in that time. Horizontal tick marks are plotted on each side of the line - the opening price for that time period on the left, and the closing price on the right. Usually an OHLC line will be coloured green if on that day the closing price exceeded the opening price (an ‘up day’), and coloured red if not (a ‘down day’). D3 is a JavaScript library for data visualisation on the web. It is not a charting library. Instead, it gives us the flexibility to bind data to web graphics, utilising modern web standards such as SVG, HTML5 and CSS3. Charts are just one type of visualisation we can make with it. This post assumes some familiarity with D3. There are already lots of great introductory tutorials available on the D3 wiki if you need to get up to speed. While D3 does have a component to draw a line series on a chart (see here), it does not have an inbuilt component we can use to render an OHLC series. In this post, we’ll make one. Reusable Chart Components We’ll use D3 creator Mike Bostock’s convention for creating reusable components in D3. Essentially this means our component will be a closure with getter-setter methods. This follows the same pattern used by other D3 components and plugins, so will allow us to treat our OHLC component just like any other D3 component. We’ll assume our data is an array of objects that look like this: { date: // A Date object open: // A Number high: // A Number low: // A Number close: // A Number } Here’s what the OHLC component will look like internally: sl.series.ohlc = function () { var xScale = d3.time.scale(), yScale = d3.scale.linear(); var ohlc = function (selection) { selection.each(function (data) { // Generate ohlc bars here. }); }; ohlc.xScale = function (value) { if (!arguments.length) { return xScale; } xScale = value; return ohlc; }; ohlc.yScale = function (value) { // Similar to xScale above. }; return ohlc; }; Here, we are attaching our component to the sl.series namespace object. This gives us a nice way to organise the components we write. For example, if we were to implement an axis component, it could go in sl.axis. Internally, we have 2 scales, xScale and yScale. We’ll need these to map the dates and prices of our input to pixel positions on our chart. The scales are initialised to be default D3 scales. This allows us to use the component without attaching scales, although typically we’ll set them to the scales used by our axes. These scales are exposed to users of the component using getter/setter functions. For example, calling the xScale function with no arguments returns the internal xScale, and calling it with one or more arguments sets the internal xScale to the first argument. When called with arguments, these functions return the OHLC function. This allows setter calls to be chained together. We’ll draw the OHLC bars in the ohlc function returned by the component. We’ll use D3’s General Update Pattern. This is an important D3 concept. In simple terms, we select page elements that may or may not exist, and bind data to these elements. Page elements are then created, updated or removed as necessary to reflect the data. Creation happens in the enter() selection, updating in the update selection, and removal in the exit() selection. This is nice because we can use the same function to both create and update our component to reflect changes in the bound data or in configuration. To use an instance of the component, we’ll set an xScale and a yScale, bind data to a selection, then call the component on the selection. This will draw the series on the selection. This is how we’ll use our component when we come to drawing the chart. // Create series and bind x and y scales var series = sl.series.ohlc() .xScale(xScale) .yScale(yScale); // Bind data to a selection and call the series. d3.select('.series') .datum(data) .call(series); OHLC Component Let’s go ahead and implement the ohlc create/update function. First we need an SVG group element to contain our series on the selection. We’ll use the general update pattern. We want just one element to be created, so we’ll bind the whole array of data to the ‘ohlc-series’ element. Now we can create this element in the enter() selection. var ohlc = function (selection) { selection.each(function (data) { // Generate ohlc bars here. series = d3.select(this).selectAll('.ohlc-series').data([data]); series.enter().append('g').classed('ohlc-series', true); //... }); }; Next we need a group for each OHLC bar of our series. We will select all the elements with class ‘bar’ and bind a price object to each one. This time, we’ll also include a key function which returns the price object’s date. While not really necessary for this example, if we wanted to use D3’s transitions to animate updates to the data, this would ensure that D3 can match up existing bars with their new data, making for smooth animation. This idea is called Object Constancy. With the series data bound, we can create the bar groups in the enter() selection. In the update selection, we will give them a the css class ‘up-day’ or ‘down-day’ depending on the difference in opening and closing price. This means that we will be able to give colours to the up-day and down-day bars with CSS. //... bars = series.selectAll('.bar') .data(data, function (d) { return d.date; }); bars.enter() .append('g') .classed('bar', true); bars.classed({ 'up-day': function(d) { return d.close > d.open; }, 'down-day': function (d) { return d.close <= d.open; } }); bars.exit().remove(); All that’s left to do is to draw the lines inside each bar. We need to draw 3 lines for each bar - one extending from the low price to the high price, and 2 horizontal ticks for the open and closing prices. First, in the body of sl.series.ohlc, we will set up a d3.svg.line with appropriate x and y accessors. This means that we will be able to generate svg lines by supplying line with an array of points. var line = d3.svg.line() .x(function (d) { return d.x; }) .y(function (d) { return d.y; }); For each line, we’ll select a path element by its class and then append a path element in the enter() selection. The enter() selection is returned by binding data using selection.data, but what data should we bind? In this case we want to bind the price object that’s already bound to the the parent bar group element. It turns out that for this type of multiple selection we need to give a function to selection.data which returns an array containing the elements to bind (see here). In the update selection, we will draw the line, scaling all x and y coordinates with the xScale and yScale respectively. We’ll put the high low line create/update code in a function of its own which we will call from the OHLC create/update function. It looks like this: var highLowLines = function (bars) { var paths = bars .selectAll('.high-low-line') .data(function (d) { return [d]; }); paths.enter().append('path'); paths.classed('high-low-line', true) .attr('d', function (d) { return line([ { x: xScale(d.date), y: yScale(d.high) }, { x: xScale(d.date), y: yScale(d.low) } ]); }); }; It’s a similar situation for drawing the the open/close ticks: var openCloseTicks = function (bars) { var open, close, tickWidth = 5; open = bars.selectAll('.open-tick').data(function (d) { return [d]; }); close = bars.selectAll('.close-tick').data(function (d) { return [d]; }); open.enter().append('path'); close.enter().append('path'); open.classed('open-tick', true) .attr('d', function (d) { return line([ { x: xScale(d.date) - tickWidth, y: yScale(d.open) }, { x: xScale(d.date), y: yScale(d.open) } ]); }); close.classed('close-tick', true) .attr('d', function (d) { return line([ { x: xScale(d.date), y: yScale(d.close) }, { x: xScale(d.date) + tickWidth, y: yScale(d.close) } ]); }); }; OHLC Chart We’ve built the component, so now let’s use it in a chart! First we’ll set up margins, scales, axes and our series. var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 660 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; var xScale = d3.time.scale(), yScale = d3.scale.linear(); var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom') .ticks(5); var yAxis = d3.svg.axis() .scale(yScale) .orient('left'); var series = sl.series.ohlc() .xScale(xScale) .yScale(yScale); Next, we will create an svg element. We’ll assume that our html page has a div with id ‘chart’ to draw this inside. Following the usual D3 margin convention, we’ll draw our chart in a group element that translates the origin to the top left corner of the chart area. Our series will be drawn in the ‘plotArea’ - a group element which references a clipPath. The clipPath contains a rect with dimensions equal to the inner dimensions of our chart. This will ensure that OHLC bars for dates that lie outside domain of the axes are not shown. // Create svg element var svg = d3.select('#chart').classed('chart', true).append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom); // Create chart var g = svg.append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Create plot area var plotArea = g.append('g'); plotArea.append('clipPath') .attr('id', 'plotAreaClip') .append('rect') .attr({ width: width, height: height }); plotArea.attr('clip-path', 'url(#plotAreaClip)'); Next, we set the domains and ranges of the scales. For this example, we’ll have the x domain extend to a day after the most recent data point from about 1 month before the most recent data point. The y domain will extend from the lowest ‘low’ to the highest ‘high’ in our data. // Set scale domains var maxDate = d3.max(data, function (d) { return d.date; }); // There are 8.64e7 milliseconds in a day. xScale.domain([ new Date(maxDate.getTime() - (8.64e7 * 31.5)), new Date(maxDate.getTime() + 8.64e7) ]); yScale.domain( [ d3.min(data, function (d) { return d.low; }), d3.max(data, function (d) { return d.high; }) ] ).nice(); // Set scale ranges xScale.range([0, width]); yScale.range([height, 0]); Finally, we can draw the axes and the series. // Draw axes g.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height + ')') .call(xAxis); g.append('g') .attr('class', 'y axis') .call(yAxis); // Draw the series. plotArea.append('g') .attr('class', 'series') .datum(data) .call(series); We’ll colour the up-day and down-day bars with css by styling the stroke property of the paths: .chart .bar.up-day path { stroke: green; } .chart .bar.down-day path { stroke: red; } Here’s the end result: Candlestick Component Candlestick charts are very similar to OHLC charts, so with a small modification we can turn our OHLC component into a candlestick component. All that’s needed is to draw a rectangle between the open and close price instead of the open close ticks. The rectangle create/update function looks like this: var rectangles = function (bars) { var rect, rectangleWidth = 5; rect = bars.selectAll('rect').data(function (d) { return [d]; }); rect.enter().append('rect'); rect.attr('x', function (d) { return xScale(d.date) - rectangleWidth; }) .attr('y', function (d) { return isUpDay(d) ? yScale(d.close) : yScale(d.open); }) .attr('width', rectangleWidth * 2) .attr('height', function (d) { return isUpDay(d) ? yScale(d.open) - yScale(d.close) : yScale(d.close) - yScale(d.open); }); }; We’ll need to style the fill property of the rectangles to get the right colours. The sl.series.candlestick component is identical to the sl.series.ohlc component, but its create/update function calls rectangle instead of openCloseTicks. Since the components share a lot of code, we could have a function which contains the common code, takes rectangle or openCloseTicks as input, and produces the required component (we’ll leave out the details for now). We can use the same code we used to create the OHLC chart. We just have to replace sl.series.ohlc with sl.series.candlestick when creating the series. Here’s what our candlestick chart looks like: Conclusion We have made 2 reusable components for financial charts with D3. This is really just the beginning of what we would need for a fully featured financial chart. There are many components we could make using this pattern, including technical studies, comparison series and chart navigators. However, with these simple examples, we can already see the power of breaking chart features into reusable components. It would also be important to see how well these charts perform for large data sets. Ideally, we should be able to smoothly pan and zoom an OHLC chart which shows multiple years of prices. We’ll look at that in another post, where we’ll improve our OHLC component so that it is optimised for panning and zooming.
https://blog.scottlogic.com/2014/08/19/an-ohlc-chart-component-for-d3.html
CC-MAIN-2022-33
refinedweb
2,255
68.16
A simple package for parsing function arguments from the command line Project description ParseArgs A simple, intuitive way to parse command line arguments. Simply make a function, and call parseargs on it. - parses data types through annoations (annotations not required for string arguments) - parses optional keyword arguments by adding them as optional cli arguments - parses positional arguments in a variable called arglist (so don't use that as a keyword!) - adds a description of the command by using the signature of the method. Example in fun.py: from parseargs import parseargs def fun(firstname, lastname:str, number:int = 5): print(f"Hello {firstname} {lastname}") print(f"Your number is {number}") number *= 2 print(f"Twice your number is {number}") parseargs(fun) Now on the command line, you can do: $ python fun.py ricky bobby --number 5 Notice how it will print out 10. If you remove the annotation declaring the number an int, it will instead print out 55, because it will interpret it as a string. We can get the method signature with: $ python fun.py -h usage: test2.py [-h] [--number NUMBER] arglist arglist signature = (firstname, lastname: str, number: int = 5) positional arguments: arglist optional arguments: -h, --help show this help message and exit --number NUMBER 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/parseargs/
CC-MAIN-2020-05
refinedweb
235
52.9
In a typical scenario, threat actors try to gather as much information as possible (such as sensitive documents like credit card numbers, SSN details, and passwords stored in unprotected text files, etc.) about their targets after a successful exfiltration. It is possible to detect such malicious attempts by deploying file decoys or baits on endpoints or emails. If an attacker tries to access such a decoy, an alert is triggered and logged into a centralized system. In this document, we will be getting our hands dirty on creating the decoys using readily available tools at our disposal (PS: no macros). This document will cover the following: - How the decoys work - Creating image beacons for decoys using Python - Creating file decoys and setting up unique identifiers - Monitoring malicious attempts Perquisites: Python 2.x, Apache server, MS Office Suite Let’s get started! 1. File Decoys – Understanding the Background So, to understand the working of file decoys, first, we need to understand how HTTP works. Below is a basic HTTP request and response model: Below is the workflow describing how the decoys work. In case of an HTTP request/response mode, a web-browser initiates a request for certain content. The web server locates the requested content and serves it as a part of response back to the browser. The browser then interprets the content and finally renders it. Initially, when the request reaches the web server, a log entry is made in the logs (e.g., access.log) depicting the origin, user-agent, timestamp, etc. Similarly, in case of the workflow for decoys, a similar approach is followed. A word document is embedded with a linked image which is stored on the web server. Whenever the document is accessed/opened; the document tries to load the image from the remote location (i.e., web server), this, in turn, sends an HTTP request to the server. The server looks up for the image and delivers it to be embedded into the document. A log entry is created for this inbound request as well. In a real scenario, an adversary will try to get sensitive data from a system. A decoy will be placed with a lucrative name such as password-list.docx within the directory. Once the adversary tries to open the file, a request will be fired to the web server, and a log entry will be generated depicting that someone has infiltrated the system and is trying to steal away sensitive information. 2. Creating Image Beacons Using Python Let’s create an image beacon which will be linked in our decoys. The beacon will be 1×1 pixel by size with full transparency. Due to the miniature size of the pixel, it would not be easily spotted by the naked eye once the decoys are opened. We will use python along with Python Image Library (PIL) module to generate a beacon: from PIL import Image img = Image.new(‘RGBA’, (1,1), (0,0,0,0)) img.save(‘beacon.gif’, “GIF”, transparency=0) This will create an image file beacon.gif. Save this file in the /var/www/ directory of your Linux web server. Now on the Linux box, start the apache service (service apache2 start) and check if the default page appears in the browser (). Mobile Device Penetration Testing 3. Creating File Decoys and Setting Up Unique Identifiers Once the beacon is ready, we need to embed the remotely deployed beacon into the office document file. Following steps will walk you through linking beacons for MS Word 2013. Step 1. Open a word document > Click Insert Step 2. Select Quick Parts > Click Field… Step 3. Select IncludePicture and enter the path for beacon > Check Data not stored with Document Step 4. Click Okay. In an organization where file decoys need to be placed at multiple endpoints like the CEO’s computer, the CFO’s laptop, etc. it can become tedious to identify the source of the attack just based on the IP address of the system. To overcome this shortcoming, we can append unique identifiers to the URL path for the beacon in Step 3. Let’s assume we need to add two systems – CEO’s desktop and the Head of Marketing’s laptop; we will introduce distinct identifiers in the URL path by including pseudo parameters. - CEO’s desktop http://<server-IP>/beacon.gif?Pos=CEO&Name=UserName&Dept=Null&Origin=Dsk - Head of Marketing’s laptop http://<server-IP>/beacon.gif?Pos=HoM&Name=UserName2&Dept=Mkt&Origin=Lpt So, when you run through the access logs looking for malicious attempts, it will be easier to differentiate as to whose system was infiltrated. After successfully embedding the beacon, it is time to fill up the document file with data which look lucrative for the adversary such as fake password details, credit card numbers, SSN, so on and so forth. It is mandatory that such data is entered to deceive the adversary. Additionally, rename the file such as password-list.docx or similar to trick the adversary into believing that he has actually hit the jackpot. 4. Monitoring Malicious Attempts This will be the last piece where we will monitor if an adversary has gained access to the system and tried to steal away and access our decoy. Go to the /var/log/apache2/ directory and open the access.log file using your favorite log viewer or text editor. Deploy the decoys on the endpoint systems. Once the document is opened on the endpoint, it will send an HTTP request to our web server. You should be able to view an entry similar to the one below in the Apache’s access log: Where to deploy the decoys? The decoys can be deployed anywhere, ranging from laptops, servers, desktops, emails, mobile phones, etc. Generally, the decoys can be deployed on HVT’s (High-Value Targets) systems.
https://resources.infosecinstitute.com/file-decoys-endpoints/
CC-MAIN-2018-39
refinedweb
977
63.7
Holy cow, I wrote a book! M." SendInput You can take advantage of the fact that the OVERLAPPED associated with asynchronous I/O is passed by address, but there was some confusion about how this technique could "work" when kernel mode has no idea that you are playing this trick. OVERLAPPED. MasterOverlapped OtherData. OTHERDATA OVERLAPPEDEX Overlapped. FindOverlappedExFromOverlapped. a[b] *(a+b) &a[b] a+b Master + index == CONTAINING_RECORD(lpOverlapped, OVERLAPPEDEX, Overlapped) Master: index. Commenter S asks, "What happened to the return code from WinMain in a Windows 3.1 app?" After all, there was no GetExitCodeProcess function in 16-bit Windows. GetExitCodeProcess Basically, the exit code vanished into the ether. Unless you captured it. The Toolhelp library provided a low-level hook into various parts of the kernel, allowing you to monitor, among other things, the creation and destruction of tasks. That was how you captured the return code of a Windows program in 16-bit Windows. But if you didn't catch it as it happened, it was gone forever, lost in the ether. When you issue asynchronous I/O, the completion function or the I/O completion port receives, among other things, a pointer to the OVERLAPPED structure that the I/O was originally issued against. And that is your key to golden riches. If you need to associate information with the I/O operation, there's no obvious place to put it, so some people end up doing things like maintaining a master table which records all outstanding overlapped I/O as well as the additional information associated with that I/O. When each I/O completes, they look up the I/O in the master table to locate that additional information. But it's easier than that. Since the OVERLAPPED structure is passed by address, you can store your additional information alongside the OVERLAPPED structure: // in C struct OVERLAPPEDEX { OVERLAPPED o; CClient *AssociatedClient; CLIENTSTATE ClientState; }; // or in C++ struct OVERLAPPEDEX : struct OVERLAPPED { CClient *AssociatedClient; CLIENTSTATE ClientState; }; When the I/O completes, you can use the CONTAINING_RECORD macro or just static_cast the LPOVERLAPPED to OVERLAPPEDEX* and bingo, there's your extra information right there. Of course, you have to know that the I/O that completed is one that was issued against an OVERLAPPEDEX structure instead of a plain OVERLAPPED structure, but there are ways of keeping track of that. If you're using a completion function, then only use an OVERLAPPEDEX-aware completion function when the OVERLAPPED structure is part of an OVERLAPPEDEX structure. If you're using an I/O completion port, then you can use the completion key or the OVERLAPPED.hEvent to distinguish OVERLAPPEDEX asynchronous I/O from boring OVERLAPPED I/O. static_cast LPOVERLAPPED OVERLAPPEDEX* OVERLAPPED.hEvent Alternate title: News flash: Sometimes things happen by mistake rbirkby asks why the SHCOLUMNINFO structure has 1-byte packing. "Was the expectation that there would be so many columns in a details view that the saving would be worthwhile?" SHCOLUMNINFO: shlobj.h #include <pshpack1.h> /* Assume byte packing throughout */ (There was of course a matching #include <poppack.h> at the bottom.) This set the default packing for the entire header file to byte packing instead of natural alignment. #include <poppack.h> By the time this mistake was identified, it was too late. Windows 2000 had already shipped, byte packing and all. And once the code ships, it's done. You're stuck with it. Sorry. Yes, it's another installment of I bet somebody got a really nice bonus for that feature. A customer had this question for the Windows 7 team: Our program creates a notification icon, and we found that on Windows 7 it is hidden. It appears properly on all previous versions of Windows. What is the API to make our icon visible? First of all, I'd like to congratulate you on writing the most awesome program in the history of the universe. Unfortunately, Windows 7 was not prepared for your awesomeness, because there is no way to prevent your notification icon from being hidden. That's because if there were, then every other program (the ones that aren't as awesome as you) would use it, thereby causing your awesome icon to be lost among all the non-awesome ones. I'm sorry. You will just have to find some other medium for self-actualization. My flights to and from Beijing were on Hainan Airlines, a Chinese airline. One consequence of this is that Mandarin Chinese is the primary language of communication; English is a distant second. It also means that the in-flight movies are subtitled in Chinese, so if you can't read Chinese, you are restricted to movies in languages you understand. I wasn't interested in the English-language movies, although I did watch a little bit of "The Other Guys", a Will Ferrell vehicle. In one scene, Ferrell's character and his friend have dinner in a Chinese restaurant. Ferrell's character says to the waiter, "謝謝" which means "Thank you" in Mandarin. The waiter responds, "唔該" which means (in this context) "You're welcome" in Cantonese.¹ Part of my brain wondered if this language mismatch was some sort of subtle commentary about the nature of Will Ferrell's character, that he's perhaps a bit of a poseur, or that he's out of place and doesn't realize it? And part of my brain couldn't believe that the other part of my brain used "subtle" and "Will Ferrell" in the same sentence. Anyway, the only other language I knew that was offered by the in-flight entertainment system was German. So I watched Willi und die Wunder dieser Welt, a movie-length version of the German children's television show Willi wills wissen. And watching the movie reminded me that Germans are obsessed with poop. During the course of the movie, you see a flying fox pooping, you see a polar bear pooping, and you investigate a Japanese toilet. I didn't stick around for the whole movie, but I wouldn't be surprised if you also saw a scorpion pooping in the final segment. (In the Canadian segment, somebody talks with Willi in heavily Canadian-accented German which was apparently learned phonetically. I could barely understand him. It reminded me of my high school German class and the students who couldn't shake their thick American accents.) Footnote ¹There are several phrases that roughly mean "Thank you" in Cantonese. The two primary ones are the aforementioned "唔該" and "多謝", and the rules governing proper use of each one are complicated. Microspeak is not always about changing a word from a verb to a noun or changing a noun to a verb or even changing a noun into a verb and then back into a noun. Sometimes it's about data compression. This testing won't inform RC, but we'll need it to inform an RTM release. First, you need to familiarize yourself with a less-used sense of the verb to inform, namely to guide or direct. A typical use would be something like "This data will inform the decision whether to continue with the original plan in Product Q." In other words, this data will be used to help decide whether to continue with the original plan. But of course, at Microsoft, it's all rush rush hurry hurry no time for slow sentences just get to the point. So we drop out a few words from the sentence and instead of informing a decision about something, we just inform the thing itself: "This data will inform Product Q." Therefore, the sentence at the start of this article is shorthand for "This testing won't inform [some sort of decision regarding] RC, but we'll need it to inform [that same decision in] an RTM release." In other words, the result of this testing won't have any effect on the release candidate, but it will be used to help make some sort of decision regarding the RTM release. Another citation, taken from an executive slide deck: Other take-aways What learnings can we get today to inform the release? I like how that brief snippet combines three pieces of Microspeak: take-away, learnings, and inform. Tanveer Badar asks why the file properties Advanced dialog shows two checkboxes (compression and encryption) even though NTFS supports only one or the other at a time. "Why not have two radio buttons instead of these silly check boxes?" Actually, if you want radio buttons, you'd need three, one to cover the "neither" case. Let's look at what those radio buttons would look like: Compress contents to save disk space Encrypt contents to secure data Neither compress nor encrypt This takes an implementation detail (that NTFS currently does not support simultaneous compression and encryption) and elevates it to the user interface, so that it can provide maximum confusion to the user. "What a strange way of exposing compression and encryption. If I want to turn on encryption, I should just check a box that says 'Encryption'." The current implementation (two check boxes) matches user expectations, but then says "Sorry, we can't do that" if the user picks a combination that is not currently supported. But who knows, maybe someday, NTFS will support simultaneously encryption and compression, and all that will happen is that the error message goes away. You don't have to redesign the property sheet (and invalidate all the training materials that had been produced in the meantime). Either way, it's a leaky abstraction that sucks, but at least the suckiness isn't shoved in the user's face. Single-use tickets purchased from subway vending machines are valid only on the day of purchase for use in that station. Do not buy your return ticket at the same time as your outbound ticket because it will not work. This detail is clearly explained on the ticket that you receive after you have paid for it. (Also, the vending machine will ask you how many "sheets" you want. It's asking how many tickets you want.) Subway station names are printed in both Chinese and pinyin, but the pinyin omits the tone markers, which means that you will have no idea how you're supposed to pronounce the station name, should anybody ask you to say it. (See below.) Unlike in some cities, where the subway logo is bright and distinctive (and therefore easy to spot from a long way away), the logo for the Beijing subway is not consistent in color, which makes it hard to pick out from a busy streetscape. (One sign I saw used the high-visibility color scheme of beige-on-brown.) The logo is a monogram of the Latin letters "D" and "G", because the Mandarin word for "subway" is pronounced "dì-tiě". You might think they would use "D" and "T", but you're being too literal. Even worse, the Olympic Green station entrance nearest the convention center is so unobtrusively marked that if you aren't standing on the correct side of the building looking directly at it, you won't see the sign at all and you will end up spending an hour walking around Beijing looking for it. (For reference, the station entrance is opposite convention center entrance C-2.) When you fail to find the Olympic Green station entrance, you might consider going to a security guard booth (they are all over Beijing, the city being somewhat security-obsessed in a mostly-theater sort of way) holding a subway map with the Olympic Green station circled and asking, "火車?" because you don't know the Mandarin word for "subway" and have to make do by asking for the "train". Do not expect the security guard to have any clue what you're asking for. (Okay, I sort of undermined myself by pronouncing the first word in Mandarin but the second in Cantonese, because the two languages occupy similar portions of my brain and I often get them mixed up. But still, the first two cues...) In general, if you ask for directions but don't know more than a few dozen words of Mandarin, you're going to be in a world of hurt. My plan was to hold a map, point at it, and ask, "我在哪裡?" ("Where am I?"), and then calculate what direction to head based on the answer. Do not expect people to answer the question you ask. They will instead ask you other questions like "你去哪兒?" ("Where are you going?") but since answering that question is beyond your vocabulary, all you can do is repeat your original question, and they will give up, frustrated. Telling them that you're from the United States doesn't help, because they don't speak English. (The "Where am I?" technique worked great in Germany. The person I asked would locate me on the map, and even orient the map, then follow up with additional questions that I struggled to understand and answer.) It has been suggested that my profound difficulty in getting directions was exacerbated by the fact that I look like somebody who should know Mandarin. If I were some European-looking person, I wouldn't have had as much of a problem because, I'm told, Chinese people naturally assume that if they see a Chinese person on the street, that person speaks Mandarin. (The person may speak a regional language as well, but you can count on them speaking at least Mandarin.) If you look Chinese but don't speak Mandarin, then they will just get frustrated at this Chinese person who refuses to speak Chinese. This roughly matched my experience. Pretty much everybody assumed that I spoke Mandarin. The exception? The street hustlers and scam artists. They had me pegged for a foreigner. By the way, I eventually solved my problem by looking for a bank. The manager on duty spoke some English, and combined with my rudimentary Mandarin, Cantonese, and Hokkien (thank heaven for cognates), I was able to get the information I needed. Of course, by that time, I had wandered so far astray that the nearest subway station was nowhere near the one I was looking for originally! Oh, and do not expect the hotel concierge to give you an up-to-date map. The information on the map had not been updated to take into account recent subway expansion, which means that its directions on how to get to points of interest were unnecessarily cumbersome. (What's more, the hotel itself did not appear on the map, because it was covered by an inset of the Olympic stadiums. This makes it hard to orient yourself once you step outside.) In fact, most of the time the street I was standing on didn't appear anywhere on the map (or at least I couldn't find it), so I had no clue where I was. The air pollution in Beijing is legendary. The week before I arrived, the United States Embassy declared that the Air Pollution Index in Beijing topped 500, earning the rating "Hazardous for all people." On the other hand, the official Chinese government pollution index was "only" 341. (Mind you, 341 is still off the chart. For grins, compare the scales used by mainland China, Hong Kong, and Malaysia.) You don't really notice the effect of the air pollution until you return to your hotel at the end of a day outdoors and wonder why your throat is sore and you feel like you spent the day in a smoke-filled bar. Walking through the Forbidden City makes you feel like Frodo in The Lord of the Rings. You fight your way across a courtyard to reach the building at the other end. Upon reaching the building, you cross the gate and before you lies... another seemingly-identical courtyard. This repeats about twenty-five bazillion times. They should really call it the Forbidden County. If you're trying to get to the Summer Palace, do not accidentally leave your map in your hotel room thinking that "This is such a prominent tourist location it must certainly have adequate signage, or at least be present on the 'things nearby' map at the station." The only nearby attraction on the map at the station is the Old Summer Palace. The only directions to the Summer Palace is a single arrow on the plaza level of the station. The arrow tells you to Frogger across a busy four-lane street (and over the fence). If you go to the crosswalk some distance away, you end up wandering in the wrong direction for a while and turning around when you figure "This can't be right." On the way back, you try a slight variation on the path out of the station and notice that there's a directional sign for the Summer Palace facing away from the station. (I.e., only people returning to the station can see it.) You follow that arrow and wonder if you're on the right street since it's pretty much an empty street as far as the eye can see, but you gradually find tour buses so you figure you're getting closer. You then find the Summer Palace parking lot and say, "Cool, there must certainly be a sign to the Summer Palace from the parking lot" but you'd be wrong. You then see a tour group in the distance and take your chances that they are going into the Summer Palace (rather than returning) and follow them down an unmarked side street, then another unmarked side street, before spotting the entrance to the Summer Palace. China clearly has yet to figure out this "foreign tourists not visiting as part of a guided tour" thing. My guess is that since it was a closed country for so long, there was no need for directional signage because all foreign tourists were necessarily accompanied by a government-approved tour guide, and the government-approved tour guide knows how to get there. The Summer Palace is very scenic. I bet it's even prettier in the summer. Orthographic note: Out of habit, I use traditional characters even though China uses simplified characters. With one exception, I'm reasonably comfortable with reading both sets of characters, though when writing I prefer traditional. Traditional characters feel more formal and "standard" to me, whereas simplified characters feel too casual for normal use. (Like writing "u" and "b4" instead of "you" and "before".) The one exception? The character for "car": 車. The simplified version is 车 which to me is unrecognizable because it destroys the ideographic representation of the top view of a car. (The central box is the body of the car, and the horizontal bars at the top and bottom are the axles. The simplified version is just a number "4" with some extra bars.) Mostly-theater: X-ray machines are omnipresent, but they are largely ignored. People just walk right on past them. The TechEd conference I attended had three security checkpoints: One with an X-ray machine and a metal detector, and two additional checkpoints where security personnel checked that you had a valid badge before letting you pass. What nobody appeared to notice is that if you took the publically-accessible skybridge from the Intercontinental Beijing Beichen hotel next door, you could enter the inner sanctum of the conference without ever passing through a security checkpoint.
http://blogs.msdn.com/b/oldnewthing/archive/2010/12.aspx?PageIndex=2
CC-MAIN-2013-48
refinedweb
3,256
60.75
jboss-cli-client.jar cli.disconnect() hangs when called from groovy scriptLloyd Meinholz May 28, 2013 7:41 PM I am trying to follow the instructions from: I have copied the groovy script and things seem to work as expected, but the script hangs on the disconnect. I have simplified the script to: import org.jboss.as.cli.scriptsupport.* cli = CLI.newInstance() cli.connect() cli.disconnect() and still the script hangs. I am connecting to a JBoss EAP 6.1.0 instance running on my Linux localhost. I have tried with 32-bit and 64-bit 1.6.0 and 1.7.0 JDK's with the same result. When I do a kill -3 on the script, I get some things that seem to point to xnio: Full thread dump Java HotSpot(TM) 64-Bit Server VM (23.21-b01 mixed mode): "DestroyJavaVM" prio=10 tid=0x00007fc74c009000 nid=0x6dc2 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Remoting "cli-client" task-4" prio=10 tid=0x00007fc6f8072000 nid=0x6ddb waiting on condition [0x00007fc739667000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000007c47c5f40> .xnio.LimitedBlockingQueue.take(LimitedBlockingQueue.java:95)) at java.lang.Thread.run(Thread.java:722) The script functions correctly in that I am able to retreive the start time and compute the uptime, but the script doesn't seem to properly disconnect from the server. Does anyone have any pointers? Thanks, Lloyd 1. Re: jboss-cli-client.jar cli.disconnect() hangs when called from groovy scriptMustaq Pradhan Jun 21, 2013 2:20 AM (in response to Lloyd Meinholz) I am experiencing the same. Any resolution? 2. Re: jboss-cli-client.jar cli.disconnect() hangs when called from groovy scriptjaikiran pai Jun 21, 2013 6:41 AM (in response to Mustaq Pradhan) This should be fixed once this PR gets reviewed and merged 3. Re: jboss-cli-client.jar cli.disconnect() hangs when called from groovy scriptjaikiran pai Jun 21, 2013 11:42 PM (in response to jaikiran pai)1 of 1 people found this helpful The fix will be available in WildFly 8.0.0.Alpha2 which will be released soon. 4. Re: jboss-cli-client.jar cli.disconnect() hangs when called from groovy scriptLloyd Meinholz Jun 23, 2013 8:37 PM (in response to jaikiran pai) I was able to verify that this issue does not exist with WildFly 8.0.0.Alpha2. I tried the jar with my EAP 6.1.0 instance and it didn't work, which I thought was likely. Thanks. 5. Re: jboss-cli-client.jar cli.disconnect() hangs when called from groovy scriptMustaq Pradhan Jun 24, 2013 6:39 PM (in response to Lloyd Meinholz) As we are using EAP 6.1.0 we will wait for the next EAP release with the fix. Thanks.
https://developer.jboss.org/thread/228708
CC-MAIN-2017-47
refinedweb
473
65.01
Conclusion Disk I/O is not and never has been a simple area. The scope for problems is very wide. If your C# I/O code doesn't handle exceptions properly, you'll get to see some very difficult problemsgenerally at inconvenient moments! Before tackling any I/O, it's a good idea to devise an effective exception-management strategy. Fortunately, the C# language provides a powerful technique in the form of the low-tech try-catch-finally statement. The finally clause provides a good opportunity for deallocating resources, which helps you to avoid leaving old files behind after exceptions occur or after the program finishes. If you take away just one point from reading this article, make it this: Strive to manage any exception conditions in your own code. Even if you just make a note of the exception, that provides a means to audit the execution at some later time. I've seen cases where code was written with little cognizance taken of exceptions; then, many months later, some weird platform configuration resulted in an uncaughtand troublesomeproduction exception. An important point to understand about I/O is that larger platforms tend to be more forgiving about poor resource deallocation. The same rule is not true of smaller platforms, such as mobile devices. If your code is not well behaved on small devices, your software may get into difficulties. C# provides a rich I/O namespace with support for a variety of different design approaches. For example, you can open streams in read-only mode; not exactly super-high-tech, but this approach can help to protect data from inadvertent changes. In this context, read-only access is a useful design pattern to incorporate into your work. In addition, C# provides good support for binary data I/O. There is much scope for study in the C# I/O namespace.
https://www.informit.com/articles/article.aspx?p=1347504&seqNum=6
CC-MAIN-2020-24
refinedweb
311
54.02
Socialwg/2016-06-21-minutes Contents Social Web Working Group Teleconference 21 Jun 2016 Attendees - Present - cwebber, Arnaud, aaronpk, eprodrom, ben_thatmustbeme, wilkie, KevinMarks, sandro, rhiaro - Regrets Chair - Arnaud - Scribe - rhiaro Contents - Topics - Summary of Action Items - Summary of Resolutions <cwebber2> oh hi Arnaud <aaronpk> all my technology is failing <Arnaud> tantek can't make the call today and asked me to take over chairing <aaronpk> can you hear me? <aaronpk> redialing <KevinMarks> I'm on but muted, didn't hear aaron <wilkie> I hear you! <aaronpk> woo <aaronpk> ironically hangouts never seems to work for me in chrome. had to dial from safari <scribe> scribenick: rhiaro Approval of f2f minutes <Arnaud> <Arnaud> <KevinMarks> <KevinMarks> is where micropub is discussed Arnaud: there's a -1 from tantek about approval of micropub for CR is missing <KevinMarks> the resolution is in that Arnaud: MIcropub going to CR was discussed on 2nd day, June 7th, resolution is there to publish new ED <ben_thatmustbeme> I don't think it was there at the time of his -1 Arnaud: But no resolution on CR ... Does anybody remember? <ben_thatmustbeme> oh, nevermind eprodrom: did we vote on that at the f2f or in the previous telecon sandro: at the face to face I'm pretty sure ben_thatmustbeme: I know it stopped tracking minutes at some point rhiaro: the bot caught that up, that was fixed Arnaud: we can approve June 6, we need to do archeology on the 2nd day ... If we are missing minutes maybe somebody has a personal log? <KevinMarks> or public log? <aaronpk> logs here: <eprodrom> Arnaud: this resolution was captured about WD, no mention of CR ... Maybe it's the way the proposal and the resolution were worded? <aaronpk> we started this document too <ben_thatmustbeme> should we just make the official resolution again? sandro: we wouldn't have made the transition request document if we hadn't ... I'm checking my irc logs Arnaud: let's not spend too much time on this, see if we can track this down eprodrom: tantek and I will do that <Arnaud> PROPOSED: Approve minutes of June 6 2016 <cwebber2> iirc Loqi logs this channel right? <eprodrom> +1 <cwebber2> +1 +1 <aaronpk> +1 <paul> _1 <aaronpk> cwebber2: that's the url i pasted above (socialwg.indiewebcamp) <cwebber2> oh oops <ben_thatmustbeme> I could not find it in my irc logs <paul> +1 <cwebber2> thx aaronpk <ben_thatmustbeme> +1 RESOLUTION: Approve minutes of June 6 2016 AS2 Arnaud: evan, anything blocking? eprodrom: At the f2f we had gone through some additional requirements for the document including implementation report template, that kind of stuff, those are all now in the documents ... We also chose to move it from jasnell's personal github to w3c github namespace <eprodrom> <eprodrom> eprodrom: So as of right now we have up to date documents at these two urls <eprodrom> <wilkie> and I fixed the links on the socialwg wiki to point to them <wilkie> not sure if there are any other links eprodrom: These are mostly editorial changes, the big editorial change was adding an implementation report template and including that ... Ready for submission of new implementation reports by email or github PR <Arnaud> eprodrom: Our issue list is at 0 ... The last outstanding task for me is making sure the transition req is filled out. I have to answer some questions on that. Arnaud: Ist here a schedule for the call? sandro: Is the test suite stuff done, the cross linking between two different testing systems? eprodrom: links from the document to the different test suites, link to the paresable data and a link to the validator sandro: they don't link to each other but I guess that's okay eprodrom: I can put links on each of them if that's what we need to get done ... I'll do an issue for a link to the validator from the test documents directory with a readme ... And a link from the validator to ... one thing that I did with this last push is that I moved the test data into the spec document repo, it was easier to keep everything all together. May do that with the validator code too aaronpk: I just found a random URL in the test suite and dropped it into the validator and it gives a warning that it should have an 'id' property, so I thought that it might be good to check the test suite data actually validates ... Looks like the examples are missing ids Arnaud: we can keep working on the test suite, but good that you point that out eprodrom: with AS2, there are very few required properties. A name is almost always required, an id is usually required, so we give warnings. We have examples.. one example we have is an empty object. So we have examples that processors should be able to consume and should be able to parse, however when they're put through the validator they'll show warning because they're poor style. Does that make sense? <aaronpk> eprodrom: If you put an empty document through as2.rocks ... I think need to have a testable system for consumers and we need to have test data that's useful to help them test edge cases, but we also have to have those notifications in the validator for those edge cases <sandro> ( Arnaud, I'd like to return to Micropub CR this meeting, soon ) <Arnaud> ok aaronpk: How do I know what to do with the data ? How do I know if my code is properly handling it? eprodrom: What should your code do? Send an email, fetch a url, put a pin into a map. I'm not sure if there's a correct behaviour we can require out of these processors. What we're looking for is can you parse it, does it look right within your framework cwebber2: I just wanted to follow up; we've discussed this before, AS2 is a vocab and the testing toosl around it don't and can't enfoce side effects. That's what AP and ActivitySub do, they're examples of real requirements of implementing that. This has come up before and we specifically went against requiring side effects to have in the tests, as this isn't specified in the vocabulary aaronpk: I just want to know how I know if my code is handling it eprodrom: How would we know that? Ther'es no way to know that? There are a million different things you could do ... We can't require any behaviour out of these systems ... One way you might know is if you're writing a parser and your parser doesn't throw any errors, that's one good way ... So what wev'e done is provide some documents that are known good, and that's about the extent we can go to Arnaud: I'd rather not we have this discussion again, we've gone over it ... There's only so much testing we can do eprodrom: One thing we could do is are you looking for some comments on this? Like this is a place, this has all the optional attributes of a place... something like that? aaronpk: The other way to handle that is are there examples of documents that are known bad, so I know that if I parse this document I should see an error? That would help give me something to test ... Otherwise I'm just parsing a json document and tha'ts all I'm testing ... If there are examples of valid json documents that are invalid AS2 documents I can use that to test parsing as2 eprodrom: That sounds good. We can put together test documents that are known invalid AS2 documents aaronpk: THat would definitely help me sandro: but mostly I think you have to hand inspect each one. You're supposed to look at the document, read the spec, and see if your app does whatever makes sense to do for that content. That's my expectation of what it means to be a conforming consumer. You can't automate consumer testing of AS2 ... That may be something to say prominently on the readme around these files ... The implementation report around consumers presumably say something like my appication understands what this vocabulary temr means and does something meaningful with it. There's no way to automatically test that given it's all human behaviours.. it turns into some html or pixels on the screen aaronpk: makes sense <cwebber-argh> server I was connected to for irc is unreachable eprodrom: Yeah the implementation document covers all of the object classes, each property of each object class, the core and extended vocab, and asks whether you implemented that class, and for each property did you implement it, and a place for comments ... So if you implemented audio class but you don't necessarily process wav files or something, you could put that kind of comment into there <cwebber-argh> also we had a heavy discussion about this in SF and after and came to the conclusions about how to go about testing and etc, I really feel like this has been move forwarded with after already being discussed to death sandro: do you think it's possible peopel might see that and go.. I have a json parser therefore I'm implementing all of this? eprodrom: We say in our document your application must use this, just passing through unrecognised properties doesn't count as an 'implementation' <eprodrom> "For each core class your application implements, note which properties of the class it uses. Here, "implements" means that your application uses the property directly; just passing through unrecognized properties doesn't count as an "implementation"." Arnaud: I think this is good, still some things to be tied up, but I don't hear anything that would stop us on the CR request ... We already have a resolution eprodrom: I'd like to take the current version and take the new links to WD and we do need a resolution on that <Arnaud> PROPOSED: publish the latest editor's draft of AS 2 <aaronpk> +1 <eprodrom> +1 <cwebber-argh> +1 +1 <ben_thatmustbeme> +1 <sandro> +1 (as new WD) RESOLUTION: publish the latest editor's draft of AS 2 as new WD <KevinMarks> +1 Arnaud: sandro, you'll work on the scheduling and sending the request? sandro: yes ... Back to micropub. I did find me IRC log and it looks like we messed up and we didn't record that <ben_thatmustbeme> obviously tantek did understand that was well sandro: I certainly understood that we had. I've talked to Wendy about it. But it's not in the record, so that's an oops ... I guess the easiest thing to do would be to do that resolution now? <KevinMarks> makes sense <Arnaud> PROPOSED: Move MicroPub to CR <ben_thatmustbeme> +1 <eprodrom> +1 <KevinMarks> +1 <aaronpk> +1 <cwebber-argh> +1 <sandro> +1 (I feel we decided this as the F2F but it didnt get recorded) <wilkie> +1 +1 RESOLUTION: Move MicroPub to CR <cwebber2> whew, back on this server :) Micropub Arnaud: want to add anything on status of WD? aaronpk: I went through all the issues from the f2f and published a new WD yesterday. All work we had agreed on at the f2f ... No more open issues on that <aaronpk> sandro: as far as you know we're ready to finish the transition request. Wouldn't hurt for people to give it another read ... Later today I'll look over them both and try to send them ... Evan do you think you'll be able to do your publication today? eprodrom: I think so. There may be some trickiness with the fact we've moved to a different ED location. I'm not sure if the echidna token stays valid... aaronpk: I'm pretty sure they do eprodrom: If that works then I should probably be able to do it after the call sandro: I will circulate a doodle poll once I have a little more data from folks jf2, fpwd ben_thatmustbeme: I ran out of the meeting early last time and we resolved to get there. I don't know where to go next. I need to work out with sandro to get a token to publish Arnaud: It doesn't work for the fpwd ben_thatmustbeme: So then I don't know sandro: we've already got the approval from wendy for that so it's the talking with the webmaster ... I guess send me an email with the pointers to what you've got and I'll try to help you from there ben_thatmustbeme: ok post type discovery Arnaud: tantek is not here, so we skip for this week? eprodrom: he presented a new version at the f2f but I'm not sure if there have been any new devleopments on it since then <sandro> FPWD was approved Arnaud: I see there are open issues so this is work in progress obviously sandro: the main thing is this was approved for fpwd by the group and wendy, so we are ready to publish once he turns the crank, same as ben Arnaud: unelss anybody else has anything to add I think we can leave it at this for this week? Webmention aaronpk: We have received a couple of implementation reports, one from ben and one from GNU Social <aaronpk> aaronpk: That's pretty exciting ... Three including mine. HOpefully we'll get more coming in ... I have been working on the issues and published a new ED with a lot of the issues addressed. Still a couple of open ones <aaronpk> aaronpk: One in particular I would like to get some help on, but I can chat offline about that, it's a minor thing ... So new ED yesterday ... Not ready to publish a WD of that yet <ben_thatmustbeme> i had wanted to show off mf2 -> as2 conversion for SOME things, but my hosting provider is having issues, so i'll hold off on that eprodrom: I have a question for aaronpk ... I looked through exit criteria for webmention. Report for GNU Social has a couple of unchecked boxes, I assume that's going to be the case for all implementations ... What happens if we have 3 implementations or 5 implementations, and none of them pass discovery test 17 for example aaronpk: my understanding is that each part needs to be implemented by at least 2, but no implementation has to implement everything ... If there is something that nobody has implemented we take it out of the spec because it had no purpose. But correct me if I'm wrong sandro: that sounds right Arnaud: The exit criteria is every feature has to be implemented by two implementations at least ... If one part is not implemented, one way to deal with it is to prompt implementors to implement it ... Then you can declare victory and move forards. Downside is you're focring peopel to implement something they don't care about ... Other thing to do would take a resolution from the wg, to publish a new CR without that feature <sandro> Yeah -- nudging people to implement something just for the spec is a BAD IDEA. (and I confess I've done it several times. With lots of regret.) Arnaud: Still delayed because of process ... Just a matter of a few weeks aaronpk: is this non-normative things, or only normative? Arnaud: non-normative is editorial, we can change anything we want ... Between CR and PR you can change anything that's not normative ... Only talking about what impacts compliance sandro: I'm a little fuzzy about the SHOULDs ... Do you think that we can .. I don't think we can freely change places where the spec says you SHOULD do this.. we can't just take those out or add those Arnaud: I think technically you can sandro: I think it would invalidate reivews. I wouldn't want to do that withotu careful thought Arnaud: I agree with that, just because you can doesn't mean you should. Probably wise not to do that casually eprodrom: the only thing that I'm getting out of.. looking at the gnu social implementation.. seems like they skipped some of the security and verification suggestions, which I think are that's up to you if you choose not to implement the security ocnsiderations, but if we see a pattern there where we see no-one implements the chekc of not accepting webmentions that are in an html comment, I wonder if that informs any decision making we do later on. Do we change it in the spec? scribe: We're suggesting some verification, validation and security parts of the implementation. We have at least one case where somoene has skipped a lot. If we see people skipping a lot is that cause for concern for us? Arnaud: You could write up an issue to say you think we got it wrong about security and we need to change the spec to make it reuqired ... Then we'd need a new CR and new implementation reports <ben_thatmustbeme> aaronpk, i don't actually see in the spec reference to ignoring links in HTML comments actually eprodrom: I'm going to keep an eye open. i think that in writing most of our specs we are saying it's okay to do x because you will also do y. It's okay to include this link in your page because you're also going to be verifying the link was in this webmention. It's okay to include unverified properties in your AS2 because you're going to be checking this and this. But if you don't do the checks, i makes those other parts more dangerous ... I'll keep an eye on this. I'll raise it if it seems to be a pattern ... Aaron, for your implementation did you do these security considerations? aaronpk: My implementation passes all of the webmention.rocks test ... In security I think mine.. I don't moderate, I displya them immediately. I don't reverify. I don't have a byte limit, but I do have a time limit <ben_thatmustbeme> i had wanted to show off mf2 -> as2 conversion for SOME things, but my hosting provider is having issues, so i'll hold off on that <cwebber2> +q Arnaud: We have 8 minutes left, anything else? cwebber2: I thought I'd give an update on activitypub stuff ... One thing is that jessica and I have done some large refactoring of the document that's making things structurally better to reduce effort when we split into two documents <aaronpk> ben_thatmustbeme, i don't think it needs to explicitly say ignore links in comments since it says to explicitly look for <a> <img> and <video> and similar tags cwebber2: So I have also completely marked up locally everything that needs to be done towards that and am working on that ... Meanwhile jessica merged a couple of issues we'd discussed ... And there's a PR from jessica that we're looking at merging, we just need to refactor it to the existing refactor that just happened. THerew as also some discussion we should have next week about authentication stuff ... Not now, possibly complicated ... One positivie thing, I should have a minimal implementation of AP done that I could report on ... That I can point to ... That's mostly it <ben_thatmustbeme> aah aaronpk, i see that now, that does make sense, yes cwebber2: One other thing that's not AP related ... More about implementations of AS2 ... I had recently updated activipy to handle the id and type aliases, and as we discussed you don't need @id and @type, we support id and type ... I supported that from a consumption standpoint, but I'm still outputting @id and @type. In a certain sense it's easier for me because I'm using json-ld tooling ... Using the context for @id and @type as aliases is kind of -cwebber2 cuts off- ... Is it mandatory to use them without the @, and we expect all AS2 documents do use them without the @ or is that optional? ... It's not clear in the document currently, it says they're equivalent, doesn't require eprodrom: that question is above my pay grade ... The way that we've structured the aliases, it's preferable for publishers to output without the @ ... But it's still valid AS2 if you have them cwebber2: I'm going to make the change to make it output them without, so I'll do that soon but not immediately if it's still valid Arnaud: If you want to, feel free to put that as an agenda item for next week <ben_thatmustbeme> it was my understanding as well that the @id should always be id rhiaro: if both are allowed, what's the point of the alias? <ben_thatmustbeme> etc rhiaro: It's a massive pain to check for both eprodrom: I'd like to put this on the agenda for next week ... I'll be better informed then ... and what that means for publishers and consumers ... I understand for consumers it's an extra burden to check for both and it would be good to minimise that burden Arnaud: every time you add some flexibility it means more pain ... Anything else? We're out of time <ben_thatmustbeme> rhiaro++ <Loqi> rhiaro has 207 karma Arnaud: Have a good day :) <Arnaud> trackbot, end meeting
https://www.w3.org/wiki/Socialwg/2016-06-21-minutes
CC-MAIN-2017-43
refinedweb
3,588
66.47
Our 10th Year! I N F O C U S VOL.10, NO.12 F O R P E O P L E OV E R More than 125,000 readers throughout Greater Baltimore Can you expand your brain? Memory loss isn’t inevitable Whereas memory specialists have long concentrated on the physiological elements of the brain, the centers will move to improve the brain’s functioning by treating the lifestyle — eating, sleeping, exercising — of the individual to whom the brain belongs. “Slowing of memory and memory loss is a common occurrence as we age,” said Fotuhi, a Harvard Medical School graduate who got his Ph.D. in neurology from Johns Hopkins University. “But it doesn’t have to happen,” he said. “Through physical and mental activities, people can keep their brain and memory in good shape and ward off Alzheimer’s.” A recent article in AARP magazine noted that “a mounting stack of studies suggests that the condition of the body somehow affects the condition of the DECEMBER 2013 I N S I D E … PHOTO BY CHIRSTOPHER MEYERS By Robert Friedman “Just because your brain can’t hop on a treadmill doesn’t mean it can’t exercise,” said Dr. Majid Fotuhi, chief medical officer of the NeurExpand Brain Centers in Lutherville and a recently opened center in Columbia. The centers, which Fotuhi heads, treat “anyone who has concerns about memory and brain functions,” he said. “Our memory makes us who we are. It shapes the kind of life we live.” Fotuhi, a Baltimore-based neurologist, is fast becoming recognized by experts, from Dr. Mehmet Oz to RealAge author Dr. Michael Roizen, as being on the cutting edge of treating brain and memory problems. Fotuhi also plans for another center next year in Chevy Chase. Executives of the company that has been formed to run the brain centers have set a goal to open some 100 centers around the country in the next five years, according to the Baltimore Business Journal. “What this [center] is designed to do is to focus on what you can do to make your brain stronger and improve your memory,” said David Abramson, who helped put together the new company. He said that he sees a significant business opportunity among the millions of aging baby boomers concerned about their brain functions. 5 0 L E I S U R E & T R AV E L Voluntourism makes for the trip of a lifetime; plus, how to rent a car and drive it in Europe page 25 Majid Fotuhi, chief medical officer of NeurExpand Brain Centers, examines an MRI of the brain. The centers help patients with memory problems by working to increase brain size through lifestyle improvements, memory exercises and biofeedback. brain…Being obese quadruples the risk of [Alzheimer’s]. Diabetes can speed up brain shrinkage, as can high blood pressure,” as well as sleep apnea, depression and everyday stress. Depression, which used to be treated almost exclusively by psychiatrists going into mental histories and prescribing drugs, can now be greatly relieved, according to mental health specialists, through a change in lifestyle — especially increased exercise. And Fotuhi said not only could memory loss be averted, it could also improve through a 12-week, individualized program devised at the center and meant to grow the brain. “The best remedy for late-life Alzheimer’s disease is mid-life intervention,” he said. While the program costs several thousand dollars, “all our testing and treatment protocols are covered by Medicare and major insurances,” Fotuhi said. “Patients do not need to have a major neurological disease to qualify.” ARTS & STYLE A new Baltimore poet finds her voice; plus, theater and music highlight the holiday season page 30 FITNESS & HEALTH k Bacteria that may fight fat k Raising a toast to grape juice 3 Fighting brain shrinkage The treatment aims to expand the hippocampus, the portion of the brain deep within the temporal lobes that controls short-term memory and determines which remembrances are stored longterm. It’s the hippocampus that “makes See BETTER BRAIN, page 6 LAW & MONEY k Finding lost savings bonds k Obamacare scams 16 VOLUNTEERS & CAREERS k Turning vets’ lives around 22 PLUS CROSSWORD, BEACON BITS, CLASSIFIEDS & MORE 2 DECEMBER 2013 — BALTIMORE BEACON More at TheBeaconNewspapers.com Imperfect harmony You know how it is that sometimes a different gentleman who often attends something very ordinary strikes you as the same service cannot carry a tune. I have learned to tune out his meaningful in a new way? near misses on those occaFor example, I attend Sabsions when he chooses to bath services every week at a sing along. synagogue near my home. But this new fellow was difThere are a number of places ferent. He didn’t have any trouin the service where everyble keeping to his key. He was one is expected to sing along or sing in response. dead on — just in a different Normally, at these times, I key from everyone else, and it hear mostly my own voice in wasn’t a key that harmonized. my head. But if I stop singing He even had a nice voice. and listen for a moment, I can FROM THE He probably was well aware hear the whole room singing PUBLISHER of that, too, as he continued as if it were a symphony. By Stuart P. Rosenthal to sing quite loudly and clearThere are the lady sopraly in his own personal key, nos (with a diva or two), some altos, the every single note clashing against the othmale tenors and baritones, an occasional ers in the room, grating on my nerves. bass. All blend, usually, into a nice, rich In the sanctuary as a whole, his dissotone, at least when the tune being led is a nance was probably negligible. In fact, I familiar one. may have been the only person aware of it. For some reason, though, it continued But the other day, I was aware not of a symphony, but of a cacophony. A fellow sit- to occupy me long after the song was over. ting near me, apparently a visitor or new- (Yes, I daydream in synagogue. Somecomer, had begun to sing loudly right at times.) the start of the song — but at a note or two So I kept thinking: Why did this fellow, lower than the leader and, to my mind, the who evidently was quite musical, not realize that he was out of sync with everyone else? rest of us in the room. Or did he realize it and not care? Was Now, I happen to be used to the fact that Beacon The I N F O C U S F O R P E O P L E O V E R 5 0 The Beacon is a monthly newspaper dedicated to inform, serve, and entertain the citizens of the Greater Baltimore area, and is privately owned. Other editions serve Howard County, Md., Greater Washington DC and Greater Palm Springs, Calif. Subscriptions are available via third-class mail ($12), prepaid with order. Maryland • Contributing Editor ..........................Carol Sorgen • Graphic Designer ..............................Kyle Gregory • Advertising Representatives ............Steve Levin, ........................................................................Jill Joseph • Publishing Assistant ....................Rebekah Sewell. © Copyright 2013 The Beacon Newspapers, Inc. he, perhaps, trying to make a statement? Did he think that, somehow, he was singing in the “right key” and everyone else was wrong? Was he listening so intently to his own voice that he remained truly unaware of the dissonance he was causing? Or did he view the clashing notes as a problem created by others, not himself? I have no idea who the fellow was or what, if anything, he was thinking. But I couldn’t help but see the whole experience as a metaphor of sorts — for human differences in personality, political beliefs, lifestyles and the like. Most of us are content to play our role in society and to focus for the most part on ourselves, with some secondary attention to those around us and to society as a whole. We prefer to do the work, or sing the part, that comes most naturally to us. (Perhaps that’s because when we must strain to reach beyond our register, our voices become “falsetto.”) Then there are some whose song/personality/belief is a bit different. It sounds to the rest of us like it’s off-key, or as if those people can’t carry the tune the way most of us can. But they’re singing along just the same, eager to participate in their way, and we generally respect that. But it can be harder to deal with those who, knowingly and unabashedly, insist on singing loudly in a different key altogether — a key, in fact, that creates dissonance with the song the vast majority of us sing. Now, it’s interesting to realize that, were we to listen to this other song on its own, we might well think it is a perfectly fine song, as melodic as any other. It only produces dissonance when it’s sung a half-tone or so differently from the song others sing. (After all, it takes two to make a dissonance.) If yet more people start to pick up the same “off” melody, the resulting “dischord” can grow even more noticeable for awhile. But in some cases, so many others adopt the new melody that it can supercede the first one. We hear a lot nowadays about our diversity in culture, our conflicting political parties, and the split in opinions that deeply divide us. These are not subtle differences, and they can tear apart a family, an institution, even a government. Yet, on some level, we are all just trying to sing our song — sometimes following the notes, sometimes riffing on the melody, other times purposely belting out something completely different. It’s all just part of what it means to be a free human being, a member of the chorus, each with our own unique voice. Letters to the editor Readers are encouraged to share their opinion on any matter addressed in the Beacon as well as on political and social issues of the day. Mail your Letter to the Editor to The Beacon, P.O. Box 2227, Silver Spring, MD 20915, or e-mail to barbara@thebeaconnewspapers.com. Please include your name, address and telephone number for verification. Dear Editor: Your September issue contained a travel guide to Myrtle Beach, S.C. Since I was planning a trip there, I read the article carefully. When I arrived, I was amazed at how many restaurants were available. However, for our last dinner, my friend and I ordered a carry-out dinner from Mr. Fish, one of the two places mentioned in the article. Wow! It was delicious, plentiful and a real bargain. My friend commented that we should have eaten there when we first came because we would have had more meals there. When I picked up my meal, I told the cashier that Mr. Fish had been mentioned in your publication. He immediately called over the owner, with whom I had a lovely chat. Love your magazine, by the way. You have many informative articles. Grace Planalp Randallstown BEACON BITS Ongoing MATISSE’S MARGUERITE The Baltimore Museum of Art is presenting a special exhibition of prints, drawings, paintings and sculptures that provide a fascinating glimpse of Henri Matisse’s relationship with his only daughter, Marguerite. On view through Jan. 19, . The museum is located at 10 Art Museum Dr. For more information, visit or call (443) 573-1700. Admission to the Museum is free. BALTIMORE BEACON — DECEMBER 2013 Say you saw it in the Beacon Health Fitness & 3 RAISE A TOAST TO GRAPE JUICE In some ways, grape juice may provide more health benefits than red wine HIGH-DOSE FLU SHOTS The high-dose vaccine for seniors works better than the standard shot SCANS FOR SMOKERS Heavy smokers need yearly CT scans to help detect lung cancer earlier DRUG MUGGERS Many medicines can rob your body of essential nutrients. What you can do The right bacteria might help fight obesity By Lauran Neergaard. The report in the journal Science.’’ Our intestines differ. Some surprising findings adversely affected. However, the fatter mice got the bacterial benefit only when they were fed a lowfat,. — AP Is it viral or bacterial? New test may tell By Lauran Neergaard It happens too often: A doctor isn’t sure what’s causing someone’s feverish illness but prescribes antibiotics just in case — drugs that won recently reported on a study that provided early evidence sam- ples. Hints from our immune systems 102 feverish people who had come to the emergency room — and who See VIRUS TEST, page 5 4 Fitness & Health | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON A toast to benefits of red wine, grape juice The buzz about the benefits of red wine has many of us drinking a glass to good health. And for those who choose not to imbibe, it turns out the booze behind the buzz may not be necessary. Grape juice and dealcoholized wine can offer similar benefits.. Grape juice better in some ways The flavonoid content in grape juice was shown to be similar to that of red wine.. Furthermore,. But red wine has resveratrol. Reprinted with permission from Environmental Nutrition, a monthly publication of Belvoir Media Group, LLC. 1-800-8295384.. © 2013 Belvoir Media Group. Distributed by Tribune Content Agency, LLC. BEACON BITS Nov. 27 HOW TO BE ACTIVE EVERY DAY Attend this discussion at the Seven Oaks Senior Center on how to find more opportunities to be active, as well as exploring the benefits of walking and creating an activity plan on Wednesday, Nov. 27 at 10:45 a.m. The center is located at 9210 Seven Courts Dr. Sign up at the front desk if you plan to attend. For more information, call (410) 887-5192. theatre and demonstration kitchen • Salon • Indoor saltwater pool • Yoga studio & classes • Bingo, and many more planned activities • Movie theatre & Billiards room • Business center – 24 hours • Incredible courtyard and meditation garden with koi pond and gazebo • Guest suites PLANNED ACTIVITIES SUCH AS WATER AEROBICS, RESIDENT MIXERS, COOKING CLASSES, ZUMBA, MOVIE NIGHTS, BBQ’S AND MANY MORE! 3305 Oak West Drive Ellicott City, MD 21043 855.446.1131 Say you saw it in the Beacon | Fitness & Health BALTIMORE BEACON — DECEMBER 2013 Phone (day)_____________________________(evening)_____________________________ E-mail_____________________________________________________________________________ Check the boxes you’re interested in and return this form to: The Beacon, P.O. Box 2227, Silver Spring, MD 20915 or fax to (410) 248-9102. BB12/13 ✃ I N F O R M A T I O N F R E E ★ I N F O R M A T I O N F R E E ★ I N F O R M A T I O N F R E E ★ I N F O R M A T I O N City_________________________________________State__________Zip____________________ I N F O R M A T I O N Address__________________________________________________________________________ F R E E Name_____________________________________________________________________________ ★ ❏ Autism Research Study (see ad on page 13) ❏ Cognition Studies (see ad on page 11) ❏ Coronary Artery Disease Study (see ad on page 12) ❏ Dementia Study (see article on page 12) ❏ Exercise Research Study (see ad on page 12) ❏ High Cholesterol Study (see ad on page 13) ❏ Fall Prevention Study (see ad on page 12) ❏ Weakness Prevention Study (see ad on page 11) I N F O R M A T I O N Health Study Volunteers F R E E ❏ Aigburth Vale (see ad on page 17) ❏ Alta at Regency Crest (see ad on page 4) ❏ Atrium Village (see ad on page 18) ❏ Augsburg Lutheran Village (see ad on page 22) ❏ Bay Forest (see ad on page 29) ❏ Charlestown Assisted Living (see ad on page 26) ❏ Charlestown Independent Living (see ad on page 6) ❏ Charlotte Hall (see ad on page 9) ❏ CSI Affordable Rental Communities (see ad on page 9) ❏ Glen Forest (see ad on page 29) ❏ The Greens at English Consul (see ad on page 26) ❏ The Greens at Logan Field (see ad on page 19) ❏ Green House Residences (see ad on page 27) ❏ Meadows of Reisterstown (see ads on pages 22 & 29) ❏ Neighborhoods at St. Elizabeth (see ad on page 17) ❏ New Life Healthy Living (see ad on page 20) ❏ North Oaks (see ad on page 23) ❏ Oak Crest Assisted Living (see ad on page 26) ❏ Oak Crest Independent Living (see ad on page 6) ❏ Park Heights Place (see ad on page 18) ❏ Park View Catonsville (see ad on page 21) ❏ Park View Dundalk (see ad on page 21) ❏ Park View Rosedale (see ad on page 21) ❏ Park View Taylor (see ad on page 21) ❏ St. Mary’s Roland View Towers (see ad on page 32) ❏ Wayland Village Apartments (see ad on page 23) ❏ Westminster House Apts. (see ad on page 20) ★ F R E E Housing Communities I N F O R M A T I O N Tell them you saw it in the Beacon! complete and clip this coupon and mail or fax it to the Beacon. F R E E Why would a doctor want to know merely that a virus is present and not which virus? That’s enough information to rule out antibiotics, Zaas said. Unnecessary antibiotic use is one factor in the growing prob- For free materials on housing communities and health studies, just ★ Preventing antibiotic resistance MAIL OR FAX FOR FREE INFORMATION I N F O R M A T I O N were eventually diagnosed, the old-fashioned way, with either some type of virus or a bacterial infection. The genomic test proved 89 percent accurate in sorting out who had a virus, and did even better at ruling out those who didn’t, Zaas reported. ★ FREE INFORMATION ★ FREE INFORMATION ★ FREE INFORMATION ★ F R E E From page 3 lem. — AP ★ FREE INFORMATION ★ FREE INFORMATION ★ FREE INFORMATION ★ Virus test 5 6 Fitness & Health | More at TheBeaconNewspapers.com Better brain From page 1 you, you,” said the 51-year-old Fotuhi. It’s also the part of the brain that shrinks with age more than any other. “When you get older, the hippocampus has a tendency to shrink, usually .5 percent each year after 50, which would mean shrinkage of 10 percent in 20 years,” said Fotuhi. And the size of your hippocampus matters. “Changes in its size bring noticeable changes in a person’s memory and cognitive function,” he said. When it comes to peak brain We specialize in short-term rehabilitation and long-term relationships. Mary came to ManorCare Health Service – Woodbridge Valley debilitated from an infection. Mary couldn’t even get out of bed! DECEMBER 2013 — BALTIMORE BEACON performance, bigger is undeniably better. But can natural shrinkage with age be reversed? Yes, Fotuhi said. He pointed to research published a few years ago in the Proceedings of the National Academy of Sciences in which one group of seniors did stretching exercises, while another group walked 45 minutes four days a week, both for a year. MRIs showed that while areas of the hippocampus in the stretchers shrank by about 1.5 percent during that period, those of the walkers increased by about 2 percent, “effectively reversing age-related loss in volume by 1 to 2 years,” the researchers said. Furthermore, the increased brain volume was associated with improved memory function and oxygen consumption in the walkers compared with the stretchers. In a book published in 2008, Fotuhi suggested that a great workout for the brain would be doing the New York Times crossword puzzle daily. He has also recommended that older adults put on their dancing shoes. Dancing is the perfect activity to keep the brain young, Fotuhi said. He told CNN that he began ballroom dancing when he was a student at Harvard Medical School, and that he and his wife Bita have mastered the tango. Dancing, crossword puzzles and other lifestyle changes may sound simple, but they’re based on sound science, Roizen said in an interview. “I think that what Dr. Fotuhi is recom- didn’tknow know She told us ‘Ididn’t what to expect. I’ve never been hospitalized.’ “Everyone was so wonderful. I’m glad I came here.” - Mary 410.821.9600 Roland Park Towson 410.662.8606 410.828.9494 Rossville Woodbridge Valley 410.574.4950 410.402.1200 See BETTER BRAIN, page 7 Life opens up when you’re not weighed down by worries. At Charlestown and Oak Crest, we take care of details like maintenance, security, health care and finances, so you’re free to relax and focus on doing what you love. FREE Call to receive your free Charlestown or Oak Crest brochure or to schedule a visit. For more information, please call the location nearest you or visit: 410.828.6500 Fotuhi stressed that his 12-week program is not in any way akin to the “miracle” cures promised on TV infomercials for various health concerns. Rather, it is an individualized treatment plan with proven results. “I take pride in the fact that 90.6 percent of the patients who have gone through this retirement potential As an added bonus, ManorCare’s exercise regimen jump-started a weight loss which helped her to resolve her diabetes. Mary says, “Thanks to ManorCare, I feel great!” Ruxton How the program works Realize your After our rehab team worked with Mary, she was up on her own two feet, managing all of her own needs and, in no time, was discharged and back to her regular routine. Dulaney mending is something that helps you expand your current brain power. Whether exercise or memory games, his treatment is at the forefront of medicine,” said Roizen, who heads the Wellness Clinic at the Cleveland Clinic and wrote the introduction to Fotuhi’s newest book, published in September. In the book, Boost Your Brain: The New Art + Science Behind Enhanced Brain Performance, Fotuhi calls the hippocampus “the gateway for new memories and essential for learning; as such, it is a major player in the quest for a bigger, stronger brain.” Look at the hippocampus as if it were the brain’s librarian, Fotuhi suggests in Boost Your Brain. “It processes all new information and decides what to keep and what to discard....The good stuff — that which the hippocampus deems storageworthy — is sent to various parts of the cortex for long-term storage.” What is deemed forgettable may be held for a short-time, then is tossed. Charlestown: 1-800-989-6854 Oak Crest: 1-800-339-9326 9631709 Say you saw it in the Beacon | Fitness & Health BALTIMORE BEACON — DECEMBER 2013 Health Shorts High-dose flu shot protects better A new high-dose flu vaccine for seniors works better than the standard shot in that age group, according to a long-awaited study by the vaccine’s manufacturer. Experts say regular flu shots tend to be only about 30 to 40 percent effective in Better brain From page 6 people 65 and older, who generally have weaker immune systems. Sanofi Pasteur’s Fluzone High-Dose vaccine boosted effectiveness Patients meet with a “brain coach” who helps them with tasks to boost memory, including memorizing a list of random items. Neurofeedback therapy — biofeedback applied to the brain using EEG — is also part of the program. Some patients, such as those who had a concussion in the past, require more training than others to enhance their brain function and are offered cognitive training. Stress reduction strategies and meditation are also offered as ways to improve memory and increase brain size. Treatments for sleep disorders and apnea are also available. In Boost Your Brain, Fotuhi said that “with a greater understanding of how to stave off brain atrophy, it’s likely that just as we have experienced an increase in lifespan over the past century, we will see an increase in our ‘brain span’ — the portion of our lives that we live in peak cognitive condition. “Memory, creativity, mental agility — our ability to respond quickly or ‘connect the dots’ — all can be improved with a bigger brain,” Fotuhi said. For more information on the NeurExpand Brain Center, call (410) 494-0191 or visit. See HEALTH SHORTS, page 9 E M ! CO U E YO W TO program have significant improvement of their memories,” he said. ”The one-size-fits-all approach does not work, and we need to assess each person’s current brain health and make a plan with that in mind,” he said. The plan starts with a doctor visit and extensive testing. Among other things, the participants give their health history, get bloodflow exams, physical stress tests and mental memory tests. An EEG (electroencephalography) checks out brain-wave function. After physical and mental habits are assessed, the doctor explains how to immediately embark upon a drug-free personalized treatment program. 7 Don't Let Pain Prevent You From Doing the ings You Love Our wellness practice can alleviate many types of pain and help prevent it from returning. Call (410) 695-6045 for a FREE consult Early a.m. and weekend hours available. Harmonious Living Chiropractic: Fitness & Wellness Center, L.L.C., 8288 Telegraph Road, Suite A, Odenton, MD 21113 •ffanybutler.com That word on the tip of your tongue SM SM Finally, a treatment program that builds your brain’s capacity to resist memory loss and cognitive decline. The early signs of cognitive decline can seem inconsequential. However, the symptoms can be the first indication of more severe problems on the horizon. The NeurExpand Brain Center can assess your risk and create a treatment plan shown to measurably improve memory, focus, and cognitive performance in patients. Developed by renowned neurologist Majid Fotuhi, M.D., Ph.D., this clinical program, covered by Medicare and most insurance plans, is your best chance to ensure that your mind and memory remain sharp. Call NeurExpand today. 1205 York Road, Lutherville, MD 21093 Phone: 410.494.0191 8 Fitness & Health | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Target Pharmacy has you covered. Members of AARP® MedicareRx plans, insured through UnitedHealthcare,® could save on Medicare prescription copays at Target Pharmacy. BALTIMORE BEACON — DECEMBER 2013 Health Shorts From page 7 both, and Sanofi executives say they don’t think cost is a significant deterrent. Instead, they believe doctors have been holding off until they saw real-world effectiveness studies. Small 2014 Social Security increase Social Security benefits for nearly 58 million people will increase by only 1.5 percent next year, the government announced in late October. Social Security pays retired workers an average of $1,272 a month. A 1.5 percent raise comes to about $19. The annual cost-of-living adjustment, or COLA, is based on a government measure of inflation. It is small because consumer prices haven’t gone up much in the past year. The increase is among the smallest since automatic adjustments were adopted in 1975. This year’s increase was 1.7 percent. There was no COLA in 2010 or 2011 because inflation was too low. withholding is also rising.. In some years, part of the COLA has been erased by an increase in Medicare Part B premiums, which are deducted automatically from Social Security payments. But Medicare announced in October that Part B premiums, which cover doctor visits, will stay the same in 2014, at $104.90 a month for most seniors. (Premiums are much higher for those with high incomes.) Medical implants will soon carry tracking codes Federal health regulators will begin tracking millions of medical devices, from pacemakers to hip replacements, using a new electronic system designed to protect patients by catching problematic implants earlier. The Food and Drug Administration published new rules in September that require most medical devices sold in the U.S. to carry a unique code — identifying its Say you saw it in the Beacon | Fitness & Health insur- 9 ers will be able to add the codes to patients’ medical records, helping them quickly identify people who have received problematic implants and devices.. — AP 10 Fitness & Health | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Heavy smokers need yearly lung scans By Marilynn Marchione were taken through the end of August, and the panel is expected to issue its final advice by February. Reports on screening were published in the Annals of Internal Medicine. Gentle Foot Care in Your Home Diabetic foot exams Corns/calluses Wound/infection care Toenail fungus Over 25 years experience Same Day, Weekend and Evening appointments. Most Insurance Accepted g in Heairz Qu Have high blood pressure or diabetes? Hear out of one ear better than the other? Turn the television/radio volume up higher than those around you? Get annoyed because those around you are mumbling? Find that the voices of women and children are harder to understand than men? !Work or have worked in noisy environments? Make inappropriate responses because you have misunderstood what others are saying? !"#$%&"'#()%('*#!#*#+&%,+'(-&+%."-%/(!+%$#01'-)*.% hearing in crowded rooms (like restaurants)? ! ! ! ! ! ! If you answered yes to three or more of these questions, then it’s time for a comprehensive hearing evaluation. Bring this quiz with you on !"#$%#&'$())!*+',-+'$&!$'.('$!"#$("/*!0!1*&'&$2(+$1*3-$ !"$'.-$,!&'$ comprehensive care possible. CALL 410-318-6780 FOR AN APPOINTMENT TODAY! THE HEARING AND SPEECH AGENCY 5900 Metro Drive | Baltimore, MD 21215 410.318.6780 | Free Fitting 3-Year Warranty THE HEARING AND SPEECH AGENCY 410.318.6780 THE HEARING AND SPEECH AGENCY 410.318.6780 ($250 Value) With this coupon. Not valid with other offers or prior purchases. that 10 million Americans would fit the smoking and age criteria for screening. The American Cancer Society (ACS) used to recommend screening with ordinary chest X-rays, but withdrew that advice in 1980 after studies showed they weren’t saving lives. Since then, CT scans have come into wider use, and the ACS and other groups have endorsed their limited use for screening certain heavy smokers. The scans cost from $100 to as much as $400, and are not usually covered by Medicare or private insurers now. But under the new healthcare law, cancer screenings recommended by the task force are to be covered with no co-pays. See LUNG SCANS, page 11 BEACON BITS INSIGHTS ON AGING Join a group discussion at the Bykota Senior on the changes and challenges faced by seniors. The discussion takes place Monday, Nov. 25, from 10 to 11 a.m. The center is located at 611 Central Ave., Towson. For more information, call (410) 887-3094. 6606 Park Heights Avenue Baltimore, MD D O Y O Nov. 25 410-358-0544 Dr. Richard Rosenblatt DPM Recommendation affects millions on all Hearing Aids With this coupon. Not valid with other offers or prior purchases. Nov. 27 BEREAVEMENT SUPPORT GROUP Northwest Hospital offers an ongoing bereavement support group at its Education Center at 5401 Old Court Rd. in Randallstown. The next group will meet on Wednesday, Nov. 27, from 6 to 7:30 p.m. (Except for Nov. and Dec., the group meets on the third Thursday of the month.) Meetings are free, but registration is required. Call (410) 601-WELL. Ongoing HELP A CHILD WITH READING Literacy tutors are needed to improve the reading skills of children in kindergarten through third grade. Volunteers must be at least 55 years old and speak, read and write English fluently. Tutors with this Experience Corps program will complete a 30-hour pre-service training, attend inservice trainings monthly and/or as assigned, and complete a minimum of 450 hours during the school year. For more information, visit. Say you saw it in the Beacon | Fitness & Health BALTIMORE BEACON — DECEMBER 2013 Lung scans From page 10 at 52 and too light a smoker (he reportedly smoked less than a pack a day), to be in the high-risk group advised to get screening. Why screening isn’t for all • those showing a high risk are then directed to have a CT scan. The test is called the PAULA test, which stands for Protein Assay Using Lung cancer Analytes, and is named after the wife of a local physician who died of lung cancer at age 55 only a few months after diagnosis. The test is designed for smokers or former smokers who have at least a 20year history smoking a pack or more a day. Those who get the test should be age 50 or over, without lung cancer symptoms, and not currently receiving annual CT scans. Most insurances and Medicare cover the test, said Cohen. The blood test is done in a patient’s doctor’s office and sent to Genesys’ Rockville lab for analysis. For more information, ask your doctor, see or call (240) 453-6342. — Barbara Ruben !"#$ %&'" (DUO\'HWHFWLRQ6DYHV/LYHV A Simple Blood Test Is Now Available From Your Doctor · · · • low [may] see this as a pass to continue smoking,” Bach said of screening. “I don’t think it’s likely,” because people know how harmful smoking is, he said. — AP !"#$%&'("&%$)$"% The potential benefits of screening may New blood test measures cancer risk A blood test to identify lung cancer risk has recently been developed by a company in Rockville, Md. Genesys Biolabs’ test, the second of its kind available in the U.S., examines a panel of six biomarkers in the blood that are associated with lung cancer. While the test doesn’t diagnose lung cancer, it identifies the risk level for having the disease. “Lung cancer is a silent killer,” said Barry Cohen, product manager for Genesys Biolabs. “The reason so many people die of the disease is that there hasn’t been a good way to identify those with the disease until it’s too late.” While CT scans can help identify those who may have lung cancer, the test is expensive and exposes patients to radiation. If the patient first has the blood test and is found to have a low risk of lung cancer, a CT scan may not be necessary, Cohen said. Conversely, not outweigh its possible harms for people not at high risk of developing lung cancer. A suspicious finding on a scan often leads to biopsies and other medical tests that have costs and complications of their own. Ironically, the radiation from scans to look for cancer can raise the risk of developing the disease. “These scans uncover things, often things that are not important. But you don’t figure that out for a while,” and only after entering “the medical vortex” of fol- For persons age 50 and over that smoked for at least 20 years. Can Identify Lung Cancer at earliest stages when most treatable. Covered by most insurances and Medicare. ASK YOUR DOCTOR ABOUT THIS NEW TEST TODAY! More information for you and your doctor is available online at: Call (240) 453-6342 To receive an info packet by mail Johns Hopkins University investigators seek healthy adults ages 40 and up to participate in research studies designed to investigate ways to improve cognitive abilities. You will be compensated for your time. For more information call: Julia Hernandez (410) 955-7789 Protocol Number: NA_00015657 PI: Barry Gordon, M.D., Ph.D. 11 Approved August 22, 2013 12 Fitness & Health | More at TheBeaconNewspapers.com Health Studies Page DECEMBER 2013 — BALTIMORE BEACON THE PLACE TO LOOK FOR INFORMATION ON AREA CLINICAL TRIALS Understanding the dementia experience By Carol Sorgen Frontotemporal dementia (FTD) is the second most common cause of early-onset dementia. Alzheimer’s disease is the most common. While Alzheimer’s disease occurs most often in the elderly, FTD typically appears between 40 and 60 years of age. FTD also has a strong genetic component, with up to 40 percent of cases linked to positive family histories. Earlier diagnoses and genetic tests mean that people with FTD will spend more years in earlier stages of the disease, aware of the fact that they suffer from this progressive illness. Currently, there are no published studies describing the personal experience or coping styles of individuals with FTD. Researchers at Johns Hopkins University, Columbia University and the University of Pennsylvania are conducting an observational study to interview people with FTD and their caregivers to understand their experiences with the disease. The study, titled “Challenges of Living With Frontotemporal Dementia: The Perspective of the Affected Individual,” is Exercise Research Study Healthy men & women 50-80 years old are needed to participate in an exercise research study at the University of Maryland / Baltimore VA Medical Center. Participation involves medical evaluations, blood draws, fitness tests and 2 weeks of exercise sessions. Compensation for your time is provided. Call 410-605-7179. Mention code EPC-X. sponsored by the National Human Genome Research Institute in hopes that the information collected will help create better treatments and therapies for those affected by FTD. diagnosis must be made by a behavioral neurologist, neuropsychologist, psychiatrist, or a group consensus of any of the above in a specialized dementia center. Caregiver issues addressed In-depth interviews required To accomplish the study’s objectives, interviews will be conducted with 20 to 30 patients with FTD as well as their spouse/partner caregivers. Both sets of interviews will be audiotaped, transcribed and analyzed. Themes emerging in both members of each pair will be compared and contrasted in order to understand the subjective experience of the disease. In a similar study conducted in Great Britain, researchers studied whether or not people with dementia are aware of the level of distress experienced by their caregivers, who often suffer from considerable levels of anxiety and depression. Results showed that people with dementia were aware of their caregivers’ state of psychological health. The researchers concluded that the clinical implications of awareness of caregiver distress in people with dementia should be considered. FTD study participants will be recruited through Johns Hopkins University dementia care centers, private physicians, patient support groups and ClinicalTrials.gov. The Caregivers must be a spouse or partner (non-spouse relatives or friends, healthcare providers, or hired caregivers are not eligible) who provides day-to-day care for the affected individual, and spends a minimum of 16 hours per week, on average in a month, in direct contact with the individual. Participants with FTD will answer questions about their experience with the disease, touching on their mental abilities, challenges and coping strategies. Caregivers will answer questions about their experience in caring for someone with FTD, also talking about their own challenges and coping strategies. They will also be asked about the person with FTD, and how aware they believe the patient is of his or her dementia symptoms. All participants will receive a small gift card as compensation for their time. No treatment will be provided as part of this study. For more information or to volunteer, call Weiyi Mu or Barbara Biesecker at (301) 496-3979. Or email or weiyi.mu@nih.gov or barbarab@nhgri.nih.gov. BEACON BITS Dec. 11 HOW TO BEAT CRAVINGS Once a craving hits, it is tough to get away from it. With all the yummy foods around during the holidays, it’s great to have a tool set up to not only beat the cravings once they hit, but to avoid the craving in the first place. Bring your own tricks and hear more from dietitian Melissa Majumdar at this free event at Sinai Hospital on Wednesday, Dec. 11, from 6 to 7:30 p.m. Meet in the Hoffberger Building, Suite 15 Conference Room, 2435 W. Belvedere Ave. Call (410) 601-0723 for more information. This event is open to the public, but specifically tailored for pre-op and post-op bariatric surgery patients.! Say you saw it in the Beacon | Fitness & Health BALTIMORE BEACON — DECEMBER 2013 13 Consider this before entering clinical trial By Jim Miller Dear Savvy Senior: What can you tell me about clinical trials and how to go about finding one? My wife has a chronic condition, and we’re interested in tr ying. the costs, but not always. • What if something goes wrong during or after the trial and your wife needs extra medical care? Who pays? • If the treatment works, can your wife keep using it after the study? What to ask? • Who’s paying for the study? Will you have any costs, and if so, will your insurance plan or Medicare cover the rest? Sponsors of trials generally pay most of How to find a trial Every year, there are more than 100,000 clinical trials conducted in the U.S. You can find them at condition-focused organizations like the American Cancer Society or the Alzheimer’s Association, or by asking her doctor. Or use the National Institutes of Heath’s website at. This site contains a comprehensive database of federally and privately supported clinical studies in the U.S. and abroad on a wide range of diseases and conditions. You’ll find information about each trial’s purpose, who may participate, locations, and phone numbers for more details. If, however, you don’t have Internet access or could use some help finding the right trial, contact the Center for Information and Study on Clinical Research Participation. This is a nonprofit organization that will take your wife’s information over the phone and do a thorough search of clinical trials for you, and mail or email you the results in a few days. Call 1-877-633-4376 for assistance. You can also find them online at. Jim Miller is a contributor to the NBC Today show and author of “The Savvy Senior” book. 14 Fitness & Health | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Many meds deplete important nutrients By Suzy Cohen Dear Pharmacist: I take a water pill (diuretic) for blood pressure. Now, my doctor says I have to take Boniva for osteopenia. Is there a connection? What’s next for me? — H.J. Dear H.J.: Oh yes,. Often, you’ll find that each drug you take creates a side effect calling for another drug. I’ll share my side effect solutions with you because I realize you have to (or want to) take your prescription medications. You’ve asked, “What’s next for me?” Depending on the specific diuretic you take, Service. Deliver Delivered. FREE prescription delivery EASY prescription transfers ALL major plans accepted Pharmacy Locations: Erickson Retirement Communities: Charlestown Community, OakCrest Village Hospital Locations: Bon Secours Hospital, GBMC, Mercy Medical Ctr, Sinai Hospital, Saint Agnes Hospital, St Joseph Medical Center Medical Office Building Locations: Liberty/BCCC, Owings Mills/Crossroads Med Ctr, Pikesville/Old Court Prof Bldg, Woodholme Med Ctr, Reisterstown / Signature Bldg Steve Neal, RPh NeighborCare® s Liberty/BCCC YOUR FIRST NEW OR TRANSFERRED PRESCRIPTION Present this coupon with your prescription. Limit one per customer. Offer not valid on prescriptions transferred from other NeighborCare locations. No cash value. Per federal law, offer not valid if any portion of prescription is paid for by a government program. Coding: SrB2012 Location: New Customer Existing Customer 410-752-CARE neighborcare.com you may eventually need an antidepressant, something for leg cramps, and maybe tinnitus (ear ringing). You may also need a drug for heart arrhythmias — all just to counter the mineral and electrolyte deficiencies that result from the “drug mugging” effect of drug number 1, your blood pressure drug! Shocked? When side effects due to nutrient depletion by a drug (drug mugging) are not recognized, you’ll get a new ‘disease’ and a new medication for it. This year, an estimated 163,000 people will suffer memory loss (perhaps Alzheimer’s) due to various prescription drugs that mug brain nutrients. About 61,000 people will hear the words “Parkinson’s disease,” but won’t realize it was druginduced. (Rodale 2011) for you, because 75 percent of doctor’s office visits end with the physician giving you a prescription for a medication — and you need me to protect you! I’ll email you a longer version of this article with more side effect solutions if you sign up for my free newsletter at my web- site,. taking information is opinion only. It is not intended to treat, cure or diagnose your condition. Consult with your doctor before using any new drug or supplement. Suzy Cohen is a registered pharmacist, at. BALTIMORE BEACON — DECEMBER 2013 Say you saw it in the Beacon | Fitness & Health 15 Tamp down family feuds at Thanksgiving Dear Solutions: get along, will have some influence on I am in charge of Thanksgiving their husbands. every year, and I always To help your sons-in-law rehave the whole family here. frain from spoiling the day for My two daughters have everyone, I would also sugalways gotten along. My gest that you call each of older daughter remarried them separately and, without this past year, and, unfortaking sides in their argutunately, my two sons-inment, tell them you are countlaw who are in competing ing on them, as you are on businesses are in what I everyone who is invited, to would call a feud about help make the day a success. something that happened. Then put a big sign on your SOLUTIONS When they’re together, By Helen Oxenberg, outside door that they will see they argue constantly over MSW, ACSW as they enter. It should say everything, even the foot“Food, friends, football welball teams they support — and it seems come inside: Feuds must be left on the there’s always a football game to watch doorstep and may, if necessary, be picked during the holiday. My daughters stay up on the way out. No exceptions!!” out of the arguing because they really Dear Solutions: love each other and love to get together. Every time one of my kids or close What can I do about these guys so relatives has a problem and tells me they won’t spoil the day? — Upset about it, I start worrying and can’t stop. Dear Upset: I console them the best I can, and then Uh oh, here comes Thanksgiving, and when I don’t hear from them for a while, here, in your case, come the three Fs — I just keep worrying over and over food, football and feud. about what will happen. The same thing Hopefully your daughters, since they happens when it’s my own problems. How do I stop being a worrier? — Hilda Dear Hilda: OK, so you’re a worrier. First, stop worrying about it. It keeps you from moving on, so accept that about yourself and then focus on what you can do about it. After you’ve consoled your kids and then don’t hear from them, I’ll bet they’ve solved their problem and have moved on, while you leave yourself stuck in the same place. So, until you hear from them again, assume they’ve solved their problem. When you’re stuck worrying about a problem of your own, try removing yourself. Step back and visualize a friend asking your advice about that problem. What would you tell her/him? Also, when you’re feeling very nervous, try deep breathing. Take a deep breath, hold it for a count of four, release it slowly through your mouth and repeat. And each time the worrying starts and you haven’t found a solution, take a time out. Actually say the words out loud — “time out” — and watch a movie, read a book, anything that will engage your mind, After you’ve done all this, please tell me how it has worked. If I don’t hear from you, I’ll worry. © Helen Oxenberg, 2013. Questions to be considered for this column may be sent to: The Beacon, P.O. Box 2227, Silver Spring, MD 20915. You may also email the author at helox72@comcast.net. To inquire about reprint rights, call (609) 655-3684. Please patronize our advertisers. Treating Difficulty Standing or Walking, attributed to Arthritis, Spinal Stenosis, Neuropathy, Poor Circulation or Poor Balance. How fortunate I feel to have found a doctor who could not only diagnose an underlying problem that many specialists missed, but who has been able to find a painless and rapid method of relieving the worst symptoms. – Alvin, Baltimore – Susan, Baltimore As a podiatrist with over 30 years experience, I have always focused on non-surgical treatment of foot and leg pain. I find that most people with foot or leg symptoms (arthritic, aching, burning, cramping or difficulty walking) , even those who have had other treatments, including surgery of the foot (or back), can be helped, usually in 1or 2 visits. Stuart Goldman, DPMYour F eeT.C oM 16 DECEMBER 2013 — BALTIMORE BEACON More at TheBeaconNewspapers.com FLOATING-RATE FUNDS Floating-rate bonds retain their value when interest rates rise, unlike most other bonds Money Law & PASSWORD PROTECTION Several free software programs can help you remember all those passwords you need OBAMACARE SCAMS Watch out for scam artists using the new healthcare law to bilk seniors, including false websites and fake insurance navigators Helping with kids’ and grandkids’ finances By Jill Schlesinger Every few months, I like to empty out the inbox, which has definitely piled up recently. This month and next, I will answer a variety of your questions. As a reminder, if you have a financial question or a comment about a column, send it to: askjill@jillonmoney.com. If you would like to be a guest on my syndicated radio show, call 1-855-411-JILL. Q. I have three young grandchildren, and my broker suggested that I open 529 college savings accounts for them. Although I live in New York, he has recommended a plan from Rhode Island. When I saved for my own kids, I used custodial accounts, so I am not as familiar with a 529. Is there any reason that I would use a Rhode Island 529 versus one from New York? — Delia A. 529 plans are operated through states and allow you to save for higher education in a tax-effective way. Here’s how they work: You invest an after-tax dollar into a 529, and then choose from a variety of investment options, which usually include different kinds of mutual funds. The money grows without any current taxation, and when the child is ready to attend college, it can be withdrawn on a tax-free basis to pay for qualified education expenses. While I agree with the advice to establish a 529 plan as the college savings vehicle, it makes little sense for you to use a plan from Rhode Island. The main reason is that, as a New York resident, you would be missing a great opportunity. Some states, like New York., offer special state tax benefits to residents. New York allows for a state income tax deduction of up to $5,000 per year by an individual, and up to $10,000 by a married couple filing jointly. (Only contributions made by the account owner, or if filing jointly, by the account owner’s spouse, are deductible). [Editor’s Note: In Maryland, each account holder can deduct up to $2,500 of contributions each year per beneficiary. Account owners who are District of Columbia taxpayers may deduct up to $4,000 in plan contributions each year on their D.C. tax return (up to $8,000 for married couples filing jointly, if both taxpayers own an account and make contributions). Virginia 529 account owners who are Virginia taxpayers may deduct contributions up to $4,000 per account per year.] Perhaps you are wondering why on earth your broker would suggest the Rhode Island plan. The most likely answer is that the Rhode Island plan would pay him a commission. You can research 529 plans at. Q. I offered to help my son and his wife with the down payment on their home. When they went through the mortgage application process, the bank asked for my bank statement. Is that customary? I don’t feel comfortable sending the details of my finances. — John A. The mortgage process has changed dramatically since the housing boom and bust. Not only do borrowers have to provide lots of information, but when a gift is involved, the lender is likely to ask for a donor letter/affidavit and could require the donor’s account statements to verify the source of funds. According to mortgage brokers, this new twist has more to do with rules to prevent money laundering than for underwriting purposes. Bottom line: If you want to help your • kids, you need to comply with the new rules. Q. I have run the numbers and have determined that with my pension and retirement savings, I can probably retire as early as age 55, though I was planning to keep working until 59 1/2 so I could tap my 401(k) account without penalties. Recently, a co-worker told me that I could use something called Rule 72-T to get the money earlier. Is that true? — Jerome A. IRS Rule 72(t) allows for penalty-free withdrawals from a retirement account before age 59 1/2, as long as distributions are made as part of a series of substantially equal periodic payments over your life expectancy. The account owner must take at least five substantially equal periodic payments, and the amount depends on the account owner’s life expectancy (as calculated with various IRS-approved methods). If you want to take advantage of Rule 72(t), you must separate from service with the employer maintaining the plan before the payments begin. Keep those questions coming, readers. I enjoy hearing from you! © 2013 Tribune Content Agency, LLC & • –––––––––––––––––––––––––––––––––––––––––––––––––––– Elder Law, Estate & Special Needs Planning Medical Assistance Planning and Eligibility Advance Medical Directives / Living Wills Trusts / Estate Planning Administration Wills / Powers of Attorney Disability Planning / Special Needs Trusts Guardianship 410.337.8900 | | 1.888.338.0400 Towson | Columbia | Easton Say you saw it in the Beacon | Law & Money BALTIMORE BEACON — DECEMBER 2013 17 Investor lessons from the financial crisis We have now passed the fifth anniver- different asset classes, such as stocks, sary of the financial crisis, which tested bonds, cash and commodities. In September 2008, a client every investor in America — shrieked to me that “everything from neophytes to the most is going down!” But that was not jaded traders on Wall Street. exactly the case: this person’s 10 As Chicago Mayor Rahm percent allocation in cash was Emanuel once said, “You just fine, as was her 30 percent never want a serious crisis to holding in government bonds. go to waste. And what I mean That did not mean that the by that is an opportunity to do stock and commodities posithings you think you could tions were doing well, but not do before.” overall, the client was in far While Emanuel was talking about politics, I think we can RETIRE SMART better shape because she owned more than risky assets. apply his statement to in- By Jill Schlesinger 3. Maintain a healthy emergency revestor behavior leading up to and during serve fund. Bad luck can occur at any the financial crisis. With five years of distance from the eye time. One great lesson of the crisis is that of the storm, here is my list of the top five those who had ample emergency reserve funds — six to 12 months of expenses for lessons every investor can take away: 1. Keep cool: There are two emotions those who were employed, and 12 to 24 that influence our financial lives: fear and months for those who were retired — had greed. At market tops, greed kicks in, and many more choices than those who did not. While a large cash cushion seems like a we tend to assume too much risk. Conversely, when the bottom falls out, fear waste to some (“it’s not earning anything!”), takes over and makes us want to sell it allowed many people to refrain from selling assets at the wrong time and/or from ineverything and hide under the bed. If you had sold all of your stocks during vading retirement accounts. Side note: The home equity lines of the first week of the crisis in September 2008, you would have been shielded from another credit on which many relied for emer40+ percent in further losses (stocks bot- gency reserves vanished during the crisis. 4. Put down 20 percent for a morttomed out in March 2009). But how would you have known when to gage (and try to stick to plain vanilla home get back in? It is highly doubtful that most in- loans, like 15- or 30-year fixed rate mortvestors would have had the guts to buy when gages, unless you really understand what it seemed like stock indexes were hurtling you are doing!) Flashback to 2004-’07, and you will liketowards zero! Yet, stocks are now up close to ly recall that you or someone you knew 150 percent since the March 2009 lows. 2. Maintain a diversified portfo- was buying a home or refinancing with lio...and don’t forget to rebalance. One of some cockamamie loan that had “features” the best ways to prevent emotional swings that allowed borrowers to put down about is to create and adhere to a diversified 3 cents worth of equity. There’s a good reason that old rules of portfolio that spreads out your risk across or payday loans, you can stop paying them without filing for bankruptcy. We are celebrating 15 years of helping seniors with their debt without filing for bankruptcy and protecting them from letters and calls from collection agents. You too can live worry-free as thousands of our clients do. Call Debt Counsel for Seniors and the Disabled For a Free Consultation at 1-800-992-3275 EXT. 1304 Founded in 1998 Jerome S. Lamet Founder & Supervising Attorney • Former Bankruptcy Trustee info@lawyers-unitedbased investment for your kid’s college fund, be sure to check out the risk level. Living through a crisis is never easy, so let’s try to at least learn from it! Jill Schlesinger, CFP, is the Senior Business Analyst for CBS News, a former options trader and CIO of an investment advisory firm. She welcomes comments and questions at askjill@jillonmoney.com. © 2013 Tribune Content Agency, LLC It’s Better To Give Than Receive The Neighborhoods at St. Elizabeth has been giving independence and health back to our community members for over 87 years. With such a rich tradition of excellence and a reputation for delivering world class care, it’s no wonder families choose St. Elizabeth for their rehabilitation & nursing care needs generation after generation. Featuring: • Individually tailored, person-directed care • On-site Board Certified Geriatrician • Clinical expertise, comprehensive care, and excellent outcomes (410) 644-7100 3320 Benson Avenue • Baltimore, MD 21227 (410) 644-7100 18 Law & Money | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Got bonds? Consider floating-rate funds By Elliot Raphaelson Bond funds and individual bonds have not done well this year. Many investment advisors fol- lowed this advice would have done well. In 2013, however, most bond investors, especially those with a high proportion of their holdings in long-term or intermediateterm bonds, have seen a negative return. This was so even for investors with holdings in Treasury bonds and investmentgrade bonds. It’s true that investors in high-yield (socalled . Some bonds rise with rates BE H A PP Y T HIS HOL I DAY SE A SON — ON US! are not subject to interest-rate risk. (They are subject to other risks, which I will discuss in a moment.) Therefore, in periods when interest rates are expected to increase, floatingrate.) Still some risks,” See FLOATING RATES, page 19 Sign a lease in November and get ONE MONTH FREE RENT plus our $2000 flex cash gift to you. We would love to welcome you to our community to experience hospitality at its best. Now there is no reason to hesitate. See you soon! 888-840-2214 *Flex cash can be used for downsizing, moving expenses, or future rent. AT ATR IUM V IL L AGE, W E WA N T YOU TO BE H A PP Y. DON’T JUST TA K E OUR WOR D FOR IT, USE OUR GIF T FOR IT. 2,000 $ V I P F L E X C A SH* plus ONE MONTH FREE RENT I N DE P E N DE N T L I V I NG A S S I S T E D L I V I NG | M E MOR Y C A R E 4730 A T R I U M COU R T OW I NGS M I L L S, M D 21117 W W W. S E N IOR L I F E S T Y L E .C OM BALTIMORE BEACON — DECEMBER 2013 Say you saw it in the Beacon | Law & Money 19 Let software remember passwords for you By Jeff Bertolucci Security experts tell us to create long, complex passwords (think numerals and symbols) for every online account. But how are we supposed to remember all of those mind-numbing character strings? Fortunately, there is smartphones Floating rates From page 18 re- “vault.” The program can remember your shipping and credit card information, as well as auto-fill online checkout screens. Dashlane also works within your Web browser to monitor your online activities. When you log in to your online email,. turns. Elliot Raphaelson welcomes your questions and comments at elliotraph@gmail.com. © 2013 Elliot Raphaelson. Distributed by Tribune Content Agency, LLC. BAYADA Home Health Care is available 24 hours a day, 7 days a week. Our thoroughly screened health care professionals provide: UÊ ÃÃÃÌÛiÊV>Ài]ÊVÕ`}ÊL>Ì }]Ê`ÀiÃÃ}]Ê>`Ê}À} UÊ ,i}Õ>ÀÊÛÃÌÃÊvÀÊ>ÊÀi}ÃÌiÀi`ÊÕÀÃi Call 855-807-1085 | bayada.com Compassion. Excellence. Reliability. See PASSWORDS, page 21 This is another top-notch free password manager. Like Dashlane, LastPass () prompts you to create a master password, integrates with the browser, detects when you log in to password-protected sites, and asks whether you want it to remember log-in information. It also generates strong passwords for new sites and auto-fills credit card and shipping information. Unlike Dashlane, BAYADA Home Health Aide Vida Okine with client Virginia S. UÊ i`V>ÌÊ>`Ê>««ÌiÌÊÀi`iÀà from any Web browser. (The downside: You may be uncomfortable with having LastPass Trusted care in the comfort of home UÊ } ÌÊ ÕÃiii«}]Êi>Ê«Ài«>À>Ì]Ê and errands however, LastPass doesn’t rate the strength of existing passwords. LastPass stores your data online, which lets you access your credit card numbers - - 20 Law & Money | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Obamacare scams targeting older adults By Kimberly Lankford Q. I received an email telling me I need to buy a health insurance card that shows I have coverage under Obamacare or I will have to pay a penalty. The email looked legitimate, but it asked for my credit card number. Is it a scam? A. Yes. Although the Affordable Care Act requires people to have health insurance in 2014 or pay a penalty, there is no special card to buy. This is just one of the many ways that crooks are trying to take advantage of misconceptions and misinformation so that they can get your credit card number, bank-account information or cash. Here are a couple of other scams to watch out for: • The Medicare-card scam. The healthcare law will make few changes to Medicare in 2014, but scam artists are invoking Obamacare as a scare tactic. One woman in San Diego received a call from a person claiming to be from Medicare who said she needed a new Medicare card because of Obamacare and asked for her personal information and checking-account number. (He already had her name and address.) The woman was told that her Medicare benefits would stop if she didn’t provide the information. She became suspicious and contacted the California Senior Medicare Patrol, one of 54 programs throughout the country that work with the U.S. Department of Health and Human Services to fight Medicare-related fraud. Not only does the new healthcare law not require you to get a new Medicare or healthcare card, but Medicare will never, ever call you. Instead, like the IRS, Medicare will contact you about any personal issues through the mail. You can call 1-800-633-4227 or go to Medicare.gov for more information, or See SCAMS, page 21 BEACON BITS Ongoing LEGAL SERVICES FOR SENIORS The Legal Services for Senior Citizens Program provides free legal assistance, consultation and/or representation to seniors 60 or older on healthcare issues, income maintenance, nutrition, housing and utilities, protective services and unemployment benefits, and will assist in helping a senior in a lawsuit when there is substantial risk to the client’s person, property or civil rights. Call the Maryland Senior Legal Helpline at (410) 951-7750. Ongoing JEWISH LEGAL SERVICES PROVIDES AID Volunteer lawyers with Jewish Legal Aid Services provide pro-bono legal consultation at a monthly drop-in clinic for Jewish communi- ty members with low income. For more information, contact Jewish Community Services, or (410) 466-9200. Say you saw it in the Beacon | Law & Money BALTIMORE BEACON — DECEMBER 2013 Scams From page 20 contact the Senior Medicare Patrol in your state (). • Fake navigators and exchange sites. The U.S. Department of Health and Human Services awarded $67 million in grants to community organizations to help people sign up for coverage through the new healthcare exchanges (also called marketplaces). Now scam artists are posing as these community “navigators” and saying that they’ll sign you up for coverage if you send them or wire them a few hundred dollars to get started, said Emily Peters, of Patient Fusion, which provides medical records and health spending tools to consumers. Legitimate navigators will not cold-call you or send you an e-mail. To find a legitimate navigator in your area through your state’s exchange, go to the “How do I get help enrolling in the marketplace?” fact sheet at Healthcare.gov or call 1-800-3182596 for more information and resources. Q. Does the new healthcare law prohibit medigap insurers from denying coverage or raising rates because of health? A: No. Even though starting in 2014 most health insurers won’t be able to reject applicants or charge them more because of their health, the new law doesn’t apply to Medicare supplement policies (often called medigap). You can buy any medigap policy regardless of your health within six months of signing up for Medicare Part B. But after that initial enrollment period, insurers can reject you or charge higher rates because of a medical condition. There are some exceptions. For example, you may qualify for medigap coverage without medical underwriting if you are in a Medicare Advantage plan that discontinues operations, or if you move out of that plan’s service area. A few companies will let you switch from one version of medigap coverage to another without new medical underwriting, especially if you’re switching to a plan with more cost-sharing — such as to the high-deductible Plan F or Plan N. If your medigap premiums increase significantly, try applying for a new medigap policy, even if you have minor health issues. It generally takes about 60 days for a medigap policy to go through medical underwriting, but some companies will process the policy in 15 to 30 days, said Eric Maddux, senior Medicare adviser for eHealthMedicare, which provides price quotes and sells policies from many companies.drug coverage from a private insurer. But keep in mind that Medicare Advantage policies tend to have restrictive provider networks (make sure your doctors, hospitals and pharmacies are included), and you could have a tough time finding in-network providers if you travel a lot. They also tend to have more cost-sharing than medigap plans, so while your monthly premiums may be lower, you may have more out-of-pocket costs throughout the year. And if you change your mind later and decide to switch back from Medicare Advantage to a medigap plan, you could be rejected because of your health. Kimberly Lankford is a contributing editor to Kiplinger’s Personal Finance magazine and the author of Ask Kim for Money Smart Solutions (Kaplan, $18.95). Send your questions and comments to moneypower@kiplinger.com. © 2013 Kiplinger’s Personal Finance Passwords From page 19 your sensitive personal data stored in the cloud.) The app also supports Google Authenticator. Keeper If all you want is a free password manager and little more, Keeper () is appealing. Like its competitors, the app uses bulletproof AES-256 encryption. The app supports two-step verification, but it doesn’t rate the strength of your passwords. Jeff Bertolucci is a freelance writer for Kiplinger’s Personal Finance magazine. © 2013 Kiplinger’s Personal Finance BEACON BITS Ongoing ENERGY NewBegins Here Your Lifestyle APARTMENT HOMES FOR THOSE 62 AND BETTER! Ask about our Smoke Free Communities DESIGNED AND MANAGED FOR TODAY’S SENIORS AT THESE LOCATIONS: ASSISTANCE ANNE ARUNDEL COUNTY EASTERN SHORE FORMS AVAILABLE • Furnace Branch 410-761-4150 • Easton 410-770-3070 Do you want to save money on your • Severna Park 410-544-3411 HARFORD COUNTY BG&E bill? Energy Assistance forms BALTIMORE CITY • Bel Air 410-893-0064 are available on the Resource Wall at • Ashland Terrace 410-276-6440 • Box Hill 410-515-6115 the Arbutus Senior Center, 855A • Coldspring 410-542-4400 HOWARD COUNTY Sulphur Spring Rd. or call BGE at 1- BALTIMORE COUNTY 800-685-0123. • Catonsville 410-719-9464 • Columbia 410-381-1118 • Dundalk 410-288-5483 • Ellicott City 410-203-9501 Ongoing HAVE A WILD TIME AT THE ZOO *Newly Renovated! • Colonial Landing 410-796-4399 * Fullerton 410-663-0665 *Newly Renovated! • Ellicott City II 410-203-2096 • Miramar Landing 410-391-8375 • Emerson 301-483-3322 imals may seem like the only glam- • Randallstown 410-655-5673 • Snowden River 410-290-0384 orous job, but volunteers at the Balti- * Rosedale 410-866-1886 more Zoo can be superstars by doing • Taylor 410-663-0363 * Bladensburg 301-699-9785 all sorts of work, from keeping gar- • Towson 410-828-7185 • Laurel 301-490-1526 dens beautiful, to helping zoo staff • Woodlawn 410-281-1120 • Laurel II 301-490-9730 Taking care of the an- stay ahead of the paperwork, to leading tours or more. To learn more, email volunteers@marylandzoo.org or call (443) 552-5266. *Newly Renovated! 21 PRINCE GEORGE’S COUNTY Call the community nearest you to inquire about eligibility requirements and to arrange a personal tour or email parkviewliving@sheltergrp.com. Professionally managed by The Shelter Group. • 55 or BETTER! 22 More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Does your organization use senior volunteers or do you employ a number of seniors? Careers Volunteers & If you do and you’d like to be considered for a story in our Volunteers & Careers section, please send an email to info@thebeaconnewspapers.com. Volunteers help turn vets’ lives around generations of veterans haven’t had it any easier, said Erbe, and among the general public, there doesn’t seem to be much awareness of what these former soldiers have gone through — and continue to go through once they return home. That’s where the Baltimore Station comes in. Over the past 25 years, the organization has transformed from a small group of citizens who assisted the homeless in South Baltimore into a 144-bed therapeutic residential treatment program. Combating PTSD About 80 percent of the residents are veterans, and many of them suffer from the effects of combat, including post-traumatic stress disorder. They often turned to drugs to cope with the trauma they experienced. “The cycle can spin out of control, leading to poverty, estrangement and homelessness,” said Erbe, who notes that her own brother-in-law suffered from the early stages of PTSD when he returned from Vietnam. It takes a highly structured environment to break that cycle, and most of the THE STATE’S BEST RETIREMENT LIVING VALUE! Discover An Attractive, Attentive, Attainable Retirement Lifestyle staff at the Baltimore Station are in recovery themselves; half are also veterans. They like to say that recovery is not a “quick fix,” but “a long, tough war.” In the first month of the 18month program, residents learn to “sit still.” They attend counseling sessions, drug and alcohol education, and acupuncture treatment to assist with withdrawal symptoms. In months two to six, they focus on life skills such as job readiness, budgeting, education and household responsibilities. Months six to 12 are a transition period, during which residents are allowed to live with minimal superviSee BALTIMORE STATION, page 23 PHOTO COURTESY OF SANDRA ERBE By Carol Sorgen Sandra Erbe was unfamiliar with the Baltimore Station until two years ago, when she was asked to donate one of her paintings to the organization’s annual “restART with ART” fundraising event. Now Erbe is the volunteer chair of the nonprofit’s fund development and communications committee, spending about 10 hours a month in support of its mission to “turn lives around.” The Baltimore Station is a therapeutic residential treatment program supporting veterans and others who are committed to moving from poverty, addiction and homelessness to self-sufficiency. (Of the 408,000+ homeless in this country, approximately 35 percent are veterans.) In addition to being a contemporary abstract artist, Erbe professionally serves as director of marketing and communications for Habitat for Humanity of the Chesapeake. She prefers not to give her age, but does have vivid memories of Vietnam veterans returning home, and the lack of respect with which they were met. “I didn’t support the war, but I always respected our veterans,” she said. Future Sandra Erbe volunteers with the Baltimore Station, a residential treatment program for veterans who are homeless and/or addicted to drugs. The nonprofit organization is seeking volunteers to help with an array of jobs, from carpentry to fundraising. MOVE IN BY END OF THE CURRENT MONTH AND GET A 32” FLAT SCREEN TV In the pages of your FREE Retirement Kit, you’ll find that Augsburg Village is an active, friendly community with a bustling Town Center at its heart. You’ll see that our roomy apartments have a patio or balcony, so that you can better enjoy our picturesque setting and lovely manicured grounds. Best of all, you’ll learn that we have a state-of-the-art healthcare center enter ... and that our friendly, friendl d y, dedicated edd staff offer a full continuum of care in a truee non-profit, non-profift, faith-based faith-bbas ased e environment. ed env n ironmeent nt.. - Call 443-379-4930 to ask for your FREE Augsburg Village Retirement Kit. Augsburg village Attractive • Attentive • Attainable Senior Living by Lutherans for all 6825 Campfield Road Baltimore, MD 21207 $99 $0 Security Deposit Application Fee 300 Cantata Court • Reisterstown, MD 21136 Say you saw it in the Beacon | Volunteers & Careers BALTIMORE BEACON — DECEMBER 2013 Balitmore Station From page 22 sion, go to school or work, apply life skills, save money, repair relationships, incorporate relapse-prevention strategies and mentor others. Finally, after 18 months in the program, most residents are living independently, employed and/or enrolled in college. The program has many success stories to its credit. Take Paul, who now works as a therapy case manager — and role model — for other residents at the Baltimore Station. For 33 years, drugs ruled Paul’s life. Although gainfully employed as a chef for more than two decades, the bulk of his salary went toward buying and using drugs, a lifestyle that took a toll on his health, eventually leading him to undergo open-heart surgery. While hospitalized, Paul was evicted from his home and returned to find his possessions on the curb. When he saw his birth certificate floating down the street in the pouring rain, he realized it was time to change. Since entering the program, Paul returned to school, earned his GED, graduated summa cum laude with a BS in addictions counseling, and earned a master’s in education from Coppin State University in 2012. He is a member of Chi Sigma Iota, Psi Chi and Pi Gamma Mu honors organizations and was awarded the Rehabilitation Counseling Program Award (2013) and Dean of Graduate Studies Award (2013) for his academic accomplishments. “The Baltimore Station taught me to take personal responsibility for my life and to change my life,” Paul said. The Baltimore Station has an ongoing need for volunteers who can help in a number of ways, such as sharing their talents and skills. For example, experienced painters and carpenters are needed to keep the facilities in top shape for residents, graphic designers to assist with creating promotional materials, and experts to lead educational sessions with its residents. Other volunteers may host a fundraising event at their church, school, business or social club. Some — like Erbe — serve on a committee (in addition to fund development and communications, there is an events committee and a facilities committee), while others serve and supply meals or offer expertise in counseling, health-related issues, education and spiritual en- “Your roadmap to the right health care is me.” I’m here for you. ACT LOCALLY AND MAKE A DIFFERENCE GLOBALLY Diane Witles, R.N., health care navigator, has been helping residents of Ten Thousand Villages at 1621 Thames St. is looking for individuals who are supportive of fair trade and interested in assisting artisans in other countries. Volunteers work in the retail store to explain the mission of Ten Thousand Villages to customers, arrange merchandise, restock, clean, unpack shipments, greet customers and assist them in making their selections. Volunteers are asked to assist for 4 hours at a time. For more information, visit. Ongoing North Oaks live independently for as long as they can since she started here 22 years ago. Like other staff, she knows everyone by name – and most of their family members as well. If someone needs medication reminders, immunizations or consultation with a physician, they turn to her. Diane is often the first to pick up on a resident’s changing health needs. Perhaps you should be living at the address where she works. ACTIVITY VOLUNTEERS SOUGHT AT CHARLESTOWN Spend time assisting residents in Charlestown’s skilled nursing and assisted living facilities with various activities such as bowling, bingo, crafts, storytelling, cards, checkers and more. Charlestown is located at 715 Maiden Choice Ln. in Catonsville. For more information, visit or call (800) 917-8649. could I not help?” For more information on volunteer opportunities at the Baltimore Station, call (410) 752-4454. Many volunteer needs BEACON BITS Ongoing richment. Of her decision to become a volunteer with the Baltimore Station, Erbe said, “With such a compelling mission, how When you live in this senior living community, you’ll enjoy a close connection with staff members whose work and wishes are to connect you to the best in life. Please call (410) 486-9090 to learn more. 725 MOUNT WILSON LANE 23 PIKESVILLE, MARYLAND 21208 (410) 486-9090 V i s i t o u r w e b s i t e a t w w w. N o r t h O a k s LC S . c o m 24 Volunteers & Careers | DECEMBER 2013 — BALTIMORE BEACON 014331RXX11 BALTIMORE BEACON — DECEMBER 2013 Say you saw it in the Beacon Travel 25 Leisure & Things you need to know before renting a car in Europe. See article on page 27. Voluntourism makes for trips of a lifetime across volcanic crevices, fought off ticks and other clingy critters, been “decorated” with soupy loon feces, evaded hippopotamuses in the moonlight, sweltered under the Grecian sun, and had an infected toenail treated atop a trashcan at a clinic in African bush country. To me, these were challenging, mindexpanding adventures, and many were trips of a lifetime. PHOTO BY DUSTIN ENGLEHARDT By Glenda C. Booth “Pardon me. You did what?” asked an incredulous friend. “I caught crocodiles,” I replied coolly, when asked about my two-week Earthwatch volunteer expedition studying the Nile crocodile in Botswana’s Okavango Delta. And that’s just one of many things I have done on vacation. I have: • Filmed young marmots frolicking in the French Alps; • Identified dolphins by their dorsal fins’ nicks and streaks in Greece’s Amvrakikos Gulf; • Yanked invasive vines from an ancient heiau (temple for women) on Maui; • Helped band loons wintering in the Gulf of Mexico; • Weighed migrating shorebirds on Delaware Bay; • Mapped and macheted invasive plants in the Galapagos Islands; and • Cleared trails on St. John’s in the Virgin Islands National Park. I’ve tangled with prickly briars, tiptoed Volunteer vacations PHOTO COURTESY OF GLENDA C. BOOTH Some call it voluntourism, volunteering for conservation or another cause while vacationing. Others dub it eco-immersion or “citizen science.” Usually, it involves traveling outside one’s home area and working with a group under the leadership of a scientist or other expert. Most projects do not require subjectmatter expertise, as leaders train volunteers on-site. It’s travel with a purpose, and service without pay. There’s usually little time to read a book, sip margaritas, or lounge in a beach chair. Senior volunteering is rising and is now at a 10-year high, with one in three people over age 55 volunteering in the U.S. or elsewhere. “More than 20 million senior volunteers gave nearly three billion hours of service, at a value of $67 billion,” announced the Corporation for National and Community Service (CNCS) in May. A 2008 CNCS study reported that more than 1 million people volunteered overseas. Making a difference The author, Glenda C. Booth, films marmots in the French Alps, on an Earthwatch project. Most people say they volunteer for conservation and similar projects to do something meaningful, to make a difference. Conservation-oriented organizations promote a healthier planet, a more sustainable environment. Earthwatch volunteers, for example, often help scientists collect data that informs public policy and advances science. Vermonter Victoria Kohler, who has gone on 15 Earthwatch volunteers near the Arctic Circle in Canada use ground-penetrating radar to collect data on permafrost and soil for climate change research. An increasing number of older adults are taking part in volunteer vacations, which offer unique experiences and allow them to help the environment and communities around the world. Earthwatch expeditions, commented, “I really enjoy working with animals, and hope that my efforts will help further knowledge about them and maybe even help save them from decline or possible extinction.” Part of a conservation project’s mission might be to help people who live near the project site. Claudia Seldon, an Earthwatch volunteer and retired nurse from Detroit, Mich., said, “I’ve always enjoyed meeting with local people. It’s different from traveling as a tourist. I enjoy giving back to society.” Conservation projects are usually in outdoor settings — nature’s classrooms — in all kinds of weather. Many projects are in remote locations. That attracts Kohler. “It gets me to unusual and interesting places where the average tourist does not go,” she said. Many volunteer projects are rich learning experiences. Volunteers gain new knowledge, such as learning about animals and plants, and master new skills, like using GPS systems or tools. They often hone their observation skills. For some, volunteering abroad allows them to brush up on a foreign language. On his fifth Earthwatch expedition studying loons wintering in Louisiana, Ron LeMahieu said, “I do it because I’m a frustrated field biologist. Holding a loon is like holding the wilderness in your arms.” Volunteering abroad can also enhance your understanding of world events, generate insights into cultural values and assumptions, and can bolster respect for differences. Volunteer vacations appeal to many people who love to travel but do not have a compatible or willing traveling companion. Usually, others on the project are likeminded and may be of a similar age. The other volunteers wouldn’t be there if they did not have common interests. Because projects are often “away from the headlines” and are hands-on and in the field, they are a healthy respite from the Internet, email, cellphones, television and other technological trappings of today. Bottom line: They enrich your life. Tips for choosing trips Extended volunteering requires thoughtful planning. “A lot of pitfalls can be avoided when people research their volunteer opportunities well. It helps set the See VOLUNTOURISM, page 26 Leisure & Travel | More at TheBeaconNewspapers.com Voluntourism From page 25 volunteers’ expectations,â€? said Genevieve Brown, executive director of the International Volunteer Programs Association. “Traveling to another country, people will experience some level of culture shock, so it is important to eliminate a lot of the unknowns that can surround a volunteer placement,â€? Brown added. Here are some tips: • Understand the physical requirements, and assess your capabilities realistically. Projects may require backpacking, walking in muck or over treacherous terrain, standing for extended periods or steady on a boat, getting in and out of boats, and lifting heavy equipment. Can you tolerate weather extremes, very hot or very cold weather? • Determine your minimal requirements for sleeping arrangements. Expect few frills. You may sleep on the ground, on cots, and in sleeping bags, tents or dormitories and you’ll likely have a roommate. • Understand meals. Explain your food preferences and allergies ahead of time. You may have kitchen duty. • Decide if one, two or more weeks are desirable. Weather can reduce the number of work days, but there may be indoor work too, such as typing data into a computer. • Understand the costs. Most likely, you will have to pay for your transportation to and from the site. Understand what’s included in the organization’s price. Clarify what expenses, if any, are tax deductible. • Understand the insurance provided to volunteers by the sponsoring organization. Consider travel insurance and extra health insurance if leaving the U.S. DECEMBER 2013 — BALTIMORE BEACON • Don’t expect healthcare facilities, medicines or medical personnel like those you have in the U.S. • Pay close attention to the list of supplies recommended. Some projects require specialized gear, like headlamps for night work. Take every item recommended and don’t over pack, expecting porters. You’ll likely have to lug everything yourself. • Don’t expect much privacy or free time. While there’s always some “down time,â€? generally, your time will not be your own. • If traveling abroad, learn about the country beforehand — its governance, politics, cultural factors and restrictions based on age, gender, gender identity, race, ethnicity, sexual orientation and religion. The sponsoring organization can likely connect you with someone who has been there. • Don’t expect to save the world. “I think the biggest pitfall for people is expecting to change the world in the time of their volunteer placement,â€? Brown said. “Volunteers should go into their placement with the attitude of service, but also open to learning and striving to understand. “The greatest benefit from volunteer service is the bridge of cross-cultural understanding,â€? she observed. Plan thoughtfully not for everybody. A woman whose husband of 30 years asked for a divorce signed up for a trip to Ecuador to “get away,â€? but spent much of the two weeks dysfunctional and grieving. Another failed to bring strong hiking boots and twisted her ankle the second day, disabling her and confining her indoors for most of the project. Most volunteer travel experiences require a tolerant, patient, flexible attitude. Once there, it’s usually hard to leave, so you have to “stick it out,â€? whatever the circumstances. To help you make informed decisions about volunteering abroad, check out or. Most of all, volunteer travel requires a curiosity, a willing spirit and an open mind. You might learn something new about yourself. For many people, it is transformational. Wit Ostrenko, president of the Museum of Science and Industry in Tampa, Florida for the last 24 years, found volunteering on Earthwatch’s Gulf of Mexico loon project had a profound impact on him. “This expedition was humbling for me, and it changed my life,â€? said Ostrenko. “Being part of the Earthwatch volunteer team allowed me to be a scientist again, and it changed my life as a science center While many volunteers come home raving about the experience of a lifetime, it’s See VOLUNTOURISM, page 27 MOM STAYS SAFE & HAPPY with Nursing Care at Charlestown and Oak Crest Let her know she taught you well. Choose Nursing Care at Charlestown or Oak Crest and give your mom the advantages she deserves: t 0OTJUF GVMMUJNFQIZTJDJBOT BOEOVSTFQSBDUJUJPOFST t "QSJWBUFSPPNGPSDPNGPSU and dignity t & YDFQUJPOBMDBSF FWFOJGTIF is not a Charlestown or Oak Crest resident For more information, call for your free brochure today. Charlestown Oak Crest Catonsville, MD Parkville, MD 410-737-8922 410-882-3295 EricksonLiving.com 9296616 26 BALTIMORE BEACON — DECEMBER 2013 Say you saw it in the Beacon | Leisure & Travel 27 How to rent a car and drive it in Europe By Ed Perkins or impossible if you’re over 70. If you’re OK to drive at home — really OK, not just barely making it — you should be OK to drive in Europe. Just make a few adjustments. What to rent Voluntourism servation) • Cross-Cultural Solutions, • Idealist, • Passport in Time, USDA Forest Service, • Wilderness Volunteers, For more organizations offering a range of volunteer opportunities abroad, visit. To learn about traveling with minimal impact on the environment or cultures, visit. Glenda C. Booth is a travel writer in Alexandria, Va. From page 26 president. I was reminded that it’s the doing that matters, not the talking and the showing.” The following organizations offer volunteer travel opportunities: • Earthwatch, • Sierra Club, outings • Road Scholar, Service Learning, • World Wide Opportunities on Organic Farms, • Biosphere Expeditions (wildlife con- price premium on a smaller car. Now, however, even European secondhand car buyers want air conditioning, so you find it in most cars — even in compacts — in most central and southern Eu- ropean countries. Get a diesel, if you can; the fuel is usually cheaper, and you get fantastic mileage. Unfortunately, many companies won’t promise a diesel, but diesels do make up a big percentage of their fleets. Weigh where to rent You’re going to drive through Austria, so you rent in Austria, right? Not necessarSee RENT A CAR, page 29 You deserve to be by the glow of a cozy hearth and in the comfort of a warmly appointed private room especially when you’re in need of rehabilitation or nursing care. Discover The Green House Residences at Stadium Place where boutique care and comfortable amenities come together. • Private rooms with private European-style bathrooms • Homemade meals with personalized dining options • State of the art technology to maximize mobility & safety • Beautifully maintained open air spaces overlooking the Cal Ripken Youth Development Park (former site of the Memorial Stadium) (410) 554-9890 1010 E. 33rd Street, • Baltimore, MD 21218 (410) 554-9890 28 Leisure & Travel | More at TheBeaconNewspapers.com DECEMBER 2013 — BALTIMORE BEACON Say you saw it in the Beacon | Leisure & Travel BALTIMORE BEACON — DECEMBER 2013 Rent a car From page 27 ily. better place to rent than, check the website for country-by-country price variations. Where to stay BEACON BITS Dec. 8 WASHINGTON HOLIDAY CONCERT Join Senior Box Office as it travels to Washington, D.C., on Sunday, Dec. 8, for a holiday concert by the U.S. Army Band at DAR Constitution Hall with lunch at Pier 7. Tickets are $65. For reservations, call (410) 882-3797. Dec. 9+ PLAY AND SHOP IN DOVER, DELAWARE Victory Villa Senior Center invites you to enjoy Dover Downs, shopping at Christiana Mall, and Delaware Park Casino on Monday and Tuesday, Dec. 9-10. Cost is $139/double. Reserve a spot by calling (410) 887-0235. Dec. 11 some mistakes. No mat- 29 ter how skilled a driver you are, driving in Europe is different from driving at home. You will make mistakes — take wrong turns, head into the wrong lanes and such. I find, especially, that it’s all too easy to find yourself. Send e-mail to Ed Perkins at eperkins@mind.net. Perkins’ new book for small business and independent professionals, “Business Travel When It’s Your Money,” is now available through or. © 2013 Tribune Content Agency, LLC. CHRISTMAS IN LANCASTER See the Christmas Show at American Music Theatre, with a visit to the National Christmas Center and lunch at Good and Plenty in Lancaster, Pa., on Wednesday, Dec. 11. The trip is hosted by Seven Oaks Senior Center and is $90 per person. Call (410) 887-5192 for reservations. Dec. 20 IT’S A SWEET TRIP TO HERSHEY Join the Edgemere Senior Center on Friday, Dec. 20, for a guided tour of Hershey, Pa., including the Milton S. Hershey School, time on your own at Chocolate World, a ride through Hershey Sweet Lights, attendance at a Christmas show and lunch, all for $95 per person. Call (410) 477-2141 to reserve a spot. The Meadows of Reistertown offers the maintenance-free, independent lifestyle you’ve been looking for in a retirement community. • Social, Educational and Recreational Events • Patios or Balconies • Individual Climate Control • Convenient to Shopping, Banking and Restaurants LESS INVASIVE. E.* MORE APPEALING. KEEP UP TO 75 % OF YOUR HEALTHY KNEE.* Say this apple represents your knee. With total knee replacement, the entire surface has to be removed. But with the Oxford® Partial Knee from • Emergency Response System • Controlled-Access Entry • Hair Salon • Elevators • Smoke-Free • Small Pets Welcome Live the carefree life you’ve been waiting for, and let us take care of all the details! For more information, call 410-526-3380 Biomet, you can keep up to 75% of your healthy knee – for a more rapid recovery with less pain and more natural motion.* And now, the Oxford® is available with Signature™** personalized implant positioning. It’s the knee replacement technique that’s based on your#2/(*$7*#)+)-!1 8#9$!1(-#)02!# gives you the industry’s only Lifetime Knee Implant Replacement Warranty† in the U.S. Now that’s appealing. 300 Cantata Court • Reisterstown, MD 21136 ® 800.851.1661 I oxfordknee.com Risk Information: Not all patients are candidates for partial knee replacement. Only your orthopedic surgeon can tell !"#$%# !"&'(#)#*)+,$,)-(#%!'#.!$+-#'(/0)*(1(+-#2"'3(' 4#)+,#$%#2!4#56$*6#$1/0)+-#$2#'$36-#%!'# !"'#2/(*$7*#. Potential risks include, but are not limited to, loosening, dislocation, fracture, wear, and infection, any of which can require additional surgery. For additional information on the Oxford® knee and the Signature™ system, including risks and warnings, talk to your surgeon and see the full patient risk information on oxfordknee.com and. cfm?id=2287&rt=inline or call 1-800-851-1661. Oxford® and Signature™ are trademarks of Biomet, Inc. or its subsidiaries unless otherwise indicated. * Compared to total knee replacement. Refer to references at oxfordknee.com. ** A collaborative partnership with Materialise N.V. † Subject to terms and conditions within the written warranty. 930 Bay Forest Ct. • Annapolis, MD 21403 410-295-7557 7975 Crain Hwy. • Glen Burnie, MD 21061 410-969-2000 30 DECEMBER 2013 — BALTIMORE BEACON More at TheBeaconNewspapers.com Style Arts & A festive Lincoln is part of a Civil War Christmas music show at Center Stage. For more information on this and many more holiday events, see story on page 31. A new Baltimore poet finds her voice While the slim volume of verse is Amour’s first written publication, she has also previously released two spoken word CDs, “Love’s Journey” and “ilovemesomewords.” “My true love, though, is the written word,” she said, adding that while she’s “pausing” now between projects, she hopes to write other books in the future, including a guide to self-publishing and a book of short stories. A poetic memoir Free to Be Me explores Amour’s geographical and emotional journey from childhood to adulthood, and from the Caribbean, where she was born, to Canada, Detroit and now Baltimore. The poems deal with both feelings of abandonment and the personal remedies she has developed through the years for healing. Amour’s poems tell her stories of being separated from her parents when she was just two years old. They moved to England for their education, leaving Amour and her siblings with their grandparents, returning to them six years later. “They had a good reason for leaving,” said Amour, explaining that educational opportu- A Season of Hits at Toby’s Dinner Theatre! OPENING NOVEMBER 15 Just in time for the Holidays! nities were not readily available in the Caribbean. “But still, for six years I didn’t have my parents. “I was inspired to begin writing this poetic memoir shortly after my mother’s passing,” said Amour, “particularly because we had worked through many of our mother/daughter issues caused by my feelings of abandonment. “It took years for me to fully accept my parents’ reasons for making difficult life choices, and many more years for me to forgive and heal. I hope my book will give readers a point of reference for their own journeys.” Her poetry also helped Amour cope with the loss of her sister in 2004 from lupus-related complications. When her sister died, Amour, who had always sought her advice when it came to love Cherrie Amour recently published her first book and relationships, was left again of poetry at age 50. Her poems focus on loss, separation and her family. without a confidante. “The writing has been therabe made up primarily of women, she’s depeutic for me,” she said. And apparently to others as well, said veloping quite a male following as well, Amour, who relates that people who have with one man telling her that it’s not often come to her author appearances have told men can find out what women are thinking her that through her writings they have in a “non-combative” way. “A lot of men say they’re buying the felt empowered to confront some of their book for their girlfriends or wives,” Amour own challenges. said, clearly pleased at this unexpected PHOTO COURTESY OF CHERRIE AMOUR By Carol Sorgen At the age of 50, Cherrie Amour feels that she is finally finding her creative voice, and it has resulted in the release of her first book of poetry, Free to Be Me: Poems on Life, Love and Relationships. “It’s a little scary to be doing this at this stage of life,” said the Mount Vernon resident, a public relations practitioner by profession, “but maybe I’m finally getting my courage up.” Amour, born Cherrie Woods, was first given the moniker that has turned out to be her nom de plume by her mother. The name is a take on the 1969 Stevie Wonder song, “My Cherie Amour.” Amour is also the French word for love, which is the focus of much of her writing. Fascinated by the written word, Amour said she’s an avid reader and has been keeping written journals since she was in high school. Indeed, there were so many journals that when she moved to Baltimore from Detroit five years ago to take a position with the Reginald F. Lewis Museum (she now works for Baltimore City), she decided it was time to thin out the collection a bit —though she continues to add to it anew. Appealing to men and women While Amour expected her audience to 2014 SUBSCRIPTION PACKAGE • $159 for 4 Tickets - Dinner & Show Coupon book which includes one FREE adult admission. Good for the first two weeks of the five 2014 shows...plus many more money saving coupons Holiday Gift Certificates (Valid 1/2/2014 until 3/2/2014) Children's Gift Certificates & Custom Gift Certificates See POET, page 33 Cars, boats, furniture, antiques, tools, appliances Everything and anything is sold on 1/11/14 - 3/23/14 3/28/14 - 6/22/14 6/26/14 - 8/31/14 9/5/14 - 11/9/14 11/14/14 - 2/22/15 TOBY’S DINNER THEATRE OF COLUMBIA • CALL 410-730-8311 Based on availability. Due to the nature of theatre bookings, all shows, dates and times are subject to change. D in TobysDinnerTheatre.com ner & S h o w RESERVE YOUR SEATS TODAY! Radio Flea Market Heard every Sunday, 7-8:00 a.m. on 680 WCBM Say you saw it in the Beacon | Arts & Style BALTIMORE BEACON — DECEMBER 2013 31 Theater, music highlight holiday season By Carol Sorgen From musical concerts to theatrical productions, Baltimore’s performance venues take on a holiday air this time of year, so take out your calendar and start making plans. It’s going to be a busy season! “A Civil War Christmas: An American Musical Celebration” Tuesday, Nov. 19 through Sunday, Dec. 22 CenterStage, 7 N. Calvert St. Pulitzer Prize-winning playwright Paula Vogel looks at Christmas from the longago vantage point of the Civil War in a musical production that, in the spirit of the season, centers on hope and forgiveness. On a frigid Christmas Eve in 1864 all along the Potomac, from the White House to the battlefields, friends and enemies alike find their lives intertwined. Through both traditional carols and folk songs, this is, according to the New York See HOLIDAY, page 32 PHOTO COURTESY OF THE BSO Tickets Make A Great Gift Cirque Musica performs acrobatics while the Baltimore Symphony Orchestra plays holiday favorites at the Meyerhoff Symphony Hall Dec. 11 to 15. DECEMBER 12TH MARCH 4TH & 5TH Talking on the phone can be easy again. You have our word. Using voice recognition technology, a Captioned Telephone operator makes it possible for you to receive on-screen captions of what your caller says as you listen. You may qualify for a Captioned Telephone, amplified phone, or other devices through the Maryland Accessible Telecommunications program at no cost. To learn more, visit mdrelay.org or call 1-800-552-7724 (Voice/TTY). Captioned Telephone from Maryland Relay R55Word-for-word captions R55Easy-to-read display R55Simple to use MAY 28TH - JUNE 1ST 410-547-SEAT MODELL–LYRIC.COM For tickets visit the Modell Lyric Box Office (M-F 10a-4p). 32 Arts & Style | More at TheBeaconNewspapers.com Holiday From page 31 Times, a “beautifully stitched tapestry of American lives.” Elf the musical Friday, Nov. 22 through Sunday, Nov. 24, various show times Patricia & Arthur Modell Performing Arts Center at the Lyric, 140 West Mt. Royal Ave. You’ll want to take the little ones to this holiday-themed musical. Elf is the entertaining story of Buddy, a young orphan who crawls into Santa’s bag of gifts and is transported to the North Pole. When his enormous size and poor toymaking abilities make him realize he’s only human, Buddy sets off to New York City to find his birth father and discover who he truly is. When he discovers that his father is on the “naughty,” not “nice,” list and that his step-brother doesn’t even believe in Santa, Buddy vows to win over his new family and help New York remember the true meaning of Christmas. Irving Berlin’s White Christmas Tuesday, Dec. 3 through Sunday, Dec. 8 Hippodrome Theatre at the France-Merrick Performing Arts Center, 12 North Eutaw St. The classic holiday movie White Christmas gets new life in this musical that in- DECEMBER 2013 — BALTIMORE BEACON cludes such Irving Berlin hits as “Blue Skies,” “How Deep is the Ocean?” and the unforgettable title song, “White Christmas.” As in the movie, the show tells the story of two friends putting on a show in a small Vermont inn and finding their perfect mates in the process. You’ll be dreaming of a white Christmas too by the time you leave the theater. The Snowman Thursday, Dec. 5 and Friday, Dec. 6, at 10 and 11:30 a.m. each day Joseph Meyerhoff Symphony Hall, 1212 Cathedral St. Another one for the youngsters in your life, as the Baltimore Symphony Orchestra tells the musical tale of a young boy’s magical friendship with a snowman as they travel the world together. Handel’s Messiah Friday, Dec. 6 and Saturday, Dec. 7, 7:30 p.m. Joseph Meyerhoff Symphony Hall, 1212 Cathedral St. The BSO once again ushers in the holiday season with its powerful performance of Handel’s oratorio, featuring the stirring “Hallelujah Chorus.” 30th Annual Merry Tuba Christmas Saturday, Dec. 7, 3:30 to 4:30 p.m. Harborplace Amphitheater More than 20 tuba and euphonium play- Senior Apartments LIVE WELL FOR LESS Roland View Towers • One- and Two-Bedroom as well as Efficiencies • Rents from $443-$744* Utilities Included! • 24/7 on-site Maintenance and Reception Desk • Beauty/Barber Shop on premises • Bus Trips and Social Events and many more amenities! • Only 2 blocks from Hampden’s ‘The Avenue’ Mention the Beacon for First Month’s Rent FREE! Spectacular View For your personal tour contact Arthur or Laura Ruby at 410-889-8255 St Mary’s Roland View Towers 3838/3939 Roland Ave • Baltimore MD 21211 *All residents must meet specific income guidelines. Rooftop Restaurant ers will help get you in the holiday mood as they blend their unique styles and rhythms. BSO Holiday Cirque Wednesday, Dec. 11, 2 p.m.; Friday, Dec. 13, 2 and 7:30 p.m.; Saturday, Dec. 14, 2 and 7:30 p.m.; Sunday, Dec. 15, 2 p.m. Joseph Meyerhoff Symphony Hall, 1212 Cathedral St. Bring the entire family to hear holiday favorites while also enjoying the performance of Cirque Musica with its gasp-inducing aerial feats, strongmen and mind-boggling contortionists. Mannheim Steamroller Patricia & Arthur Modell Performing Arts Center at the Lyric Thursday, Dec. 12, 8 p.m. If it’s nearing Christmas, then it’s time to break out the Mannheim Steamroller CDs. Get a head start with this live performance at the Lyric. Soulful Holidays Saturday, Dec. 14, 8 p.m. Hippodrome Theatre at the France-Merrick Performing Arts Center, 12 North Eutaw St. Soulful Symphony’s holiday show runs the gamut from rousing renditions of Christmas carols to traditional holiday favorite adaptations of the Messiah and The Nutcracker. Carolers on the Court The Walters Art Museum Sunday, Dec. 15, 1 and 4 p.m. A cappella caroling ensemble Joyous Voices returns to The Walters this year to entertain with traditional Christmas melodies, medieval and Victorian to popular favorites. Cocoa and goodies will be on hand! The Nutcracker Family Concert Patricia & Arthur Modell Performing Arts Center at the Lyric Friday, Dec. 20, 7:30 p.m. Saturday, Dec. 21, 2 and 7:30 p.m. Sunday, Dec. 22, 3 p.m. This timeless tale of The Nutcracker is an annual tradition for many families. This production brings together the BSO, Baltimore School for the Arts, Maryland Institute College of Art and the Modell Performing Arts Center at the Lyric for a retelling of this holiday classic. Moscow Ballet’s Great Russian Nutcracker Hippodrome Theatre at the France-Merrick Performing Arts Center Saturday, Dec. 21, 12:30 p.m., 4 p.m., 8 p.m. Moscow Ballet’s Great Russian Nutcracker features 40 top Russian dancers, falling snow, silk puppets and a spectacular “Dove of Peace,” as two dancers become one stunning bird with a 20-foot wingspan, all set to Tchaikovsky’s complete score. Say you saw it in the Beacon | Arts & Style BALTIMORE BEACON — DECEMBER 2013 Poet “HERMOSO NEGRO” From page 30 turn of events. For a newly published poet, Amour has been well received, and one of her poems, “Hermoso Negro,” written about her father, garnered an Honorable Mention in the Allen Ginsburg Poetry Awards, sponsored by the Poetry Center at Passaic County Community College in New Jersey. “Hermoso” means handsome in Spanish. Amour has appeared in Baltimore, and will be reading from her work later this month in New York. Writing the book took close to two years, and while Amour contemplated looking for conventional publishing options, she felt that, creatively, it was time for her to release the book now. That is why she went the self-publishing route. “Besides,” she laughed, “poetry is a really hard sell.” Free to Be Me: Poems on Life, Love and Relationships is for sale, both in print and e-book format, on Amazon. FROM PAGE 34 ANSWERS TO SCRABBLE ANSWERS TO CROSSWORD F L U B R A T A O N U S S C R E W A B C S L U R I T R I N I R E D O D G I K I L H A V E O N E A P T S D H E N C A E B B D I L A E V M A N A B A N I T E M A S O N I C A C E D L E O R O T N I G H T E A S P S O R E S K E T C C O R E R K S K A I T I C P E R E E K S O F T S H O L L I D O U T S S T V E E P E N R O N S S A M I G O S I R E D E X T R A O R S O A S T A P E S T BEACON BITS Dec. 1 HANUKKAH FEVER CONCERT Celebrate Chanukah with the Mama Doni Band at the Gordon Center for Performing Arts, 3506 Gwynnbrook Pkwy. in Owings Mills, on Sunday, Dec. 1 at 3 p.m. Doni Zasloff Thomas, besides being Mama Doni, is a music teacher, songwriter, lead singer for the band, and herself a mom. Mama Doni celebrates Jewish culture with its high-energy, interactive family rock concerts, such as this one for Hanukkah. Tickets are $10 per person in advance, $12 at the door. For more information, visit or. “Hermoso Negro,” my Dad would say As he pulled the hairs from his chin with a tweezer I would watch him move his face closer to the mirror in the bathroom “Hermoso Negro,” he would say again. My dad would respond with a toothy grin. He would set up conferences with my teachers To ask if I should watch soap operas The merits of reading fiction books What my appropriate bedtime should be. Handsome black man, I guess that’s how my Dad saw himself Or that’s what he said And when he visited my school on parents/teachers night My female teachers acted like he was handsome. I often wondered if my teachers understood most of what he was saying Because at no time did he ever try to conceal his Caribbean accent. 6’ 2”, not so dark-skinned with a strong Caribbean accent A professional man My Dad was a novelty at my school in Dartmouth, Nova Scotia. I remember being embarrassed in front of my friends When he would say “tree” for three, “glass” for window “How ya going?” instead of How are you? But he always spoke unapologetically. “Mr. Woods, you look like Harry Belafonte,” my home room teacher said That part I liked. 33 34 DECEMBER 2013 — BALTIMORE BEACON More at TheBeaconNewspapers.com Puzzle Page Crossword Puzzle Daily crosswords can be found on our website: Click on Puzzles Plus Enjoy Yourself by Stephen Sherr 1 2 3 4 5 6 14 15 17 18 20 7 27 29 44 43 47 54 JUMBLE ANSWERS 30 31 13 32 33 34 59 60 38 40 39 12 25 37 36 11 22 24 28 10 19 21 35 Scrabble answers on p. 33. 9 16 23 26 8 41 45 42 46 48 49 51 52 55 56 50 53 57 58 64 61 62 63 65 66 67 68 69 70 Across Down 1. Attendee at a new student mixer 6. Unused 10. GE product 14. It’s used as a weapon a lot 15. Hot to ___ 16. He has a steakhouse at Caesar’s Palace 17. Complete 180 18. O: Pretty good blackjack hands 20. O: Last stop for supplies 22. Nile snakes 23. One of the w’s in 24. Achy 26. Fundamentals 29. O: Neurotic one 35. Gruesome 37. Cross the goal line 38. Match match 39. South Caribbean islander 40. TV ET HQ 41. Ann Taylor offering 43. Resentment 44. Hawaiian Island with no traffic lights 46. After Jack, he has won the most majors 47. O: New model greenlighted by Lee Iacocca in 1990 50. Concluding event 51. Jobs creation 52. “Oh no; a mouse!” 54. It turns clay to bricks 56. O: A good cleanser, bar none 61. Enjoy yourself (or what all the O’ed clues do) 64. Trojan hiding place 65. ___-Day (vitamin brand founded over 25,000 days ago) 66. Type of jazz or rock 67. Expels 68. War vet’s problem 69. Brooklyn team, since 2012 70. Short-tailed weasel 1. Botch 2. Pro ___ 3. Burden of proof 4. O: Attaches 5. In conclusion 6. One story or two lovers 7. Party pooper 8. Diary 9. Ending of the Bible 10. “I’ll be right there” 11. Senate tie-breaker 12. White-bellied Sea Eagle, and relatives 13. Ballot proposition options 19. Most pucker-producing 21. Start of a sonnet rhyme scheme 24. Home to the Illinois Holocaust Museum and Education Center 25. “___ the fields we go” 26. Other ref. nbr. 27. Small donkey 28. Wept 30. ___ Boomer (an intense post-war kid) 31. Left-over parts 32. Ole buddy 33. Begot 34. Face in a crowd scene 36. No-win situation 42. O: Evicts 45. Gardner of The Barefoot Contessa 48. Biblical mountain, in present-day Jordan 49. Arbiter or arbitrate 53. Community spirit 54. He could write of Pure Reason 55. Folk singer Burl 56. Feature of a 41 Across 57. He made 425 new cars in 1901 58. Roughly 59. “The Thin Man” dog 60. Annoyance 61. Short flight 62. Lifetime ___ (permanent expulsion) 63. Get a top grade Answers on page 33. Answer: What the clerk got when she decorated the gift package -- "WRAPPED" UP IN IT Jumbles: USURP APPLY POWDER BEHELD BALTIMORE BEACON — DECMEBER 2013 right.. Financial Services ACCOUNTING, BOOKKEEPING, TAXES – conscientious CPA, 37 years experience, reasonable rates, looking for additional business, personal and eldercare clients. Call 410-653-3363. For Rent 2ND-FLOOR APARTMENT – 2 bedrooms. Living and dining room. Kitchen and 1 bathroom. Open porch. Heat included. $600 per month. 410-298-8048, 410-523-8844. For Sale Home/Handyman Services SANFORD & SON HAULING Trash removal, house & estate clean-outs, garage cleanouts, yard work & cleanups, demolition, shed removal. 410-746-5090. Free Estimates. Insured. Call 7 days a week 7 a.m. – 7 p.m. FEDERAL HOME SOLUTIONS - Certified Aging in Place Specialists. We are a full-service, custom-remodeling company specializing in modifications for accessibility. 410-409-8128. MHIC# 104589. BASEMENT OR FOUNDATION PROBLEMS? LEVELIFT SYSTEMS, INC. offers honest, professional, no-pressure inspection, consultation & repair quotes for owner-occupied homes with settling, cracking & buckling basement walls. Our 23-year-old Jessup, Marylandbased firm has a spotless record with Angie’s List, Better Business Bureau and Maryland State Home Improvement Commission. Ask for Paul. Office: 301-369-3400. Cell: 410-365-7346. Paulm@levelift.com. MHIC #45110. MIKE RUPARD – A FULL SERVICE PAINTING contractor. Interior. Exterior. “No job is too small.” 30 years experience. Free estimates. Fully-licensed and insured. 301-6741383. BALTIMORE’S BEST JUNK REMOVAL – Clean Outs: Whole House, Emergency, Attics/Basements. Furniture and Junk Removal, Yard Waste Removal, General Hauling, Construction Debris Removal. Free estimates. 10% Senior Discount. Licensed, Bonded and Insured. Call Jesse, 443-379-HAUL (4285). HANDYMAN MATTERS will help you stay safe in your own home. Professional, Reliable Skilled Craftsmen. Grab Bar Installation, Bathroom Modifications and your to-do list! 410-549-9696. MHIC # 89094. Personal Services ESTATE SPECIALIST, experts in estate clean-outs and preparing your house for sale. Trash removal, house cleanouts, light moving, demolition, yard work, cleaning. 410-746-5090. Free estimates. Insured. Call 7 days, 7 a.m. – 7 p.m. 2 BURIAL LOTS AT PARK VIEW CEMETERY – in Parkville. New sect. Garden of Peace. Mrs. Schafer, 410-569-5686. FEMALE COMPANION, EXPERIENCED – light housekeeping, cooking, errands, organizing, pet care. 443-243-1280. WEIGHT EQUIPMENT – ALL CHROME Paramount 4 station. Cost $5,000. Will sell for $1350 firm. Also upright Sears Freezer, 16 cubic ft. Never used. $125. Full size Brunswick Slate pool table with green felt, $625. 443-797-4800, Richard. LEARN ENGLISH – SPANISH – ITALIAN – FRENCH – PORTUGUESE Conversational. Grammatical. Private lessons. Reasonable Rates. Tutoring students. 443-352-8200. 2 SALVADOR DALI woodblock prints from Dante’s Divine Comedy. Signed and framed. Asking $900 for the pair. Can email pictures if desired. Call Steve, 410-913-1653. Wanted Health WORLD’S LARGEST HEALTH AND WEIGHT LOSS company. Incredible 30 free milkshakes. Offer while supplies last!!. 443253-2640. VINYL RECORDS WANTED from 1950 through 1985. Jazz, Rock-n-Roll, Soul, Rhythm & Blues, Reggae and Disco. 33 1/3 LPs, 45s or 78s, Larger collections of at least 100 items wanted. Please call John, 301-596-6201. WE BUY OLD AND NEW JEWELRY, Coins, Silver and Gold, Paper Money Too. Watches, Clocks and Parts, Military Badges and Patches Old and New. Call Greg, 717-658-7954. BEACON BITS Ongoing 35 Say you saw it in the Beacon AFRICAN AMERICAN ARTIFACTS “The Kinsey Collection: Shared Treasures of Bernard & Shirley Kinsey — Where Art & History Intersect” is a world-class collection of art and artifacts chronicling over 400 years of African American history and culture from the 1600s to the present. Highlights of this exhibition at the Reginald F. Lewis Museum of African American History and Culture include an early copy of the Emancipation Proclamation, a signed copy of Brown vs. Board of Education, and rare works from early 19th century artists. The exhibition makes its final stop of a national tour in Baltimore through March 2, 2014. For more information, visit or call (443) 263-1800. The museum is located at 830 E. Pratt St. Admission is free for members, $6 for those 65 and older., or place a personal ad. Each ad is $10 for 25 words, 25 cents for each additional word. Business Text Ads: For parties engaged in an ongoing business enterprise. Each ad is $25 for 25 words, 50 cents for each additional word. Note: Each real estate listing counts as one business text ad. Send your classified ad with check or money order, payable to the Beacon, to: The Beacon, Baltimore Classified Dept. P.O. Box 2227, Silver Spring, MD 20915-2227 Wanted Wanted MILITARY ITEMS Collector seeks: helmets, weapons, knives, swords, bayonets, webgear, uniforms, inert ordnance, ETC. From 1875 to 1960, US, German, Britain, Japan, France, Russian. Also Lionel Trains. Please call Fred, 301-910-0783. Thank you. rugs to Tiffany objects, from rare clocks to firearms, from silver and gold to classic cars. If it is wonderful, I am interested. No phony promises or messy consignments. References gladly furnished. Please call Jake Lenihan, 301-279-8834. Thank you. OLD AND NEW WE BUY Sterling Silver Flatware, Tea Sets, Single Pieces, Fountain Pens, Lighters, Tools, Cameras, Glassware, Art Work. Toys From Trains to Hotwheels to Star Wars. Call Greg, 717-658-7954. CASH BUYER FOR OLD COSTUME JEWELRY – pocket and wrist watches (any condition). Also buying watchmaker tools and parts, train sets and accessories, old toys, old glassware & coins. 410-655-0412. BEACON BITS Ongoing BRITTANY IN BALTIMORE “La Lumiere Fantastique: Brittany Shines in Baltimore” is on view through Dec. at the Graduate Student Center: Sheila and Richard Riggs and Leidy Galleries at the Maryland Institute College of Art, 131 W. North Ave. The exhibition features works by 65 MICA artists created during and after their residencies in Brittany, France. For more information, visit or call (410) 669-9200. s a t! e ak t gif M a e gr Beacon The I N F O C U S F O R P E O P L E OV E R 5 0 $12/year via Third Class Mail plus tax Please send a one-year subscription to: Name:____________________________________________ Address:___________________________________________ City:_____________________State:_____Zip:___________ ❐ One Year = $12 (Maryland residents add 6% for sales tax = $12.72) ❐ Check here if this is a gift subscription. Ongoing EVERYMAN THEATRE PRESENTS RED Write the recipient’s name above. A gift card will be sent in your name: _____________________________ Return this form with your check, made payable to The Beacon, to: The Beacon, P.O. Box 2227, Silver Spring, MD 20915-2227 BB12/13 Winner of six 2010 Tony Awards, including Best Play, Red, playing at Everyman Theatre through Dec. 8, is an exploration of the mind of artistic genius and abstract expressionist Mark Rothko. Set against the changing landscape of the early 1960s, the celebrated artist has just landed his biggest commission: a series of massive murals for New York’s posh Four Seasons Restaurant. Everyman Theatre is located at 315 W. Fayette St. Tickets are $32 to $60. For more information, phone (410) 752-2208 or go to. 36 DECEMBER 2013 — BALTIMORE BEACON More at TheBeaconNewspapers.com 0 $2 AnÊeasierÊandÊmoreÊaffordableÊ wayÊtoÊcall,ÊtextÊandÊemail. NEW r Ca r EE rge FR ha C y n th! a P tha on ss r m e l e p Introducing the Jitterbug® Touch 2, the smartphone that features the best in simplicity and service. MoreÊ andÊ moreÊ peopleÊ areÊ gettingÊ so-calledÊ “Smartphones”ÊtheseÊdays.ÊTheyÊareÊdesignedÊ toÊdoÊmuchÊmoreÊthanÊcalling,ÊyouÊcanÊuseÊ themÊtoÊtext,ÊsendÊemails,ÊaccessÊtheÊInternetÊ andÊmuch,ÊmuchÊmore.ÊTheÊproblemÊis,ÊtheyÊ aren’tÊdesignedÊforÊseniors.ÊWhat’sÊsoÊsmartÊ aboutÊaÊphoneÊthatÊyouÊpracticallyÊneedÊaÊ computerÊdegreeÊtoÊuse?ÊThat’sÊwhyÊIÊwasÊ soÊpleasedÊtoÊfindÊoutÊaboutÊtheÊJitterbugÊ TouchÊ2.ÊItÊcomesÊfromÊtheÊsameÊpeopleÊ whoÊ introducedÊ theÊ originalÊ JitterbugÊ cellÊphone,ÊsoÊit’sÊeasyÊtoÊseeÊandÊhearÊ andÊsoÊsimpleÊtoÊuse. Ê It’sÊ Easy.Ê OtherÊ smartphonesÊ areÊ complicatedÊandÊintimidating,ÊwithÊ tinyÊ iconsÊ andÊ multipleÊ screens.Ê NotÊtheÊJitterbugÊTouchÊ2-Êit’sÊeasyÊ toÊuseÊfromÊtheÊmomentÊyouÊturnÊitÊ on.ÊEverythingÊyouÊwantÊtoÊdo,ÊfromÊ textingÊtoÊemailingÊtoÊtakingÊpicturesÊisÊorganizedÊinÊaÊsingleÊlistÊ onÊoneÊscreenÊwithÊlarge,ÊlegibleÊletters.ÊThisÊunique,ÊsimplifiedÊ approachÊtakesÊallÊtheÊguessÊworkÊoutÊofÊusingÊaÊsmartphoneÊ andÊputsÊeverythingÊrightÊatÊyourÊfingertips. It’sÊAffordable.ÊOtherÊsmartphonesÊrequireÊexpensiveÊplans,Ê andÊyouÊendÊupÊpayingÊforÊminutesÊandÊdataÊyouÊdon’tÊneed.Ê StartingÊatÊjustÊ$2.49ÊperÊmonth,ÊyouÊcanÊchooseÊaÊdataÊplanÊ thatÊfitsÊyourÊneeds.ÊComparedÊtoÊotherÊcellÊphoneÊcompanies,Ê you’llÊ saveÊ overÊ $300Ê perÊ year,Ê makingÊ theÊ TouchÊ 2Ê phoneÊ plansÊtheÊmostÊaffordableÊonÊtheÊmarket. Jitterbug Touch 2 ! "#$!%&'(!)**&+,)-.$!,)()!/.)0'! ! &*!)01!'%)+(/#&0$ ! 2)'1!(&!3'$!+45#(!&3(!&*!(#$!-&6 ! 73..8'49$!&0':+$$0!;$1-&)+,! ! %);$'!(1/405!$)'1 ! <)+5$=!$)'18(&8+$),!-3((&0'!)0,!,4'/.)1 ! >&!:&0(+):('!&+!:)0:$..)(4&0!*$$'? It’sÊSmart.ÊTheÊnewÊTouchÊ2ÊisÊaÊsleek,ÊstylishÊ smartphone with a large 4-inch display. A full-size on-screen keyboard makes typing quick and easy, while the built-in camera lets you capture and share photos anywhere. And with a long-lasting battery the Jitterbug Touch 2 is ready whenever you need it. Best of all, there are no contracts and no cancellation fees. Plus, you get dependable nationwide coverage and the support of our award-winning,Ê100%ÊU.S.ÊBasedÊCustomerÊService–ÊavailableÊ 24/7.ÊCallÊnowÊandÊfindÊoutÊhowÊyouÊcanÊtryÊtheÊJitterbugÊTouchÊ 2ÊwithÊourÊfriendlyÊreturnÊpolicy.ÊTryÊitÊforÊ30Êdays,ÊifÊyouÊdon’tÊ loveÊit,ÊjustÊreturnÊitÊforÊaÊrefund1ÊofÊtheÊproductÊpurchaseÊprice.Ê CallÊnow–ÊhelpfulÊJitterbugÊexpertsÊareÊreadyÊtoÊanswerÊyourÊ questions.Ê @#1!/)1!*&+!%403($'=!%$'')5$'!)0,!,)()!1&3!,&0A(!3'$B Minutes PAY LESS THAN $ 20/MONTH! Basic 14 Plan $ .99 14 Data TOTAL * 2 Per Month $ .48 17 *The most affordable data plan of any smartphone! BONUS OFFER! a FREE Call now and receive Car Charger – a $24.99 Value! Many other plans are available and you can mix and match minutes, messages and data to fit your needs. Ask your Jitterbug expert for details. Jitterbug Touch 2 Call today to get your Jitterbug Touch 2. 1-877-451-1619 visit us at 47604 Please mention promotional code 50987. IMPORTANT CONSUMER INFORMATION: Jitterbug is owned by GreatCall, Inc. Your invoices will come from GreatCall. All rate plans and services require the purchase of a Jitterbug phone and a one-time set up fee of $35. $300 savings calculation based on market leaders’ lowest available monthly published fees.. ©2013 GreatCall, Inc. ©2013 by firstSTREET for Boomers and Beyond, Inc.
https://issuu.com/thebeaconnewspapers/docs/1213baltbeacon
CC-MAIN-2016-50
refinedweb
20,708
63.39
Hello, everyone. I can’t find the answer to question number four on this exercise The Null Hypothesis is Are the visitors too old? Or is this just the result of chance and a small sample size? For this code from scipy.stats import ttest_1samp import numpy as np ages = np.genfromtxt("ages.csv") print(ages) ages_mean = np.mean(ages) print(ages_mean) tstat, pval = ttest_1samp(ages, 30) print(pval) I get these numbers [ 32. 34. 29. 29. 22. 39. 38. 37. 38. 36. 30. 26. 22. 22.] #ages list 31.0 #true mean 0.560515588817 #pvalue And the question asked is Does the p-value you got with the 1 Sample T-Test make sense, knowing the mean of ages? The p-value says there is a 56% chance that my null hypothesis is true and the result is due to chance. So an expected mean of 30 has 56% of chance that my null hypothesis is true, but the true mean is 31, this is pretty close to 30, i think that this result for p-value makes no sense at all. Given the true mean, it should be a much lower p-value for such a close expected mean. Am i right in my thinking and my answer? I’m confused and have no confidence that this is a right train of thought. Thank you for your time
https://discuss.codecademy.com/t/does-the-p-value-i-got-with-the-1-sample-t-test-make-sense-knowing-the-mean-of-ages/492051
CC-MAIN-2020-40
refinedweb
230
82.54
Created on 2008-03-29 02:10 by genepi, last changed 2013-11-05 03:13 by nhooey. Please add support for pgettext(msgctxt, msgid) and variants (dpgettext, dcpgettext...) in the gettext module. I will not rephrase the justification for these functions and why contexts are essential for good localization: Would you like to work on a patch? I have written a patch against the current Python trunk's gettext to add support for pgettext and friends (upgettext, npgettext, unpgettext, ...). I have also changed Tools/i18n/msgfmt.py to recognize the "msgctxt" keyword. Some new unittests for dgettext and lgettext and variants are also included. If the patch will be accepted then someone should drop a message to the maintainers of GNU gettext to add the new functions as default keywords for xgettext. Right now you have to call xgettext with "--keyword=pgettext:1c,2" to extract messages with context. Tools/i18n/pygettext.py does currently not handle context variants. I don't see any change in Modules/_localemodule.c: you reimplemented pgettext() in pure Python. Why no reusing existing pgettext() function (at least when it's present)? The gettext module is intentionally written in pure Python; it should stay that way. Whether or not the _locale module should also grow support for pgettext is a different issue. I came across this ticket while looking for alternatives to Python's gettext, since I need msgctx support. It seems a patch was supplied for this a while back. I have never contributed to Python, and am not familiar with your release process, but is there anything preventing its inclusion? It would be very convenient to have this in a release version. Only my lack of time prevents inclusion. I would just like to add that I am also looking forwards to this feature. Me too. This makes developing applications with good localizations in Python really difficult. Same here. Pleeeeeeeaaaaaaaase ;-) While we're waiting for this patch to be upstreamed, what's the best way to emulate this functionality with the current gettext module? I'm looking at the patch and it seems that code similar to this might work? def pgettext(ctx, msg): return gettext(ctx + "\x04" + msg) Yes. You can see an in-production implementation at (I'm overriding ugettext to support an optional context). Martin, is there anything we can do to help get this merged? I can really use this as well. My background here is that currently the complete zope i18n support abuses message ids as a workaround, and the result works but is very painful for translators since the original string is not immediately visible for them. The patch needs to be updated for the 3.x trunk (py3k branch), since the last 2.x version is already rc. Everyone, thanks for expressing interest for the development of Python, but posting “me too” messages does not further the discussion, and actually takes time from already busy people. Use cases, patches, reviews and the occasional bump (one is enough) are helpful. :) I have ported the patch to py3k, without tests errors but with test failures. What is left to do: 1) Carefully assess bytes/str issues. Decide to change the tests or the code. 2) Re-read over the new docs. 3) Exercise the updated msgfmt.py tool, which has no tests. 4) Add support in pygettext.py. David, Mitar, nh2, David D., Olivier, Bernie, Wil, Wichert: Do you want to help with one of those tasks? I can help test changes for python 2.x. The python 3.x ecosystem is at least a year away from becoming interesting for me I'm afraid. New features don’t go into stable branches. The patch is also reviewable at Can someone review the patch and consider its inclusion?
http://bugs.python.org/issue2504
CC-MAIN-2014-15
refinedweb
631
67.65
Cameron Beattie wrote: def main(): urllib._urlopener = MyUrlOpener() url = "%s/Control_Panel/Database/manage_pack?days:float=%s" % \ Advertising *sigh* url whacking, bleugh! If I use the backup user then urllib can't get the url due to no authentication so errors as follows: What roles do you want to have the backup user to have? What permissions are mapped to those roles? What permissions are mapped to the Owner role? Looking at the differences will tell you what's going on ;-) PS: I wouldn't do zodb packing by whacking a url. There's a script that scripts with ZOpe now that opens up a ZEO connection and does the pack that way, that's what I'd do...I don't use ZEO - can I just do the scripted packing bit without all the associated ZEO setup? You should use ZEO! there's no sane reason not to... Chris -- Simplistix - Content Management, Zope & Python Consulting - _______________________________________________ Zope maillist - Zope@zope.org ** No cross posts or HTML encoding! **(Related lists - )
https://www.mail-archive.com/zope@zope.org/msg19480.html
CC-MAIN-2018-34
refinedweb
169
76.62
ImageWin Module (Windows-only)¶ The: from PIL import ImageWin dib = ImageWin.Dib(...) hwnd = ImageWin.HWND(widget.winfo_id()) dib.draw(hwnd, xy) - class PIL.ImageWin. Dib(image, size=None)¶ A Windows bitmap with the given mode and size. The mode can be one of “1”, “L”, . draw(handle, dst, src=None)¶. query_palette(handle)¶ Installs the palette associated with the image in the given device context. This method should be called upon QUERYNEWPALETTE and PALETTECHANGED events from Windows. If this method returns a non-zero value, one or more display palette entries were changed, and the image should be redrawn. - class PIL.ImageWin. HDC(dc)¶ Wraps an HDC integer. The resulting object can be passed to the draw()and expose()methods.
http://pillow.readthedocs.io/en/3.1.x/reference/ImageWin.html
CC-MAIN-2018-26
refinedweb
119
61.22
On Mon, Jul 11, 2011 at 10:03:24PM +0200, shuerhaaken wrote: > > That's what Suggests/Recommends are made for. E.g. Rhythmbox Recommends > > rhythmbox-plugins, quodlibet Suggests quodlibet-plugins... From Policy §7.2 > > "The Recommends field should list packages that would be found together with > > this one in all but unusual installations": seems what you need. > > > > My suggestion was mainly based on personal preference (I like to choose if I > > actually want the plugins or not, if they are not strictly needed) and on > > what other packages do. It is not a requirement, hence you can do whatever > > you want. > > If that's the Debian way, I will just leave it like that and ship an > extra package for xnoise-plugins Ok, there are a couple of issue thought: - you should append something like " (plugins)" to the short description so that it does not duplicate the description of the main package. - the -plugins package right now Depends on various -dev packages. I do not think they are needed. Also, libcairo-dev is duplicated in Build-Depends. > > Btw, the package didn't show up on mentors.d.n yet, hence I couldn't check > > the modifications you did (it may just be a problem of mentors.d.n... it > > happens sometimes). > > Hmm. I uploaded and it was visible here: >;package=xnoise > But I also couldn't get it via repo. So I'll upload again in a few > minutes. I can see it now. > > Final suggestion (I forgot to say this in the previous email), you may want > > to join the Debian Multimedia Team [0] to maintain this package (it > > would be easier for you to find an uploader and some help to maintain the > > package). Please have a look at our policies [1] (maintain the package on > > git using git-buildpackage, "Debian Multimedia Team" is the Maintainer and > > you the Uploader, ...). If you are interested and ok with our workflow feel > > free to subscribe and post this RFS to the team's mailing list [2] (you will > > also need an account on alioth.debian.org). > > > I'll have a look into that. Hope they don't just pull out the current > git version instead of a release. Not sure I've understood, but the git repository is only used to keep track of the Debian-related modifications (those under "debian/"), and, additionally, it holds a convenience copy of the upstream sources (imported from the upstream tarball) to ease building. Have a look at for some examples (our packages are those under the pkg-multimedia namespace). Cheers -- perl -E'$_=q;$/= @{[@_]};and s;\S+;<inidehG ordnasselA>;eg;say~~reverse'
https://lists.debian.org/debian-mentors/2011/07/msg00333.html
CC-MAIN-2017-26
refinedweb
440
62.88
react-router v6 demystified (part 2) In my previous article, we have seen what are the new APIs of react-router v6. We also have listed what we expect to develop. In this article, we won't implement the nested Route and Routes, but don't be afraid it will be done in a next article. My implementation will not be exactly the same as react-routerbut it will help you to understand how it works and to explore the react-routerrepository on your own. The goal is to be able to implement something like this: function App() { return ( <Router> <Routes> <Route path="hobby/" element={<HobbyListPage />} /> <Route path="hobby/:name" element={<HobbyDetailPage />} /> <Route path="about" element={<AboutPage />} /> <Route path="/" element={<HomePage />} /> </Routes> </Router> ); } With a set of utility hooks: // To get the current location pathanme, query params and anchor function useLocation(); // To get the path variables function useParams(); // To push or replace a new url // Or to go forward and backward function useNavigate(); Let's start with the Router component This component is the main one. It will provide the location and methods to change the url, to components below it (in the tree). react-router provides two router BrowserHistory (using the browser's history) and MemoryHistory (the history will be stored in memory). In this article, we will only develop a BrowserHistory. The location and navigation methods will be stored in a React context. So let's create it and code the provider: import React from 'react'; const LocationContext = React.createContext(); export default function Router({ children }) { return ( <LocationContext.Provider value={{ // The current location location: window.location, navigator: { // Change url and push entry in the history push(to) { window.history.pushState(null, null, to); }, // Change url and replace the last entry in the history replace(to) { window.history.replaceState(null, null, to); }, // Go back to the previous entry in the history back() { window.history.go(-1); }, // Go forward to the next entry in the history forward() { window.history.go(1); }, // If we want to go forward or // backward from more than 1 step go(step) { window.history.go(step); } } }} > {children} </LocationContext.Provider> ); } If you try to use these methods to change the url, you will see that it doesn't work. If you try to play with this code and watch logs, you will see that the component does not render so any component that uses the location will not be informed of the new url. The solution is to store the location in a state and change it when we navigate through the pages. But we can't just push the window.location in this state, because in reality the reference of window.location does not change the reference of the object but the object is mutated. So if we do this, it will just do nothing. So we are going to build our own object, and put the values of pathname, search and hash. Here is the function to create this new location object: function getLocation() { const { pathname, hash, search } = window.location; // We recreate our own object // because window.location is mutated return { pathname, hash, search, }; } The creation of the state is: const [location, setLocation] = useState(getLocation()); Then we just have to change the state when we navigate, for example when we push: push(to) { window.history.pushState(null, null, to); setLocation(getLocation()); } We could do the same for the methods which navigate in the history entries. But it will not work when we go back or forward with the browser buttons. Fortunately, there is an event that can be listened for this use case. This event popstate is fired when the user navigates into the session history: useEffect(() => { const refreshLocation = () => setLocation(getLocation()); window.addEventListener("popstate", refreshLocation); return () => window.removeEventListener("popstate", refreshLocation); }, []); Finally we got the following for our Router: import React, { useContext, useEffect, useMemo, useState, } from "react"; const LocationContext = React.createContext(); function getLocation() { const { pathname, hash, search } = window.location; // We recreate our own object // because window.location is mutated return { pathname, hash, search, }; } export default function Router({ children }) { const [location, setLocation] = useState(getLocation()); useEffect(() => { const refreshLocation = () => { setLocation(getLocation()); }; // Refresh the location, for example when we go back // to the previous page // Even from the browser's button window.addEventListener("popstate", refreshLocation); return () => window.removeEventListener( "popstate", refreshLocation ); }, []); const navigator = useMemo( () => ({ push(to) { window.history.pushState(null, null, to); setLocation(getLocation()); }, replace(to) { window.history.replaceState(null, null, to); setLocation(getLocation()); }, back() { window.history.go(-1); }, forward() { window.history.go(1); }, go(step) { window.history.go(step); }, }), [] ); return ( <LocationContext.Provider value={{ location, navigator, }} > {children} </LocationContext.Provider> ); } I memoized the navigatorobject because we do not want to recreate it each time the location change. But did not memoized the Provider's value because it will be at the top of the React tree and should re-render uniquely when the location changes. Now we can implement, some simple hooks which will use this LocationContext. We are going to develop: useLocation: to get the location useNavigator: to get the navigator part The implementations are the following ones: useLocation function useLocation() { return useContext(LocationContext).location; } useNavigator function useNavigator() { return useContext(LocationContext).navigator; } It's time to continue our implementation with the Route component. The API is simple, it takes: - the elementto display - the pathfor which this route will be displayed And the implementation is quite simple: function Route({ element, path }) { return element; } As you can see the path prop is not used in this component, but by the Routes component which decides if this Route should be displayed or not. And this our next part. As I said previously, the Routes component decides which Route to display in function of the location. Because I don't want this article to be too long and difficult. In this part, we are just going to do routing with no nested Route and Routes. But don't be afraid, in an other article I will code all the features wanted. Now that we know the scope of this article, let's go put our hands in some code. We know that a Routes takes all the possible Route as children. From this children, we can loop through this children to extract the path of each Route from its props to build a simple array of objects, which easier to process than a React element. So we want to make a function buildRouteElementsFromChildren that will return an Array of: type RouteElement = { path: string, element: ReactNode, children: RouteElement[], } The code of this function is: || "/", }; routeElements.push(route); }); return routeElements; } If we take the following Routes example: <Routes> <Route path="hobby/:name" element={<HobbyDetailPage />} /> <Route path="hobby" element={<HobbyListPage />} /> <Route path="about" element={<AboutPage />} /> <Route path="/" element={<HomePage />} /> </Routes>; Will be transformed into: [ { path: "hobby/:name", element: <HobbyDetailPage />, }, { path: "hobby", element: <HobbyListPage />, }, { path: "about", element: <AboutPage />, }, { path: "/", element: <HomePage />, }, ]; Ok, now that we have a simple object, we need to find the first matching Route from this object. We already now all the possible paths. And thanks to the useLocation, we know the current pathname. Before doing some code. Let's think about it. Unfortunately, we can't just compare the current pathname to the Route ones because we have path variables. Yeah, I guess you already know that we are going to use Regexp :/ For example, if we are at the location /hobby/knitting/ named currentPathname, we want the following path to match: hobby/:name /hobby/:name /hobby/:name/ hobby/:name/ For the leading slash we are going to put a slash before the path, and replace all double slash by one: `/${path}`.replace(/\/\/+/g, "/"); For the trailing slash, we are to put an optional trailing slash in the regex: new RegExp(`^${regexpPath}\\/?$`); Now the question is, what is the value of regexpPath. The regex has two objectives: - get the path variable name (after the name - get the value associated to it, here it is knitting // We replace `:pathVariableName` by `(\\w+)` // A the same time we get the value `pathVariableName` // Then we will be able to get `knitting` for // our example const regexpPath = routePath.replace( /:(\w+)/g, (_, value) => { pathParams.push(value); return "(\\w+)"; } ); Now, that we have seen the complexity, let's make some code: // This is the entry point of the process function findFirstMatchingRoute(routes, currentPathname) { for (const route of routes) { const result = matchRoute(route, currentPathname); // If we have values, this is the one if (result) { return result; } } return null; } function matchRoute(route, currentPathname) { const { path: routePath } = route; const pathParams = []; // We transform all path variable by regexp to get // the corresponding values from the currentPathname const regexpPath = routePath.replace( /:(\w+)/g, (_, value) => { pathParams.push(value); return "(\\w+)"; } ); // Maybe the location end by "/" let's include it const matcher = new RegExp(`^${regexpPath}\\/?$`); const matches = currentPathname.match(matcher); // The route doesn't match // Let's end this if (!matches) { return null; } // First value is the corresponding value, // ie: currentPathname const matchValues = matches.slice(1); return pathParams.reduce( (acc, paramName, index) => { acc.params[paramName] = matchValues[index]; return acc; }, { params: [], element: route.element, // We want the real path // and not the one with path variables (ex :name) path: matches[0], } ); } Now that we can get the matching route. We are going to render the Route and use a React context name ReuteContext to put the params. The Routes component is: const RouteContext = React.createContext({ params: {}, path: "", }); function Routes({ children }) { // Get the current pathname const { pathname: currentPathname } = useLocation(); // Construct an Array of object corresponding to // available Route elements const routeElements = buildRouteElementsFromChildren(children); //; } const { params, element, path } = matchingRoute; return ( <RouteContext.Provider value={{ params, path, }} > {element} </RouteContext.Provider> ); } You may have noticed the use of a function as second parameter to the replacemethod. Very useful to get the name of the path variable. And now we need our hook to get the params: const useParams = () => useContext(RouteContext).params; Thanks to the useNavigator hook, we can access to methods to navigate between page. But the development experience is not necessarily the best. For example: - Currently, the path is /hobby - I push, knitting - I would like the new path to be /hobby/knitting Using the method pushof useNavigator, will redirect us to /knitting:( And: - Currently, the path is /hobby/knitting - I push, /about - I would like the new path to be /about Currently it works, with the method pushof useNavigator. So, to meet these two needs we are going to develop a hook useResolvePath which returns us the right path, a hook useNavigate and a component Link to navigate where we want easily. For the navigation we are just going to work with String as path. But in reality, with react-routeryou can pass object with the following structure: // For none typescript developers // The `?` means it's optional type To = { pathname?: string; search?: string; hash?: string; } | string; And in the code we should transform to as object to string and vice versa, but I repeat myself I'm just gonna work with string in this article for simplicity. To resume the strategy if the path to resolve is starting with a /then it's an absolute path otherwise a relative path to actual one. We can get the actual path, thanks to useRouteContext. Let's implement this: // Concat the prefix with the suffix // Then we normalize to remove potential duplicated slash function resolvePathname(prefixPath, suffixPath) { const path = prefixPath + "/" + suffixPath; return normalizePath(path); } // We export the utility method // because we need it for other use cases export function resolvePath(to, currentPathname) { // If the to path starts with "/" // then it's an absolute path // otherwise a relative path return resolvePathname( to.startsWith("/") ? "/" : currentPathname, to ); } export default function useResolvePath(to) { const { path: currentPathname } = useRouteContext(); return resolvePath(to, currentPathname); } Then we can develop our useNavigate hook and Link component thanks to that :) We are going to start with the hook to use it in the component. This hook will return a callback with the parameters: - First parameter: towhich is a string (the url to navigate to) or a number if we want to go backward or forward. - Second parameter: an object of options. For the article the only option will be replaceif the user just want to replace the url ( pushby default). Let's make some code: function useNavigate() { const navigator = useNavigator(); // We want to know the current path const { path: currentPath } = useRouteContext(); // By default it will push into the history // But we can chose to replace by passing `replace` option // You can pass a number as `to` to go `forward` or `backward` return useCallback( (to, { replace = false } = {}) => { // If to is a number // we want to navigate in the history if (typeof to === "number") { navigator.go(to); } else { // We want to get the "real" path // As a reminder if // to starts with / then it's an absolute path // otherwise a relative path in relation to currentPath const resolvedPath = resolvePath(to, currentPath); (replace ? navigator.push : navigator.push)( resolvedPath ); } }, [navigator, currentPath] ); } We want to be able to open a new tab from our element, and to have the same behavior than a a tag. So let's use a a with a href property. But if we just do that, the browser will load the page and refetch assets (css, js, ... files). So we need to prevent this default behavior, we are going to put an onClick method and preventDefault the event. function Link({ to, children, replace = false }) { const navigate = useNavigate(); // We want to get the href path // to put it on the href attribtue of a tag // In the real inplementation there is a dedicated hook // that use the `useResolvePath` hook // and transform the result into string // (because potentially an object but not in this article) const hrefPath = useResolvePath(to); // We put the href to be able to open in a new tab return ( <a href={hrefPath} onClick={(event) => { // We want do not browser to "reload" the page event.preventDefault(); // Let's navigate to `to` path navigate(to, { replace }); }} > {children} </a> ); } And here we go, we can navigate to new pages. I also developed a NavLinkwhich is useful for navigation item, when you want to display which item is active. You can see the code on the codesandbox below. Here is a little code sandbox of this second part of react-router implementation: In this article, we have coded the base to make a react-router like library. The main goal is to understand how works the main routing library for React, in its next version 6. To resume what we have learned and done in this second article about react-router v6: - The Routerprovides the location and methods to navigate through pages. - The Routecorresponding to a specific page / path - The Routescomponent determines the Routeto display, and provides the current pathname of the Routeand the params. Let's meet in my next article which will implement nested Route and Routes, and also bonus hooks. If you want to see more about react-router v6 which is in beta yet, let's go see the migration guide from v5.
https://rainbowapps.io/en/posts/react-router-v6-demystified-part-2/
CC-MAIN-2022-21
refinedweb
2,480
52.19
You may have heard that you need to be familiar with Objective-C if you plan to develop iOS applications. While Objective-C is indeed an important component of iOS development, people tend to forget that Objective-C is a strict superset of C. In other words, it is also important to be familiar with the fundamentals of C as an iOS developer. Don't worry though. If you already know the basics of programming, C will not be too difficult to pick up. Prerequisites It is not possible to cover the basics of programming and learn C in one article. I am therefore assuming that you already have some programming experience. Ruby, PHP, or JavaScript are good starting points for learning C and Objective-C, so if you come from a web development background you shouldn't have problems learning the basics of C by reading this article. In this article, I will focus on what makes C unique or different from other programming languages. This means that I won't cover basic programming concepts and patterns, such as variables and loops. What I will cover is how variables are declared in C and what pointers are. In other words, the focus lies on the things you need to know to become familiar with C. Introduction Dennis Ritchie started developing C in the late 1960's while working at AT&T Bell Labs. Thanks to its widespread use and simplicity of design, C can be used on almost any platform. It is not tied to any one operating system or platform. If you have explored other programming languages, then you might have noticed that they share a lot of similarities. Many languages have been inspired by C, such as C#, Java, PHP, and Python. Dennis Ritchie named his new language C because he took some inspiration from a prior language developed by Ken Thompson called B. Despite the fact that C is inspired by typeless languages (Martin Richards's BCPL and Ken Thompson's B), C is a typed language. I will cover typing in more detail later in this article. It doesn't take long to learn the basics of C, because it is a fairly small language with only a small set of keywords. You could say that C is very bare bones and only offers what is really necessary. Other functionality, such as input/output operations are delegated to libraries. Heap and garbage collection are absent in C and only a basic form of modularity is possible. However, the small size of the language has the benefit that it can be learned quickly. Despite the fact that C is a low level language, it is not difficult to learn or use. Many iOS and Mac developers have become so used to Objective-C and its object oriented design that they are afraid to try working with "straight" C or C libraries. Objective-C is a strict superset of C and nothing more than a layer on top of C. Practice Makes Perfect A programming language is best learned by practicing, so let's create a new project in Xcode and write a few lines of C to get to know the language. Launch Xcode and create a new project by selecting New > Project... from the File menu. We won't be creating an iOS application like we did earlier in this series. Instead, we will create an OS X project. Select Application in the section labeled OS X and choose Command Line Tool form the list of templates on the right. Click the Next button to continue. Name your project C Primer and give it an organization name and company identifier as we saw previously. Set the Type drop down menu to C. The only configuration option that really matters for this tutorial is the type. Don't worry about the other options for now. Click the Next button to continue. Tell Xcode where you want to save the new Xcode project. It isn't necessary to create a git repository for this project. We will only be using this project for learning C instead of creating a useful command line tool. Project Overview In comparison with the iOS application that we created earlier in this series, this project is surprisingly minimal. In fact, it only contains two source files, main.c and C_Primer.1. For the purposes of learning C, only main.c is of interest to us. The file's extension, .c, indicates that it is a C source file. Before we build and run the command line tool, let's take a look at the contents of main.c. Apart from a few comments at the top of the file and a function named main at the bottom, the source file doesn't contain much. The file also contains an include statement that I will talk about more a bit later in this article. // // main.c // C Primer // // Created by Bart Jacobs on 15/02/14. // Copyright (c) 2014 Tuts+. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); return 0; } A closer look at the main function reveals a few interesting characteristics of the C programming language. I mentioned earlier that C is a typed language, which means that variables as well as functions are typed. The implementation of the main function starts by specifying the return type of the function, an int. Also note that the arguments of the function are typed. The keyword function, which is common in many other languages, is absent in C. The body of the main function starts with a comment (single line comments start with //). The second line of the function's body is another function, which is part of the C standard library, hence the #include statement at the top of the file. The printf function sends output to the standard output, "Hello, World!\n", in this case. The \n specifies a new line. In Xcode, however, the output is redirected to the Xcode Console, which I will talk about more in a bit. The main function ends by returning 0. When a program returns 0, it means that it terminated successfully. That is all that happens in the main function. Don't mind the arguments of the main function as this is beyond the scope of this tutorial. Build and Run Now that we know what the main function does, it is time to build and run the command line tool. By building the application, the code in main.c is compiled into a binary, which is then executed. Build and run the command line tool by clicking the triangular play button at the top left of the window. If all went well, Xcode should show the debug area at the bottom of the window. You can show and hide the debug area by clicking the middle button of the View control in the toolbar at the top right. The debug area has two sections. On the left is the Variables window and on the right is the Console window. In the Console, you should see the words Hello, World!. Xcode also tells you that the program ended with exit code 0, which means that the program ended normally. In a Nutshell In the rest of this article, I will cover the most important characteristics of C. What is covered in this tutorial is limited to what you need to know to get started with iOS development. In the next article of this series, I will cover Objective-C. In contrast to interpreted languages, such as Ruby, PHP, and JavaScript, C is a compiled language. The source code of a program written in a compiled language is first compiled into a binary that is specific to the machine it was compiled on. The compilation process reduces the source code to instructions that can be understood by the machine it runs on. This also means that an application compiled on one machine is not guaranteed to run on another machine. It goes without saying that programs written in interpreted languages also need to be reduced to instructions that the target machine can understand. This process, however, takes place during runtime. The result is that, generally speaking, programs written in a compiled language are faster when executed than those written in an interpreted language. Data Types Another important difference with languages like PHP, Ruby, and JavaScript is that C is a typed language. What this means is that the data type a variable can hold needs to be explicitly specified. In C, the fundamental data types are characters ( char), integers ( int), and floating-point numbers ( float). From these fundamental types, a number of additional types are derived, such as double (double precision floating-point number), long (integer that can contain larger values), and unsigned (integer that can only contain positive values and therefore larger values). For a complete list of the basic C data types, I recommend taking a look at the Wikipedia page about C data types. Have you noticed that strings weren't mentioned in the list of basic C data types? A C string is stored as an array of chars. A char can store one ASCII character, which means that an array of chars can store a string. Take a look at the following example to see what this means in practice. The square brackets immediately after the variable name indicate that we are dealing with an array of chars. A C string is zero terminated, which means that the last character is 0. char firstName[] = "Bart"; Let's explore typing in more detail by comparing two code snippets. The first code snippet is written in JavaScript, whereas the second snippet is written in C. In JavaScript, a variable is generally declared with the var keyword. C doesn't have a keyword to declare variables. Instead, a variable in C is declared by prefixing the variable with a data type, such as int or char. var a = 5; var b = 13.456; var c = 'a'; int a = 5; float b = 13.456; char c = 'a'; Let's introduce some variables in the main function that we saw earlier. Change the body of the main function to look like the code snippet below. To print the variables using the printf function, we use format specifiers. For a more complete list of available format specifiers, visit this link.); return 0; } As we saw earlier, in C, typing isn't limited to variables. Functions also need to specify the type they return as well as the type of the arguments they accept. Let's see how this works. Functions I am assuming that you are already familiar with functions. As in other languages, a C function is a block of code that performs a specific task. Let's make main.c more interesting by introducing a function. Before the main function, we added a function prototype. It tells the compiler about the function, what type it returns, and what arguments it accepts. At the bottom of main.c, we insert the implementation of the function. All the function does is multiply the argument that is passed to the function by five and return the result. #include <stdio.h> int multiplyByFive(int a); // Function Prototype); // Functions printf("Five multiplied by five is %i\n", multiplyByFive(5)); return 0; } int multiplyByFive(int a) { return a * 5; } We've also updated the main function by invoking the multiplyByFive function. Note that a function prototype is not strictly necessary on the condition that the implementation of the function is placed before it is called for the first time. However, using function prototypes is useful as it allows developers to spread source code over multiple files and thereby keeping a project organized. If a function doesn't return a value, then the return type is declared as void. In essence, this means that no value is returned by the function. Take a look at the following example. Note that the function doesn't accept any arguments. The parentheses after a function's name are required even if the function doesn't accept any arguments. // Function Prototype void helloWorld(); // Function Implementation void helloWorld() { printf("Hello, World!\n"); } Before we move on, I want to mention that the C language doesn't have a function keyword for declaring a function like in JavaScript or PHP. The parentheses after the function name indicate that helloWorld is a function. The same is true for variables as I mentioned earlier. By prefixing a variable name with a type, the compiler knows that a variable is being declared. You may be wondering what the benefits are of a typed language, such as C. For programmers coming from Ruby or PHP, learning a typed language might be confusing at first. The main advantage of typing is that you are forced to be explicit about the behavior of the program. Catching errors at compile time is a major advantage as we will see later in this series. Even though C is a typed language, it is not a strongly typed language. Most C compilers provide implicit conversions (e.g., a char that is converted to an int). Structures What is a structure? Allow me to quote Kernighan and Ritchie. A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. Let's look at an example to see how structures work. Add the following code snippet right before the main function's return statement. // Structures struct Album { int year; int tracks; }; struct Album myAlbum; struct Album yourAlbum; myAlbum.year = 1998; myAlbum.tracks = 20; yourAlbum.year = 2001; yourAlbum.tracks = 18; printf("My album was released in %i and had %i tracks.\n", myAlbum.year, myAlbum.tracks); printf("Your album was released in %i and had %i tracks.\n", yourAlbum.year, yourAlbum.tracks); We start by declaring a new structure type and we give it a name of Album. After declaring the new type, we use it by specifying that the variable we are about to declare is a struct and we specify the struct's name, Album. The dot-notation is used to assign values to and read the values from the variables the struct holds. Pointers Pointers are often a bit of a stumbling block for people who want to learn C. The definition of a pointer is very simple though. A pointer is a variable that contains a memory address. Keep in mind that a pointer is just another C data type. Pointers are best understood with an example. Paste the following code immediately before the return statement of the main function. // Pointers int d = 5; int *e = &d; printf("d has a value of %i\n", d); printf("e has a value of %p\n", e); printf("the object that e points to has a value of %i\n", *e); We start by declaring an int and assigning a value to it. In the following line, we declare a pointer to int named e by prefixing the variable name with an asterisk. The ampersand before the variable d is a unary operator (a fancy name for an operator that has one operand) that is know as the address-of operator. In other words, by prefixing the variable d with an ampersand, our pointer e is given not the value of d, but the address in memory where the value of d is stored. Remember the definition of a pointer, it is a variable that contains the address of a variable. The print statements after the variable declarations will make this example clearer. Build and run the example and inspect the output in the console. The value of d is 5 as we expect. The second print statement might surprise you. The pointer named e contains a memory address, the place in memory where the value of d is stored. In the final statement, we use another unary operator, the dereferencing or indirection operator. What this operator does, is accessing the object that is stored at the location the pointer is pointing to. In other words, by using the dereferencing operator we retrieve the value of d. Remember, when a variable is declared in the C programming language, a block of memory is allocated for that variable. A pointer simply points to that block of memory. In other words, it holds a reference to the variable that is stored in the block of memory. Make sure that you understand the concept of pointers before moving on to the next article in which we take a look at Objective-C. Pointers are used all the time when working with objects. Don't worry if pointers don't immediately make sense after reading this article. It often takes some time to really grasp the concept. There is an excellent post written by Peter Hosey that I cannot recommend enough. Mind the Semicolon It seems as if semicolons are no longer hip. Ruby isn't fond of semicolons and the new cool kid in town, CoffeeScript, doesn't like them either. In C and Objective-C, semicolons are required at the end of every statement. The compiler is not very forgiving as you may have noticed. Conclusion There is more to the C programming language than what I've covered in this article. In the next article, however, I will talk about Objective-C and it will gradually improve your understanding of C. Once we start working with the iOS SDK, I'm sure you'll get the hang of working with objects and pointers in no time.
http://code.tutsplus.com/tutorials/learning-c-a-primer--mobile-13916
CC-MAIN-2014-15
refinedweb
2,952
65.01
QUESTIONS : 10.4,Explain why a characteristic of an efficient market is that investments in that market have zero NPVs. LO 1 7. Calculating Returns and Variability. Using the following returns, calculate the average returns, the variances, and the standard deviations for X and Y. Year x y 1 21% 24% 2 -16-3 3926 418-13 5430 (25)Using Return Distributions. Assuming that the returns from holding small-company stocks are normally distributed, what is the approximate probability that your money will double in value in a single year? What about triple in value? (11.1)The expected returns are just the possible returns multiplied by the associated probabilities: E(RA) = .10 .20 + .60 .10 + .30 .70 = 25% E(RB) = .10 .30 + .60 .20 + .30 .50 = 30% (11.10) Earnings and Stock Returns. As indicated by a number of examples in this chapter, earnings announcements by companies are closely followed by, and frequently result in, share price revisions. Two issues should come to mind. First: Earnings announcements concern past periods. If the market values stocks based on expectations of the future, why are numbers summarizing past performance relevant? Second: These announcements concern accounting earnings. Going back to Chapter 2, such earnings may have little to do with cash flow, so again, why are they relevant? 1. Determining Portfolio Weights. What are the portfolio weights for a portfolio that has 110 shares of Stock A that sell for $79 per share and 85 shares of Stock B that sell for $62 per share? LO 1 2. Portfolio Expected Return. You own a portfolio that has $1,500 invested in Stock A and $2,600 invested in Stock B. If the expected returns on these stocks are 10 percent and 16 percent, respectively, what is the expected return on the portfolio? LO 1 3. Portfolio Expected Return. You own a portfolio that is 25 percent invested in Stock X, 40 percent in Stock Y, and 35 percent in Stock Z. The expected returns on these three stocks are 10 percent, 13 percent, and 15 percent, respectively. What is the expected return on the portfolio? (6)Based on the following information, calculate the expected return. state of economy probability of state of economy rate of returns if state occurs recession .25-.09 normal .45.11 boom.30.30 (9)rate of returns if state occurs State of economy prob of state of economy stock a stock b stock c boom.65.08.02.23 bust.35.12.18-.03 a What is the expected return on an equally weighted portfolio of these three stocks? B What is the variance of a portfolio invested 20 percent each in A and B and 60 percent in C? Estimated time: 24 hours Estimated amount: $60 Now at $30 's common stock is 1.25, and the market return (Km) is 13%. If the Treasury bill rate (Rf) is 5%, what is the company's cost of capital? (Assume no taxes.) Question #5 A project has an... at an interest rate of 10 percent, and (2) issuance of new common stock at $25 per share. Currently the company is financed equally by debt and equity as follows: ... to a corporate tax rate of 28 per cent. a. What is the expected return on Green’s equity before the announcement of the debt issue? b. Construct Green’s market value balance... The Raattama Corporation had sales of $3.5 million last year, and it earned a 5% return (after taxes) on sales. Recently, the company has fallen behind in its accounts payable. Although The Raattama Corporation had sales of $3.5 million last year, and it earned a 5 percent return, after taxes, on sales. Recently, the company has fallen behind in its accounts payable By creating an account, you agree to our terms & condition We don't post anything without your permission Rating: (37 Reviews) (9 Reviews) (22 Reviews) (62 Reviews) (15 Reviews) (5 Reviews) (18 Reviews) Chat now
http://www.transtutors.com/questions/finance-in-business-world--522859.htm
CC-MAIN-2014-35
refinedweb
663
66.94
(Also published on Canonical’s design team blog) The weekend before last, I went to PyCon UK 2015. I already wrote about the keynotes, which were more abstract. Here I’m going to talk about the other talks I saw, which were generally more technical or at least had more to do with Python. Summary The talks I saw covered a whole range of topics - from testing through documentation and ways to achieve simplicity to leadership. Here are some key take-aways: - Technical leaders should take every opportunity practice various leadership styles - Instead of answering questions about how to use software directly, try pair documenting - Ask users for as little of their data as possible, and be permissive in your validation - Hypothesis is a useful library for generating test cases - keep it in mind - “Simplicity is about defaults” - make the interfaces for your software as simple as possible - It’s worthwhile practicing humility and patience in technical discussions - FIDO’s U2F and UAF standards are just starting to gain support - keep an eye on them - Python has some good tools for managing data The talks Following are slightly more in-depth summaries of the talks I thought were interesting. Friday 15:30: Leadership of Technical Teams - Owen Campbell There were two key points I took away from this talk. The first was Owen’s suggestion that leaders should take every opportunity to practice leading. Find opportunities in your personal life to lead teams of all sorts. The second point was more complex. He suggested that all leaders exist on two spectra: - Amount of control: hand-off to dictatorial - Knowledge of the field: novice to expert The less you know about a field the more hands-off you should be. And conversely, if you’re the only one who knows what you’re talking about, you should probably be more of a dictator. Although he cautioned that people tend to mis-estimate their ability, and particularly when it comes to process (e.g. agile), people think they know more than they do. No-one is really an expert on process. He suggested that leading technical teams is particularly challenging because you slide up and down the knowledge scale on a minute-to-minute basis sometimes, so you have to learn to be authoritative one moment and then permissive the next, as appropriate. 17:00: Document all the things - Kristian Glass Kristian spoke about the importance, and difficulty, of good documentation. Here are some particular points he made: - Document why a step is necessary, as well as what it is - Remember that error messages are documentation - Try pair documentation - novice sitting with expert - Checklists are great - Stop answering questions face-to-face. Always write it down instead. - Github pages are better than wikis (PRs, better tracking) One of Kristian’s main points was that it goes against the grain to write documentation, ‘cos the person with the knowledge can’t see why it’s important, and the novice can’t write the documentation.. Saturday 11:00: Asking About Gender - the Whats, Whys and Hows - Claire Gowler Claire spoke about how so many online forms expect people to be either simply “male” or “female”, when the truth can be much more complicated.. 11:30: Finding more bugs with less work - David R. MacIver David MacIver is the author of the Hypothesis testing library. Hypothesis is a Python library for creating unit tests which are simpler to write and more powerful when run, finding edge cases in your code you wouldn’t have thought to look for. It is stable, powerful and easy to add to any existing test suite. When we write tests normally, we choose the input cases, and we normally do this and we often end up being really kind to our tests. E.g.: def test_average(): assert my_average([2, 4]) == 3 What Hypothesis does it help us test with a much wider and more challenging range of values. E.g.: from hypothesis.strategies import lists, floats @given(lists(floats())) def test_average(float_list): ave = reduce(lambda x, y: x + y, float_list) / len(float_list) assert average(float_list) == ave There are many cases where Hypothesis won’t be much use, but it’s certainly good to have in your toolkit. Sunday 10:00: Simplicity Is A Feature - Cory Benfield Cory presented simplicity as the opposite of complexity - that is, the fewer options something gives you, the more simple and straightforward it is. “Simplicity is about defaults” To present as simple an interface as possible, the important thing is to have many sensible defaults as possible, so the user has to make hardly any choices. Cory was heavily involved in the Python Requests library, and presented it as an example of how to achieve apparent simplicity in a complex tool. “Simple things should be simple, complex things should be possible” He suggested thinking of an “onion model”, where your application has layers, so everything is customisable at one of the layers, but the outermost layer is as simple as possible. He suggested that 3 layers is a good number: - Layer 1: Low-level - everything is customisable, even things that are just for weird edge-cases. - Layer 2: Features - a nicer, but still customisable interface for all the core features. - Layer 3: Simplicity - hardly any mandatory options, sensible defaults - People should always find this first - Support 80% of users 80% of the time - In the face of ambiguity do the right thing He also mentioned that he likes README driven development, which seems like is an interesting approach. 11:00: How (not) to argue - a recipe for more productive tech conversations - Harry Percival I think this one could be particularly useful for me. Harry spoke about how many people (including him) have a very strong need to be right. Especially men. Especially those who went to boarding school. And software development tends to be full of these people. Collaboration is particularly important in open source, and strongly disagreeing with people rarely leads to consensus, in fact it’s more likely to achieve the opposite. So it’s important that we learn how to get along. He suggests various strategies to try out, for getting along with people better: - Try simply giving in, do it someone else’s way once in a while (hard to do graciously) - Socratic dialogue: Ask someone to explain their solution to you in simple terms - Dogfooding - try out your idea before arguing for its strength - Bide your time: Wait for the moment to see how it goes - Expose yourself to other cultures, where arguments are less acceptable All of this comes down to stepping back, waiting and exercising humility. All of which are easier said than done, but all of which are very valuable if I could only manage it. 11:30: FIDO - The dog ate my password - Alex Willmer After covering fairly common ground of how and why passwords suck, Alex introduced the FIDO alliance. The FIDO alliance’s goal is to standardise authentication methods and hopefully replace passwords. They have created two standards for device-based authentication to try to replace passwords: - UAF: First-factor passwordless biometric authentication - U2F: Second-factor device authentication Browsers are just starting to support U2F, whereas support for UAF is farther off. Keep an eye out. 14:30: Data Visualisation with Python and Javascript - crafting a data-visualisation for the web - Kyran Dale Kyran demoed using Scrapy and Pandas to retrieve the Nobel laureatte data from Wikipedia, using Flask to serve it as a RESTful API, and then using D3 to create an interactive browser-based visualisation.
https://development.robinwinslow.uk/2015/09/29/pycon-python-learnings/
CC-MAIN-2017-43
refinedweb
1,263
53.85
Input editor with extended functionality. More... #include <CExtLineEdit.h> Input editor with extended functionality. It's possible to add an icon to the edit field or insert additional widgets (e.g control buttons) into the view. Definition at line 31 of file CExtLineEdit.h. Definition at line 36 of file CExtLineEdit.h. Construct a line edit with the given properties. Add a widget to the line edit area according to alginmentFlags. Only Qt::AlignLeft and Qt::AlignRight are possible. widgetobject. Get the startup text. Get editor text. Set the icon, that will appeared on the left side of the line edit. Set the text, that will be shown at the first time the editor becomes visible. © 2007-2017 Witold Gantzke and Kirill Lepskiy
http://ilena.org/TechnicalDocs/Acf/classiwidgets_1_1_c_ext_line_edit.html
CC-MAIN-2018-51
refinedweb
123
54.69
On Thu, Jul 26, 2012 at 5:34 AM, Jeff Layton <jlayton redhat com> wrote: > On Wed, 18 Jul 2012 14:30:41 -0700 > Peter Moody <pmoody google com> wrote: > >> Additionally it looks like audit_free_names might return too early when >> AUDIT_DEBUG was set to 2. >> >> Signed-off-by: Peter Moody <pmoody google com> >> --- >> kernel/auditsc.c | 8 ++++---- >> 1 files changed, 4 insertions(+), 4 deletions(-) >> >> diff --git a/kernel/auditsc.c b/kernel/auditsc.c >> index 4b96415..0c1db46 100644 >> --- a/kernel/auditsc.c >> +++ b/kernel/auditsc.c >> @@ -997,6 +997,7 @@ static inline void audit_free_names(struct audit_context *context) >> >> #if AUDIT_DEBUG == 2 >> if (context->put_count + context->ino_count != context->name_count) { >> + int i = 0; >> printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d" >> " name_count=%d put_count=%d" >> " ino_count=%d [NOT freeing]\n", >> @@ -1005,11 +1006,10 @@ static inline void audit_free_names(struct audit_context *context) >> context->name_count, context->put_count, >> context->ino_count); >> list_for_each_entry(n, &context->names_list, list) { >> - printk(KERN_ERR "names[%d] = %p = %s\n", i, >> + printk(KERN_ERR "names[%d] = %p = %s\n", i++, >> n->name, n->name ?: "(null)"); >> } >> dump_stack(); >> - return; >> } > > I'm not certain what the intent of this code was, but if you remove the > "return" above, then the printk above it that says "[NOT FREEING]". Will > no longer be valid. Oh, good point. I was going from what I presumed the intent to be from the comment from above __audit_syscall_exit /** *(). */ (and I am assuming that 'in call cases' is a typo for 'in all cases') The other thing is that my testing indicated that my box hung if audit_free_names returned right there. I need to wait for Eric anyway; hopefully he'll be able to shed some light. Cheers, peter >> #endif >> #if AUDIT_DEBUG >> @@ -2084,10 +2084,10 @@ void audit_putname(const char *name) >> __FILE__, __LINE__, context->serial, name); >> if (context->name_count) { >> struct audit_names *n; >> - int i; >> + int i = 0; >> >> list_for_each_entry(n, &context->names_list, list) >> - printk(KERN_ERR "name[%d] = %p = %s\n", i, >> + printk(KERN_ERR "name[%d] = %p = %s\n", i++, >> n->name, n->name ?: "(null)"); >> } >> #endif -- Peter Moody Google 1.650.253.7306 Security Engineer pgp:0xC3410038
https://www.redhat.com/archives/linux-audit/2012-July/msg00058.html
CC-MAIN-2016-50
refinedweb
341
62.88
[Solved] Https page works in Windows but not in Linux Hi everybody, I wrote a small program under Linux which uses QWebView to display Web pages. When I tested this with HTTPS sites I stumbled upon a site () which results in a blank page. I tried the exact same code under Windows and there everything works. The only difference I saw was that under Windows the onSslError() displays 'The certificate has expired' message which I didn't see under Linux. Under Linux it doesn't display any error message! The only other difference I noticed was that under Windows the OpenSSL ssleay32.dll version 0.9.8.14 is used but under Linux it's libssl.so.1.0.0 I also tested another QtWebKit based browser (Arora 0.11.0) (but only under Linux) and it shows the same blank page and it gets stuck at 10%. But when I used the KDE rekonq browser or Googles Chrome, then the page gets loaded. So It seems to me it is not a WebKit problem, but they are obviously doing something differently then the plain QtWebKit based browsers. But I'm not an SSL expert, so I don't know whether I'm supposed to do something different under Linux and I was not able to find out what rekonq is doing differently. Out of sheer desperation I even build Qt5 and tested my program with it, just to see whether it might be a (fixed) bug in Qt, but it shows the same blank page. I'm running out of ideas, so if somebody could give me a hint what I have to do, it would be greatly appreciated. My environment is: - Kubuntu 12.04 (64-Bit) / Windows XP (32-Bit) - QtSdk 1.2.1 (Qt 4.8.1) (Windows and Linux) Regards Peter PS: I tried the solution from this thread but this didnt' help mainwindow.h: @ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtGui/QMainWindow> #include <QtNetwork/QNetworkReply> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); private slots: void onSslErrors(QNetworkReply* reply, const QList<QSslError> &errors); }; #endif // MAINWINDOW_H @ mainwindow.cpp: @ #include "mainwindow.h" #include <QDebug> #include <QtGui/QApplication> #include <QtWebKit/QWebView> #include <QtNetwork/QSslError> #include <QtNetwork/QSslConfiguration> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWebView *view = new QWebView( this ); connect(view->page()->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )), this, SLOT(onSslErrors(QNetworkReply*, const QList<QSslError> & ))); view->load( QUrl( "")); view->show(); setCentralWidget( view ); } void MainWindow::onSslErrors(QNetworkReply* reply, const QList<QSslError> &errors) { qDebug() << "onSslErrors: "; foreach (QSslError e, errors) qDebug() << "ssl error: " << e; reply->ignoreSslErrors(); } int main(int argc, char *argv[]) { QApplication application(argc, argv); Q_ASSERT( QSslSocket::supportsSsl() ); MainWindow w; w.show(); return application.exec(); } @ @ #------------------------------------------------- Project created by QtCreator 2012-08-18T12:25:22 #------------------------------------------------- QT += core gui webkit network CONFIG += debug TARGET = WebViewBrowser TEMPLATE = app SOURCES += mainwindow.cpp HEADERS += mainwindow.h @ Have tested it right now with QT 4.7.4 & 4.8.3(own compilation) on my LFS 64-bit and Ubuntu 12.04 32-bit, works just fine... Seems to be openssl problem on your linux distribution... Hi, thank you for the test! Could you tell me what version of openssl is installed on your machines? This might help me in narrowing down the problem. But what I don't understand then is, if Chrome and rekonq are QtWebKit based and hence use openssl, why do they work? Regards Peter On LFS 64-bit it is: @OpenSSL 1.0.0c 2 Dec 2010@ On ubuntu 12.04 32-bit: @OpenSSL 1.0.1c 10 May 2012@ But like I said - I have compiled Qt by myself... That can be the reason too... I've compiled Qt5 myself and it didn't work, so I don't think that is the problem. I'm not (yet) an SSL expert and I hoped I can avoid becoming one ;-) , but my current guess is that is has something to do with the certificates installed on my machine. The biggest problem is that I'm not getting any error message what so ever, which would give me a hint to what is wrong. Regards Peter So, your onSslErrors function didn't even get fired? Can you try to download website certificate and test it with "QSslCertificate": ? And maybe playing with "QSslConfiguration": can help you... [quote]So, your onSslErrors function didn't even get fired?[/quote] No, not in Linux. But on windows (as i wrote ;-) ) I did get ‘The certificate has expired’. [quote]Can you try to download website certificate and test it with "QSslCertificate": ? [/quote] Well, that's why I said I'm not an SSL expert ;-) Could you give me some pointers on how to do this and what I have to look for? Thank you for your help. Regards Peter Ok, i have started fresh Ubuntu 12.04 under VirutalBox and can see the same problem. The problem is in the openssl. You can test it by yourself.(in console) @ openssl s_client -showcerts -connect @ It will stack right after connection is established. SSL certificate from website uses TLSv1 , no idea why original openssl from Ubuntu can't just switch right to TLSv1 protocol.... Using following option works just fine: @openssl s_client -showcerts -tls1 -connect So, try to set following ssl configuration for QNetworkAccessManager of your WebPage: @QSslConfiguration config = sslSocket.sslConfiguration(); config.setProtocol(QSsl::TlsV1);@ OK, so I modified main() like this: @ int main(int argc, char *argv[]) { QApplication application(argc, argv); Q_ASSERT( QSslSocket::supportsSsl() ); QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration(); sslConfig.setProtocol( QSsl::TlsV1 ); QSslConfiguration::setDefaultConfiguration( sslConfig ); Q_ASSERT(QSslConfiguration::defaultConfiguration().protocol() == QSsl::TlsV1); MainWindow w; w.show(); return application.exec(); } @ which I hope is correct because I couldn't figure out how I get the 'sslSocket' from the QNetworkAccessManager. But it didn't change anything :-( One think I noted though was when I ran one of the openssl commands you gave me, I get: 'Verify return code: 20 (unable to get local issuer certificate)' and then it just hangs. It is known BUG in Ubuntu, where is a lot BUGs around this problem with openssl. For example: "Bug #965371": I have tested it too with QSslConfiguration::setDefaultConfiguration and with QNetworkAccessManager(subclassing QNAM and overriding createRequest function), it just doesn't work... Looks like Qt BUG, because sslConfig.setProtocol( QSsl::TlsV1 ); should work, and work in openssl client and in Python using openssl too. Maybe you can try to rebuild openssl for your Ubuntu... [quote]Maybe you can try to rebuild openssl for your Ubuntu... [/quote] I will try that and update this thread with the result. Thank you for your time and effort! Regards Peter So I build the OpenSSL version 1.0.1c and made sure the newly build shared libraries are picked up from my test application: @ lsof -p 9052 | grep ssl WebViewBr 9052 peter mem REG 8,1 470813 9569610 /usr/local/ssl/lib/libssl.so.1.0.0 WebViewBr 9052 peter mem REG 8,1 2194319 9569606 /usr/local/ssl/lib/libcrypto.so.1.0.0 @ but nothing changed. To be honest, I didn't think it could be an openssl bug because if it were then the questions remains why are Chrome and rekonq working? So the only option which remains is to wade through the rekonq and KDE Network source and try to find out what it does different :-( If anybody has another idea or hint, please let me know. Regards Peter Finally I got it to work! :-) I don't quite understand it completely yet, but I do understand that openssl on 12.04 seems to be really messy after all the bug reports I've read. But anyway, I simply had to replace: @ sslConfig.setProtocol( QSsl::TlsV1 ); @ with @ sslConfig.setProtocol( QSsl::SslV3 ); @ then at least for this specific site it works and for now this is good enough for me. Thanks again AcerExtensa! Regards Peter
https://forum.qt.io/topic/19195/solved-https-page-works-in-windows-but-not-in-linux
CC-MAIN-2017-43
refinedweb
1,303
66.03
This column shows you how to secure the .NET Services Bus and also provides some helper classes and utilities to automate many of the details. Juval Lowy MSDN Magazine July 2009 Read more! Paul DiLascia MSDN Magazine July 2005 MSDN Magazine November 2005 MSDN Magazine October 2005 MSDN Magazine May 2005 This month DLL problems, context menus, MFC strings to managed C++, and more. MSDN Magazine October 2006 James Avery does it again with his popular list of developer tools. This time he covers the best Visual Studio add-ins available today that you can download for free. James Avery MSDN Magazine December 2005 // reference class ref class A { void f() const; // NOT! }; field public static int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) g_private = int32(0x00000001) //////////////////////////////////////////////////////////////// // To compile type: // cl /clr const.cpp // #include <stdio.h> ref class A { int m_val; // const data member allowed, will generate modopt static const int g_private = 1; public: // public const member could be modified by Visual Basic or other // programs that don't know const -- so use literal instead. literal int g_public = 1; A(int i) { m_val = i; } void print(); // const; // NO!--const fn not allowed }; void A::print() { printf("Val is %d\n",m_val); } int main() { A a(17); a.print(); } // ref class R as local variable void f() { R r; // ref class on stack??? r.DoSomething(); ... } // how the compiler sees it. void f() { R^ r = gcnew R; // allocate on gc heap try { r->DoSomething(); ... } finally { delete r; } }
http://msdn.microsoft.com/en-us/magazine/cc163484.aspx
crawl-002
refinedweb
245
58.08
The JRuby community is pleased to announce the release of JRuby 1.1.6 Download: JRuby 1.1.6 is the sixth Key Summary JRUBY-441 Java integration code does not report errors well JRUBY-1133 $KCODE is ignored when multibyte character is used inside regular expression JRUBY-1181 Rake batch file for Windows environments JRUBY-1476 jruby.home extraction / jar-complete / content mismatch JRUBY-1489 Adding encapulated parse methods for external uses, such as JSR223 API implementation JRUBY-1801 Support Ruby 1.9 stabby lambda syntax JRUBY-2028 LocalJumpError is displayed when a block is invoked in a java thread. JRUBY-2183 handling method_missing is slower than in MRI JRUBY-2198 Array#sort is slower than MRI JRUBY-2209 An Interrupt wipes out END {} blocks JRUBY-2210 permissions on $JRUBY_HOME/lib/ruby/gem/1.8 not wide enough JRUBY-2224 jirb breaks method_added for classes JRUBY-2279 JRuby's Signal pollutes Kernel namespace with signal-specific constants JRUBY-2290 form.datetime_select not working with IE in 1.1RC2 (but does with Firefox) JRUBY-2301 JRuby script would work when java is installed but JAVA_HOME not set JRUBY-2380 Thread.list has a race condition JRUBY-2546 Using reflection to set a String on a field results in an error JRUBY-2602 Lots of Readline::HISTORY rubyspec failures JRUBY-2613 Readline.readline wants two arguments JRUBY-2703 Indexed methods are no longer supported, and options and code related to them should be removed or deprecated. JRUBY-2746 jruby -S flag does not search PATH, not support relative locations within PATH JRUBY-2780 RegexpError: target of repeat operator is invalid JRUBY-2798 File.open rubyspec failure on Mac OS X, Soylatte JRUBY-2799 Need some mechanism to call masked java methods (initialize) JRUBY-2834 More than 50 RubySpec failures for ARGF JRUBY-2852 rcov.rb:654:in `aggregate_data': NilClass can't be coerced into Fixnum (TypeError) when running jruby -S rake spec:rcov JRUBY-2948 Exceptions do not cut off at binding evals after change reported in JRUBY-2945 JRUBY-3078 require should be made either threadsafe or guaranteed to run the discovered file exactly once JRUBY-3104 Ruby 1.9 parser support JRUBY-3107 Ability to get extra position information from DefaultRubyParser JRUBY-3108 a REXML XPath query fails to run correctly JRUBY-3111 JRuby does not handle '@' sign in YAML file correctly. JRUBY-3112 Some Ruby instances are not roundtripping from Ruby to Java and back JRUBY-3117 Constant lookup from method inside class ::Object is incorrect JRUBY-3118 Creating a subclass of MatchData that's instantiable blows up because there's no allocator JRUBY-3122 Arity.required(3) ends up reporting the wrong arity JRUBY-3126 Allow Rubygems to be loaded and used from within jar files JRUBY-3130 JRuby selects wrong static method on Java class JRUBY-3131 obj.send :binding does not set the binding's 'self' to obj JRUBY-3132 String.split is broken JRUBY-3133 'jgem update' causes: java.lang.AssertionError: UpdateCommand is not interned JRUBY-3134 Define RubyRange.min/max JRUBY-3135 RubyException doesn't define to_str JRUBY-3138 import 'java.lang' and similar break due to missing PackageSearch class JRUBY-3140 Const lookup failures in precompiled specs JRUBY-3141 Array index error in JCodings running latest String#rindex specs JRUBY-3145 Module#include detects cyclic includes JRUBY-3149 Float#to_s returns a string representation of self, possibly Nan, -Infinity, +Infinity JRUBY-3155 TCPSocket#puts block when the socket is waiting in read JRUBY-3156 Import of Java classes in "main" object has no effect JRUBY-3161 java interface in base class cannot implement in derived class JRUBY-3162 Dir.glob does not like encodings, and will fail when used with File.expand_path JRUBY-3172 Error in YAML.dump JRUBY-3173 require in 1.1.5 prefers files in the current directory despite loadpath (even with "." removed) JRUBY-3176 Thread#wakeup doesn't wake up a sleeping thread JRUBY-3181 [PATCH] Stack trace lost when re-raising an exception JRUBY-3182 Symlink doesn't work with relative path destinations and Dir.chdir JRUBY-3185 Ruby.descriptors was leaking endless WeakReferences (with Integer key). JRUBY-3188 NPE when loading file in tzinfo (used by ActiveSupport) JRUBY-3189 java.lang.Iterable should have an each method JRUBY-3191 Including same Java interface twice causes ClassFormatError JRUBY-3192 Return type coercion to java interfaces broken by new JI JRUBY-3195 jruby-openssl fails to load but reports no error JRUBY-3197 Fix "undefined method `uid' for nil:NilClass" problem with Rubygems 1.3.1 JRUBY-3198 String#slice! not working correctly when used with string read from file JRUBY-3201 JRubyApplet failing when using TrivialFacade. JRUBY-3209 "java -jar jruby-complete.jar -S jirb" does not run if ~/.jruby exists JRUBY-3210 the ./ behavior with load is not MRI compatible JRUBY-3213 for loop broken for 1.9 JRUBY-3217 Memory Leak with Adopted Threads JRUBY-3225 [Regression] slowdown in Jruby 1.1.6RC2 using Rails 2.1.1 JRUBY-3230 Hpricot broke from 1.5 to 1.6 JRUBY-3233 JRuby with Rails 2.2.2 unable to instantiate a java class JRUBY-3234 Difference in require behaviour with MRI with ".rb" suffix
http://docs.codehaus.org/display/JRUBY/2008/12/17/JRuby+1.1.6+Released
CC-MAIN-2014-35
refinedweb
868
54.52
Asked by: BStrings General discussion - Hi I've mentioned BSTRINGs, ASCII and Unicode a few times. So for those of you interested in what happens under the hood, here's an old MSDN article that I personally think is very interesting (especially when hadnling the Win32 APIs in BASIC): Allan Article 3. Strings the OLE Way Bruce McKinney April 18, 1996 Introduction The difference between Microsoft® Visual Basic® strings and Visual C++® strings is the difference between "I'll do it" and "You do it." The C++ way is fine for who it's for, but there aren't many programmers around anymore who get a thrill out of allocating and destroying their own string buffers. In fact, most C++ class libraries (including the Microsoft Foundation Classes, or MFC) provide string classes that work more or less on the Basic model, which is similar to the model of Pascal and FORTRAN. When you manage an array of bytes (or an array of books or beer bottles or babies), there are two ways of maintaining the lengths. The marker system puts a unique marker at the end of the array. Everything up to the marker is valid. The count system adds a special array slot containing the number of elements. You have to update the count every time you resize the array. Both systems have their advantages and disadvantages. The marker system assumes you can find some unique value that will never appear in the array. The count system requires tedious bookkeeping to keep the count accurate. The C language and most of its offspring uses the marker system for storing strings, with the null character as the marker. All the other languages I know use the count system. You might argue that the majority indicates the better choice, but even if you buy that, C still gets the last laugh. Many of the leading operating systems of the world (all the flavors of Unix®, Windows®, and OS/2®, for example) expect strings passed to the system to be null-terminated. As a result, languages such as Pascal and FORTRAN support a special null-terminated string type for passing strings to the operating system. Basic doesn't have a separate type for null-terminated strings, but it has features that make passing null-terminated strings easy. As a language-independent standard, OLE can't afford to take sides. It must accommodate languages in which null is not a special character, but it must also be able to output null-terminated strings for its host operating system. More importantly, OLE recognizes that requiring the operating system to manage strings is inherently more stable and reliable in a future computing world where strings may be transferred across process, machine, and eventually Internet boundaries. I've been told that the name BSTR is a compression of Basic STRing, but in fact a BSTR looks a lot more like a Pascal string than like the strings Basic old-timers remember. In any case, C++ programmers have some unlearning to do when it comes to writing strings for OLE. But before you can get into BSTR details, you need to clearly understand the difference between Unicode™ and ANSI strings. Unicode vs. ANSI Stringwise, we are cursed to live in interesting times. The world according to Microsoft (and many other international companies) is moving from ANSI to Unicode characters, but the transition isn't exactly a smooth one. Most of the Unicode confusion comes from the fact that we are in the midst of a comprehensive change in the way characters are represented. The old way uses the ANSI character set for the first 256 bytes, but reserves some characters as double-byte character prefixes so that non-ANSI character sets can be represented. This is very efficient for the cultural imperialists who got there first with Latin characters, but it's inefficient for those who use larger character sets. Unicode represents all characters in two bytes. This is inefficient for the cultural imperialists (although they still get the honor of claiming most of the first 128 characters with zero in the upper byte), but it's more efficient (and more fair) for the rest of the world. Different Views of Unicode Eventually, everybody will use Unicode, but nobody seems to agree on how to deal with the transition. - Windows 3.x—Doesn't know a Unicode from a dress code, and never will. - 16-bit OLE—Ditto. - Windows NT®—Was written from the ground up first to do the right thing (Unicode) and secondly to be compatible (ANSI). All strings are Unicode internally, but Windows NT also completely supports ANSI by translating internal Unicode strings to ANSI strings at run time. Windows NT programs that use Unicode strings directly can be more efficient by avoiding frequent string translations, although Unicode strings take about twice as much data space. - Windows 95—Uses ANSI strings internally. Furthermore, it doesn't support Unicode strings even indirectly in most contexts—with one big exception. - 32-bit OLE—Was written from the ground up to do the right thing (Unicode) and doesn't do ANSI. The OLE string types—OLESTR and BSTR—are Unicode all the way. Any 32-bit operating system that wants to do OLE must have at least partial support for Unicode. Windows 95 has just enough Unicode support to make OLE work. - Visual Basic—The designers had to make some tough decisions about how they would represent strings internally. They might have chosen ANSI, because it's the common subset of Windows 95 and Windows NT, and converted to Unicode whenever they needed to deal with OLE. But since Visual Basic 4.0 is OLE inside and out, they chose Unicode as the internal format, despite potential incompatibilities with Windows 95. The Unicode choice caused many problems and inefficiencies both for the developers of Visual Basic and for Visual Basic developers—but the alternative would have been worse. - The Real World—Most existing data files use ANSI. The .WKS, .DOC, .BAS, .TXT, and most other standard file formats use ANSI. If a system uses Unicode internally but needs to read from or write to common data formats, it must do Unicode-to-ANSI conversion. Someday there will be Unicode data file formats, but today they're pretty rare. What does this mean for you? It means you must make choices about any program you write: - If you write using Unicode internally, your application will run only on Windows NT, but it will run faster. Everything is Unicode, inside and out. There are no string translations—except when you need to write string data to standard file formats that use ANSI. An application written this way won't be out-of-date when some future iteration of Windows 9x gets Unicode. - If you write using ANSI internally, your application will run on either Windows NT or Windows 95, but it will run slower under Windows NT because there are a lot of string translations going on in the background. An application written this way will someday be outdated when the whole world goes Unicode, but it may not happen in your lifetime. The obvious choice for most developers is to use the ANSI version because it works right now for all 32-bit Windows platforms. But I'd like to urge you to take a little extra time to build both versions. If you choose to write your application using both ANSI and Unicode, Win32® and the C run-time library both provide various types and macros to make it easier to create portable programs from the same source. To use them, define the symbol _UNICODE for your Unicode builds and the symbol _MBCS for your ANSI builds. The samples already have these settings for the Microsoft Developer Studio. Note As far as this article is concerned, there is no difference between double-byte character strings—DBCS—and multi-byte character strings—MBCS. Similarly, "wide character" and "Unicode" are synonymous in the context of this article. A WCHAR Is a wchar_t Is an OLECHAR Just in case you're not confused enough about ANSI and Unicode strings, everybody seems to have a different name for them. Furthermore, there's a third type of string called a single-byte character string (SBCS), which we will ignore in this article. In the Win32 API, ANSI normally means MBCS. The Win32 string functions (lstrlenA, lstrcpyA, and so on) assume multi-byte character strings, as do the ANSI versions of all application programming interface (API) functions. You also get Unicode versions (lstrlenW, lstrcpyW). Unfortunately, these aren't implemented in Windows 95, so you can't use them on BSTRs. Finally, you get generic macro versions (lstrlen, lstrcpy) that depend on whether you define the symbol UNICODE. The C++ run-time library is even more flexible. For each string function, it supports a single-byte function (strlen); a multi-byte function (_mbslen); a wide character (wcslen), and a generic macro version (_tcslen) that depends on whether you define _UNICODE, _MBCS, or _SBCS. Notice that the C run-time library tests _UNICODE while Win32 tests UNICODE. We get around this by defining these to be equivalent in OLETYPE.H. Win32 provides the MultiByteToWideChar and WideCharToMultiByte functions for converting between ANSI and Unicode. The C++ run-time library provides the mbstowcs and wcstombs functions for the same purpose. The Win32 functions are more flexible, but not in any way that matters for this article. We'll use the simpler run-time versions. Types also come in Unicode and ANSI versions, but to add to the confusion, OLE adds its own types to those provided by Win32 and ANSI. Here are some of the types and type coercion macros you need to be familiar with: Do you notice a little redundancy here? A little inconsistency? The sample code uses the Win32 versions of these types, except when there isn't any Win32 version or the moon is full. In normal C++ programming, you should use the generic versions of functions and types as much as possible so that your strings will work in either Unicode or ANSI builds. In this series, the String class hides a lot of the detail of making things generic. Generally it provides overloaded ANSI and Unicode versions of functions rather than using generic types. When you have a choice, you should use Unicode strings rather than ANSI or generic strings. You'll see how and why this nontypical coding style works later. Note Versions of Visual C++ before 4.0 had a DLL called OLE2ANSI that automatically translated OLE Unicode strings to ANSI strings behind the scenes. This optimistic DLL made OLE programming simpler than previously possible. It was indeed pleasant to have the bothersome details taken care of, but performance-wise, users were living in a fool's paradise. OLE2ANSI is history now, although conditional symbols for it still exist in the OLE include files. The OLECHAR type, rather than the WCHAR type, was used in OLE prototypes so that it could be transformed into the CHAR type by this DLL. Do not define the symbol OLE2ANSI in the hopes that OLE strings will magically transform themselves into ANSI strings. There is no Santa Claus.. That's the technical difference. The philosophical difference is that the contents of BSTRs are sacred. You're not allowed to modify the characters except according to very strict rules that we'll get to in a minute. OLE provides functions for allocating, reallocating, and destroying BSTRs. If you own an allocated BSTR, you may modify its contents as long as you don't change its size. Because every BSTR is, among other things, a pointer to a null-terminated string, you may pass one to any string function that expects a read-only (const) C string. The rules are much tighter for passing BSTRs to functions that modify string buffers. Usually, you can only use functions that take a string buffer argument and a maximum length argument. All the rules work on the honor system. A BSTR is a BSTR by convention. Real types can be designed to permit only legal operations. Later we'll define a C++ type called String that does its best to enforce the rules. The point is that BSTR servers are honor-bound to follow the rules so that BSTR clients can use strings without even knowing that there are rules. The BSTR System Functions My descriptions of the OLE BSTR functions are different from and, in my opinion, more complete than the descriptions in OLE documentation. I had to experiment to determine some behavior that was scantily documented, and I checked the include files to get the real definitions, so I am confident that my descriptions are valid and will work for you. For consistency with the rest of the article, the syntax used for code in this section has been normalized to use Win32 types such as LPWSTR and LPCWSTR. The actual prototypes in OLEAUTO.H use const OLECHAR FAR * (ignoring the equivalent LPCOLESTR types). The original reasons for using OLECHAR pointers rather than LPCWSTRs don't matter for this article. You need to read this section only if you want to fully understand how the String class (presented later) works. But you don't really need to understand BSTRs in order to use the string class. BSTR SysAllocString(LPCWSTR wsz); Given a null-terminated wide character string, allocates a new BSTR of the same length and copies the string to the BSTR. This function works for empty and null strings. If you pass in a null string, you get back a null string. You also get back a null string if there isn't enough memory to allocate the given string. Example: // Create BSTR containing "Text" bs = SysAllocString(L"Text") BSTR SysAllocStringLen(LPCWSTR wsz, unsigned len); Given a null-terminated wide-character string and a maximum length, allocates a new BSTR of the given length and copies up to that length of characters from the string to the BSTR. If the length of the copied string is less than the given maximum length, a null character is written after the last copied character. The rest of the requested length is allocated, but not initialized (except that there will always be a null character at the end of the BSTR). Thus the string will be doubly null-terminated—once at the end of the copied characters and once at the end of the allocated space. If NULL is passed as the string, the whole length is allocated, but not initialized (except for the terminating null character). Don't count on allocated but uninitialized strings to contain null characters or anything else in particular. It's best to fill uninitialized strings as soon after allocation as possible. Example: // Create BSTR containing "Te" bs = SysAllocStringLen(L"Text", 2) // Create BSTR containing "Text" followed by \0 and a junk character bs = SysAllocStringLen(L"Text", 6) BSTR SysAllocStringByteLen(LPSTR sz, unsigned len); Given a null-terminated ANSI string, allocates a new BSTR of the given length and copies up to that length of bytes from the string to the BSTR. The result is a BSTR with two ANSI characters crammed into each wide character. There is very little you could do with such a string, and therefore not much reason to use this function. It's there for string conversion operations such as Visual Basic's StrConv function. What you really want is a function that creates a BSTR from an ANSI string, but this isn't it (we'll write one later). The function works like SysAllocStringLen if you pass a null pointer or a length greater than the length of the input string. BOOL SysReAllocString(BSTR * pbs, LPWSTR wsz); Allocates a new BSTR of the same length as the given wide-character string, copies the string to the BSTR, frees the BSTR pointed to by the first pointer, and resets the pointer to the new BSTR. Notice that the first parameter is a pointer to a BSTR, not a BSTR. Normally, you'll pass a BSTR pointer with the address-of operator. Example: // Reallocate BSTR bs as "NewText" f = SysReAllocString(&bs, "NewText"); BOOL SysReAllocStringLen(BSTR * pbs, LPWSTR wsz, unsigned len); Allocates a new BSTR of the given length, and copies as many characters as fit of the given wide-character string to the new BSTR. It then frees the BSTR pointed to by the first pointer and resets the pointer to the new BSTR. Often the new pointer will be the same as the old pointer, but you shouldn't count on this. You can give the same BSTR for both arguments if you want to truncate an existing BSTR. For example, you might allocate a BSTR buffer, call an API function to fill the buffer, and then reallocate the string to its actual length. Example: // Create uninitialized buffer of length MAX_BUF. BSTR bsInput = SysAllocStringLen(NULL, MAX_BUF); // Call API function to fill the buffer and return actual length. cch = GetTempPathW(MAX_BUF, bsInput); // Truncate string to actual length. BOOL f = SysReAllocStringLen(&bsInput, bsInput, cch); unsigned SysStringLen(BSTR bs); Returns the length of the BSTR in characters. This length does not include the terminating null. This function will return zero as the length of either a null BSTR or an empty BSTR. Example: // Get character length of string. cch = SysStringLen(bs); unsigned SysStringByteLen(BSTR bs); Returns the length of the BSTR in bytes, not including the terminating null. This information is rarely of any value. Note that if you look at the length prefix of a BSTR in a debugger, you'll see the byte length (as returned by this function) rather than the character length. void SysFreeString(BSTR bs); Frees the memory assigned to the given BSTR. The contents of the string may be completely freed by the operating system, or they may just sit there unchanged. Either way, they no longer belong to you and you had better not read or write to them. Don't confuse a deallocated BSTR with a null BSTR. The null BSTR is valid; the deallocated BSTR is not. Example: // Deallocate a string. SysFreeString(bs); BSTR SysAllocStringA(LPCSTR sz); The same as SysAllocString, except that it takes an ANSI string argument. OLE doesn't provide this function; it's declared in BString.H and defined in BString.Cpp. Normally, you should only use this function to create Unicode BSTRs from ANSI character string variables or function return values. It works for ANSI string literals, but it's wasted effort because you could just declare Unicode literals and save yourself some run-time processing. Example: // Create BSTR containing "Text". bs = SysAllocStringA(sz) BSTR SysAllocStringLenA(LPCSTR sz, unsigned len); The same as SysAllocStringLen, except that it takes an ANSI string argument. This is my enhancement function, declared in BString.H. Example: // Create BSTR containing six characters, some or all of them from sz. bs = SysAllocStringLenA(sz, 6) The Eight Rules of BSTR Knowing what the BSTR functions do doesn't mean you know how to use them. Just as the BSTR type is more than its typedef implies, the BSTR functions require more knowledge than documentation states. Those who obey the rules live in peace and happiness. Those who violate them live in fear—plagued by the ghosts of bugs past and future. The trouble is, these rules are passed on in the oral tradition; they are not carved in stone. You're just supposed to know. The following list is an educated attempt—based on scraps of ancient manuscripts, and revised through trial and error—to codify the oral tradition. Remember, it is just an attempt. Rule 1: Allocate, destroy, and measure BSTRs only through the OLE API (the Sys functions). Those who use their supposed knowledge of BSTR internals are doomed to an unknowable but horrible fate in future versions. (You have to follow the rules if you don't want bugs.) Rule 2: You may have your way with all the characters of strings you own. The last character you own is the last character reported by SysStringLen, not the last non-null character. You may fool functions that believe in null-terminated strings by inserting null characters in BSTRs, but don't fool yourself. Rule 3: You may change the pointers to strings you own, but only by following the rules. In other words, you can change those pointers with SysReAllocString or SysReAllocStringLen. The trick with this rule (and rule 2) is determining whether you own the strings. Rule 4: You do not own any BSTR passed to you by value. The only thing you can do with such a string is copy it or pass it on to other functions that won't modify it. The caller owns the string and will dispose of it according to its whims. A BSTR passed by value looks like this in C++: void DLLAPI TakeThisStringAndCopyIt(BCSTR bsIn); The BCSTR is a typedef that should have been defined by OLE, but wasn't. I define it like this in OleType.H: typedef const wchar_t * const BCSTR; If you declare input parameters for your functions this way, the C++ compiler will enforce the law by failing on most attempts to change either the contents or the pointer. The Object Description Language (ODL) statement for the same function looks like this: void WINAPI TakeThisStringAndCopyIt([in] BCSTR bsIn); The BCSTR type is simply an alias for BSTR because MKTYPLIB doesn't recognize const. The [in] attribute allows MKTYPLIB to compile type information indicating the unchangeable nature of the BSTR. OLE clients such as Visual Basic will see this type information and assume you aren't going to change the string. If you violate this trust, the results are unpredictable. Rule 5: You own any BSTR passed to you by reference as an in/out parameter. You can modify the contents of the string, or you can replace the original pointer with a new one (using SysReAlloc functions). A BSTR passed by reference looks like this in C++: void DLLAPI TakeThisStringAndGiveMeAnother(BSTR * pbsInOut); Notice that the parameter doesn't use BCSTR because both the string and the pointer are modifiable. In itself the prototype doesn't turn a reference BSTR into an in/out BSTR. You do that with the following ODL statement: void WINAPI TakeThisStringAndGiveMeAnother([in, out] BSTR * pbsInOut); The [in, out] attribute tells MKTYPLIB to compile type information indicating that the string will have a valid value on input, but that you can modify that value and return something else if you want. For example, your function might do something like this: // Copy input string. bsNew = SysAllocString(*pbsInOut); // Replace input with different output. f = SysReAllocString(pbsInOut, L"Take me home"); // Use the copied string for something else. UseString(bsNew); Rule 6: You must create any BSTR passed to you by reference as an out string. The string parameter you receive isn't really a string—it's a placeholder. The caller expects you to assign an allocated string to the unallocated pointer, and you'd better do it. Otherwise the caller will probably crash when it tries to perform string operations on the uninitialized pointer. The prototype for an out parameter looks the same as one for an in/out parameter, but the ODL statement is different: void WINAPI TakeNothingAndGiveMeAString([out] BSTR * pbsOut); The [out] attribute tells MKTYPLIB to compile type information indicating that the string has no valid input but expects valid output. A container such as Visual Basic will see this attribute and will free any string assigned to the passed variable before calling your function. After the return the container will assume the variable is valid. For example, you might do something like this: // Allocate an output string. *pbsOut = SysAllocString(L"As you like it"); Rule 7: You must create a BSTR in order to return it. A string returned by a function is different from any other string. You can't just take a string parameter passed to you, modify the contents, and return it. If you did, you'd have two string variables referring to the same memory location, and unpleasant things would happen when different parts of the client code tried to modify them. So if you want to return a modified string, you allocate a copy, modify the copy, and return it. You prototype a returned BSTR like this: BSTR DLLAPI TransformThisString(BCSTR bsIn); The ODL version looks like this: BSTR WINAPI TransformThisString([in] BSTR bsIn); You might code it like this: // Make a new copy. BSTR bsRet = SysAllocString(bsIn); // Transform copy (uppercase it). _wcsupr(bsRet); // Return copy. return bsRet; Rule 8: A null pointer is the same as an empty string to a BSTR. Experienced C++ programmers will find this concept startling because it certainly isn't true of normal C++ strings. An empty BSTR is a pointer to a zero-length string. It has a single null character to the right of the address being pointed to, and a long integer containing zero to the left. A null BSTR is a null pointer pointing to nothing. There can't be any characters to the right of nothing, and there can't be any length to the left of nothing. Nevertheless, a null pointer is considered to have a length of zero (that's what SysStringLen returns). When dealing with BSTRs, you may get unexpected results if you fail to take this into account. When you receive a string parameter, keep in mind that it may be a null pointer. For example, Visual Basic 4.0 makes all uninitialized strings null pointers. Many C++ run-time functions that handle empty strings without any problem fail rudely if you try to pass them a null pointer. You must protect any library function calls: if (bsIn != NULL) { wcsncat(bsRet, bsIn, SysStringLen(bsRet)); } When you call Win32 API functions that expect a null pointer, make sure you're not accidentally passing an empty string: cch = SearchPath(wcslen(bsPath) ? bsPath : (BSTR)NULL, bsBuffer, wcslen(bsExt) ? bsExt : (BSTR)NULL, cchMax, bsRet, pBase); When you return functions (either in return values or through out parameters), keep in mind that the caller will treat null pointers and empty strings the same. You can return whichever is most convenient. In other words, you have to clearly understand and distinguish between null pointers and empty strings in your C++ functions so that callers can ignore the difference in Basic. In Visual Basic, a null pointer (represented by the constant vbNullString) is equivalent to an empty string. Therefore, the following statement prints True: Debug.Print vbNullString = "" If you need to compare two strings in a function designed to be called from Visual Basic, make sure you respect this equality. Those are the rules. What is the penalty for breaking them? If you do something that's clearly wrong, you may just crash. But if you do something that violates the definition of a BSTR (or a VARIANT or SAFEARRAY, as we'll learn later) without causing an immediate failure, results vary. When you're debugging under Windows NT (but not under Windows 95) you may hit a breakpoint in the system heap code if you fail to properly allocate or deallocate resources. You'll see a message box saying "User breakpoint called from code at 0xXXXXXXX" and you'll see an int 3 instruction pop up in the disassembly window with no clue as to where you are or what caused the error. If you continue running (or if you run the same code outside the debugger or under Windows 95), you may or may not encounter a fate too terrible to speak of. This is not my idea of a good debugging system. An exception or an error dialog box would be more helpful, but something is better than nothing, which is what you get under Windows 95. A BSTR Sample The Test.Cpp module contains two functions that test BSTR arguments. They're the basis of much of what I just passed on as the eight rules. The TestBStr function exercises each of the BSTR operations. This function doesn't have any output or arguments, but you can run it in the C++ debugger to see exactly what happens when you allocate and reallocate BSTRs. The TestBStrArgs function tests some legal and illegal BSTR operations. The illegal ones are commented out so that the sample will compile and run. This article is about the String class, not raw BSTR operations, so I'll leave you to figure out these functions on your own. It's probably more interesting to study this code than to run it, but the BSTR button in the Cpp4VB sample program does call these functions. Before you start stepping through this sample with the Microsoft Developer Studio, you'll have to tell the debugger about Unicode. You must decide whether you want arrays of unsigned shorts to be displayed as integer arrays or as Unicode strings. The choice is pretty obvious for this project, but you'll be up a creek if you happen to have both unsigned short arrays and Unicode strings in some other project. The debugger can't tell the difference. You probably won't have this kind of problem if your compiler and debugger interpret wchar_t as an intrinsic type. To get the Microsoft debugger to display wchar_t arrays as Unicode, you must open the Tools menu and select Options. Click the Debug tab and enable Display Unicode Strings. (Note that this applies to Visual C++ versions 5 and later.) For Visual C++ version 5, you can use the su format specifier on all Unicode variables in your watch window (although this won't help you in the locals window). To get a little ahead of ourselves, you can add the following line to make the String class described in the next section display its internal BSTR member as a Unicode string: ; from BString.h String =<m_bs,su> Comments in AUTOEXP.DAT explain the syntax of format definitions. Comments in AUTOEXP.DAT explain the syntax of format definitions. You don't need to do this for Visual C++ version 6. The String Class One reason for writing server DLLs is to hide ugly details from clients. We'll take care of all the Unicode conversions in the server so that clients don't have to, but handling those details in every other line of code would be an ugly way to program. C++ provides classes so that we can hide ugly details even deeper. The String class is designed to make BSTR programming look almost as easy as programming with Basic's String type. Unfortunately, structural problems (or perhaps lack of imagination on my part) make this worthy goal unachievable. Still, I think you'll find the String type useful. Note I know that it's presumptuous of me to name my BSTR class wrapper String, my VARIANT class wrapper Variant, and my SAFEARRAY class wrapper SafeArray. Most vendors of classes have the courtesy to use some sort of class naming convention that avoids stealing the most obvious names from the user's namespace. But I've been using the Basic names for other OLE types through typedefs. Why not use them for the types that require classes? After all, the goal is to make my classes look and work as much like intrinsic types as possible. The include filename, however, is BString.H because the name string.h is already used by the C++ run-time library. Rather than getting into String theory, let's just plunge into a sample. The goal is to implement the Visual Basic GetTempFile function. If you read my earlier book, Hardcore Visual Basic, you may remember this function. It's a thin wrapper for the Win32 GetTempFileName function. Like most API functions, GetTempFileName is designed for C programmers. GetTempFile is designed for Basic programmers. You call it the obvious way: sTempFile = GetTempFile("C:\TMP", "VB") The first argument is the directory where you want to create the temporary file, the second is an optional prefix for the file name, and the return value is a full file path. You might get back a filename such as C:\TMP\VB6E.TMP. This name is guaranteed to be unique in its directory. You can create the file and fill it with data without being concerned about it overwriting any other temporary file or even a permanent file that happens (incredibly) to have the same name. A String API Sample It would probably be easier to write the GetTempFile wrapper in Visual Basic, but we're going to do it in C++ to prove a point. Besides, some of the more complex samples we'll be looking at later really do need C++. The GetTempFile function is tested by the event handler attached to the Win32 button in the sample program. This code also tests other Win32 emulation functions and, when possible, the raw Win32 functions from which they are created. You can study the Basic code in Cpp4VB.Frm and the C++ code in Win32.Cpp. Here's the GetTempFile function: BSTR DLLAPI GetTempFile( BSTR bsPathName, BSTR bsPrefix ) { try { String sPathName = bsPathName; String sPrefix = bsPrefix; String sRet(ctchTempMax); if (GetTempFileName(sPathName, sPrefix, 0, Buffer(sRet)) == 0) { throw (Long)GetLastError(); } sRet.ResizeZ(); return sRet; } catch(Long e) { ErrorHandler(e); return BNULL; } } Exception Handling This function, like many of the other functions you'll see in this series of articles, uses C++ exception handling. I'm not going to say much about this except that all the normal code goes in the try block and the catch block gets all the exceptions. The ErrorHandler function is purposely elsewhere so that we can change the whole error system just by changing this function. For now, we're only interested in the normal branch of the code. You can see that if the GetTempFileName API function returns zero, we throw an error having the value of the last API error. This will transfer control to the catch block where the error will be handled. What you can't see (yet) is that constructors and methods of the String class can also throw exceptions, and when they do, the errors will bubble up through as many levels of nested String code as necessary and be handled by this outside catch block. Instead of handling errors where they happen, you defer them to one place in client code. In other words, C++ exception handling works a lot like Visual Basic's error handling. Throwing an exception in C++ is like calling the Raise method of the Err object, and catching an exception is like trapping an error with Basic's On Error statement. We'll revisit exception handling again in Article 4. Initializing String Variables The first thing we do is assign the BSTR parameters to String variables. This is an unfortunate requirement. It would be much nicer if we could just pass String parameters. Unfortunately, a String variable requires more storage than a BSTR variable and you can't just use the two interchangeably. You'll understand this later when you get a brief look inside the String type, but for now just be aware that the performance and size overhead for this assignment is very low and well worth the cost, especially on functions that are larger than GetTempFile. The second thing we do is initialize the sRet variable, which will be the return value. The String type has several constructors and one of them creates an empty buffer of a given length. The constant ctchTempMax is the maximum Win32 file length—256 characters. That's a lot more than you'll need for a temporary filename on most disks, but we're being safe. If you watch the code in a debugger, you'll see that in debug builds the buffer is filled with an unusual padding character—the @ sign. The only purpose is so that you can see exactly what's going on. The data is left uninitialized in release builds. In the extremely unlikely case that you don't have 256 bytes of memory left in your system, the initialization will fail and throw an out-of-memory exception. Buffers for Output Strings Now we're ready to call the Win32 GetTempFileName function. The sPathName and sPrefix arguments provide the input, and the sRet argument is a buffer that the function will fill. There's only one problem. Strings are Unicode internally, but GetTempFileName will usually be GetTempFileNameA and will expect ANSI string arguments. Of course if you're building for Windows NT only, you can do a Unicode build and call GetTempFileNameW. Either way, the String type should do the right thing, and do it automatically. Well, that worthy goal isn't as easy as you might expect. It's not too bad for the input arguments because the String type has a conversion operator that knows how to convert the internal Unicode character string to a separate internal ANSI character string and return the result. The conversion just happens automatically. But the buffer in the sRet variable is a little more difficult because the conversion must be two-way. The API function has to get an ANSI string, and the ANSI string created by the function must be converted back to a Unicode BSTR. That's why we pass the Buffer object rather than passing the sRet argument directly. You might think from the syntax that Buffer is a function. Wrong! Buffer is a class that has a constructor taking a String argument. A temporary Buffer object is constructed on the stack when GetTempFileName is called. This temporary object is destroyed when GetTempFileName returns. And that's the whole point of the object. The destructor for the Buffer object forces the automatic Unicode conversion. Let's step through what happens if you're doing an ANSI build. You call the GetTempFileName function. The Buffer object is constructed on the stack by assigning the sRet String variable to an internal variable inside the Buffer object. But sRet contains a Unicode string and GetTempFileName expects an ANSI string. No problem. Buffer provides a conversion operator that converts the Unicode string to an ANSI string and returns it for access by the ANSI API function. GetTempFileName fills this buffer with the temporary filename. Now the ANSI copy is right, but the Unicode buffer is untouched. That's OK because when GetTempFileName returns, the destructor for the Buffer object will convert the ANSI copy of the buffer to Unicode in the real string buffer. Sounds expensive, but all these operations are actually done with inline functions and the cost is acceptable. You can check out the details in BString.H. Now, what happens during a Unicode build? Pretty much nothing. The Buffer constructor is called, but it just stores the BSTR pointer. The Buffer class also has a conversion operator that makes the buffer return a Unicode character buffer, but it just returns the internal BSTR pointer. The destructor checks to see if anything needs to be converted to Unicode, but nothing does. That's pretty much how the String type works throughout. It performs Unicode conversion behind the scenes only when necessary. String Returns Let's continue with the rest of the function. After calling GetTempFileName, the GetTempFile function has the filename followed by a null in the sRet variable. That's what a C program would want, but it's not what a Basic program wants because the length of sRet is still 256. If you passed the variable back as is, you'd see a whole lot of junk characters following the null in the Visual Basic debugger. So we first call the ResizeZ method to truncate the string to its first null. Later we'll see a Resize method that truncates to a specified length. Unlike most API string functions, GetTempFile doesn't return the length, so we have to figure it out from the position of the null. Finally, we return the sRet variable and exit from the GetTempFile function. The destructors for all three String variables are called. At this point, all the temporary ANSI buffers are destroyed, but the destructors don't destroy the internal Unicode strings because they're owned by the caller. Visual Basic will destroy those strings when it gets good and ready, and it wouldn't be very happy if our String destructor wiped them out first—especially the return value. If this seems hopelessly complicated, don't sweat it. You don't have to understand the implementation to use the String type. It's a lot simpler (and shorter) than doing the same operations with the BSTR type. You just have to understand a few basic principles. A String Warm-up Let's take a look at some of the specific things you can do with strings. The most important thing you'll be doing with them is passing them to and receiving them from functions. Here's how it's done in the mother of all String functions, TestString. TestString puts the String class through its paces, testing all the methods and operators and writing the results to a returned string for analysis. BSTR DLLAPI TestString( BCSTR bsIn, BSTR * pbsInOut, BSTR * pbsOut) { This doesn't mean much without its ODL definition: [ entry("TestString"), helpstring("Returns modified BSTR manipulated with String type"), ] BSTR WINAPI TestString([in] BSTR bsIn, [in, out] BSTR * pbsInOut, [out] BSTR * pbsOut); We talked about in and out parameters in Article 1, but at that point they were primarily documentation. With the BSTR type (as well as with VARIANT and SAFEARRAY) you had better code your DLL functions to match their ODL declarations. Otherwise, your disagreements with Visual Basic can have drastic consequences. The purpose of an in parameter (such as bsIn) is to pass a copy of a string for you to read or copy. It's not yours, so don't mess with the contents. The purpose of an in/out parameter (such as pbsInOut) is to pass you some input and receive output from you. Do what you want with it. Modify its contents, copy it to another String, or pass a completely different string back through its pointer. The purpose of an out parameter (such as pbsOut) is to receive an output string from you. There's nothing there on input, but there had better be something there (if only a NULL) when you leave the function, because Visual Basic will be counting on receiving something. String Constructors Once you receive your BSTRs, you need to convert them to String. You can also create brand new Strings to return through the return value or out parameters, or just to serve as temporary work space. The String constructors create various kinds of strings: // Constructors String sTmp; // Uninitialized String sIn = bsIn; // In argument from BSTR String sCopy = *pbsInOut; // In/out argument from BSTR String sString = sIn; // One String from another String sChar(1, WCHAR('A')); // A single character String sChars(30, WCHAR('B')); // A filled buffer String sBuf(30); // An uninitialized buffer String sWide = _W("Wide"); // From Unicode string String sNarrow = "Narrow"; // From ANSI string String sNative = _T("Native"); // From native string String sRet; Most of these speak for themselves, but notice the WCHAR casts and the use of the _W macro to initialize with a wide-character constant. When initializing Strings with constants, you should always use Unicode characters or strings. The String type will just have to convert your ANSI strings to Unicode anyway. Conversion is a necessary evil if you have an ANSI character string variable, but if you have a constant, you can save run-time processing by making it a Unicode string to start with. Unfortunately, you can't just initialize a String with a Unicode string like this: String s = L"Test"; The problem is that the String type has a BSTR constructor and a LPCWSTR constructor, but what you'll get here is an LPWSTR and there's no separate constructor for that. There can't be a separate constructor because to C++, a BSTR looks the same as an LPWSTR, but of course internally it's very different. Any time you assign a wide character string to a String, you must cast it to an LPCWSTR so that it will go through the right constructor. The _W macro casts to LPCWSTR unobtrusively. C++ is a very picky language, and the String class seems to hit the edges of the pickiness in a lot of places. You have to develop very careful habits to use it effectively. Note Extending Visual Basic with C++ DLLs Many of the problems in writing a String class are caused by Unicode confusion, and much of that confusion comes from the fact that in most current compilers the wchar_t type (called WCHAR in this article) is a typedef to an unsigned short rather than an intrinsic type. Overloaded functions are a critical part of designing a safe, convenient class in C++, but when overloading, C++ considers a typedef to be a simple alias rather than a unique type. A constructor overloaded to take a WCHAR type actually sees an unsigned short, which may conflict with other overloaded integer constructors. Debuggers won't know whether to display a WCHAR pointer as a string or as an array of unsigned shorts. Compile-time error messages will display confusing errors showing unsigned short rather than the character type you thought you were using. If you're fortunate enough to use a compiler that provides wchar_t as an intrinsic type, you won't see these problems. Unfortunately, Microsoft Visual C++ is not yet among those compilers. String Assignment As you already know (or had better find out soon if you're going to program in C++), initialization is a very different thing from assignment, even though the syntax may look similar. The String type provides the assignments you expect through the operator= function: // Assignment WCHAR wsz[] = L"Wide"; char sz[] = "Narrow"; sTmp = sIn; // From another String variable sTmp = _W("Wide"); // From Unicode literal string sTmp = WCHAR('W'); // From Unicode character sTmp = LPCWSTR(wsz); // From Unicode string variable sTmp = LPCSTR(sz); // From ANSI string variable Again, you have to jump through some hoops to make sure your wide-character string assignments go through the proper const operator. C++ can't tell the difference between a wide-character string and a BSTR, so you have to tell it. Generally, you should avoid doing anything with ANSI character strings. The String type can handle ANSI strings, but you just end up sending a whole lot of zeros to and from nowhere. The only reason to use ANSI strings is to pass them to API functions or to C run-time functions, and you normally shouldn't do the latter either, because it's much more efficient to use the wscxxx versions of the run-time functions. String Returns Let's skip all the cool things you can do to massage String variables and go to the end of TestString where you return your Strings: // Return through out parameters. sTmp = _W("...send me back"); *pbsInOut = sTmp; *pbsOut = _B("Out of the fire"); // Return value return sRet; } catch(Long err) { HandleError(err); } } In the first line we assign a wide string to the temporary variable (sTmp) and then assign sTmp to the BSTR out parameter (pbsInOut). A BSTR conversion operator in the String type enables you to perform the assignment of the wide string stored in sTmp to the BSTR out parameter, pbsInOut. The second assignment does the same thing, but uses the _B macro to create and destroy a temporary String variable on the stack. The _B macro uses a double typecast and token paste to hide the following atrocity: *pbsOut = String(LPCWSTR(L"Out of the fire")); Finally, the return value is set to the sRet variable containing the string that we'll build in the next section. Internally, the return works exactly like the assignment to an out parameter and in fact calls the same BSTR conversion operator. Think of the Basic syntax: TestString = sRet This gives you a better picture of what actually happens in a C++ return statement. Friday, August 22, 2008 3:06 PM All replies - The other half of the article on btsrings: Allan A String Workout There's a lot more to the String type than initialization and assignment. It's designed to be a full-featured string package—duplicating most of the functions you find in the C run-time library or in popular string classes such as MFC's CString. You won't find everything you could ever need, but conversion operators make it easy to pass Strings to run-time string functions. Or better yet, whenever you want to do something that isn't directly supported, add it to the library and send me the code. Be sure to use the wscxxx version of run-time library calls. The TestString function uses the iostream library to build a formatted string that tests the String methods and operators, and then assigns that string to the return value. Here's how it works: ostrstream ostr; ostr << endcl << "Test length and resize:" << endcl; sTmp = _W("Yo!"); ostr << "sTmp = _W(\"Yo!\"); // sTmp==\"" << sTmp << "\", " << "sTmp.Length()==" << sTmp.Length() << endcl; . . . ostr << ends; char * pch = ostr.str(); sRet = pch; delete[] pch; The String class defines an iostream insertion operator (<<) so that you can easily insert ANSI character strings (converting from Unicode BSTRs) into an output stream. Notice that I also use a custom endcl manipulator rather than the standard endl manipulator. My version inserts a carriage return/line feed sequence rather than the standard line feed only. You can study up on iostream and check the code if this isn't clear. The point here is to show off String features, not the iostream library. The rest of this section will show chunks of output that put the String type through its paces. Length Methods We'll start with the length-related methods: sTmp = _W("Yo!"); // sTmp=="Yo!", sTmp.Length()==3 sTmp.Resize(20); // sTmp=="Yo!", sTmp.Length()==20, sTmp.LengthZ()==3 sTmp.ResizeZ(); // sTmp=="Yo!", sTmp.Length()==3 The Length() method always returns the real length of the String regardless of nulls, while LengthZ() returns the length to the first null. Normally you'll Resize to truncate a string to a specified length, but you can also expand a string to create a buffer, then truncate back to the first null after passing the buffer to an API function. Empty Strings and Comparisons Internally, a String, like a BSTR, can be either a NULL string or an empty string, although Basic treats these the same. The String type provides methods to test and set this state: sTmp = "Empty"; // sTmp=="Empty",sTmp.IsEmpty==0, sTmp.IsNull==0 sTmp.Empty(); // sTmp=="",sTmp.IsEmpty==1, sTmp.IsNull==0 sTmp.Nullify(); // sTmp=="",sTmp.IsEmpty==1, sTmp.IsNull==1 In the Basic tradition, the IsEmpty() method returns True if the string is either null or empty. That's generally all you need to know. Many C++ run-time functions can't handle null strings, and some API functions can't handle empty strings. So you can use the IsNull() function to identify a null string. There's no direct way to identify what C++ thinks of as an empty string, but the following expression will work: sTmp.IsEmpty() && !sTmp.IsNull() Of course, you can test equality to empty or any other value with logical operators. If sTmp is empty (in either sense), the String == operator will return True for (sTmp == BNULL) or for (sTmp == _B("")). Notice how cast macros are used to convert literals to Strings before comparison. You can also test comparisons with expressions such as: (sNarrow >= sWide) String Indexing The String class provides an indexing operator to insert or extract characters in strings. For example: // sWide=="Wide", i==2, wch=='n' sWide[i] = wch; // sWide=="Wine" wch = sWide[i - 1]; // wch=='i' sWide[0] = 'F'; // sWide=="Fine" There's nothing to prevent you from enhancing the index operator so that you could insert a string with it or even extract one. I'll leave that to you. Concatenation Any string type worth its salt must be capable of concatenation, and String does it as you would expect—with the + and += operators. It can append characters or strings: // sChar=="A", sIn=="Send me in" sChar += sIn; // sChar=="ASend me in" sChar += WCHAR('F'); // sChar=="ASend me inF" sChar += 'G'; // sChar=="ASend me inFG" sChar += _W("Wide"); // sChar=="ASend me inFGWide" sChar += "Narrow"; // sChar=="ASend me inFGWideNarrow" sTmp = sNarrow + sNative + _W("Slow") + "Fast" + WCHAR('C') + 'D' // sTmp=="NarrowNativeSlowFastCD" Some of the String methods look and act like Visual Basic string functions. Don't forget that Visual Basic strings are 1-based, not 0-based like C++ strings: sChar = sTmp.Mid(7, 6); // sChar=="Native" sChar = sTmp.Mid(7); // sChar=="NativeSlowFastCD" sChar = sTmp.Left(6); // sChar=="Narrow" sChar = sTmp.Right(6); // sChar=="FastCD" An additional challenge (left as an exercise for the reader) is to add the Visual Basic Mid statement to insert characters into a string. String Transformations The String class has some transformation functions in both method and function versions: // sWide=="Fine" sWide.UCase(); // sWide=="FINE" sWide.LCase(); // sWide=="fine" sWide.Reverse(); // sWide=="enif" sChar = UCase(sWide); // sChar=="ENIF", sWide=="enif" sChar = LCase(sWide); // sChar=="enif", sWide=="enif" sChar = Reverse(sWide); // sChar=="fine", sWide=="enif" There are also similar versions of the Trim, LTrim, and RTrim functions: sChar = Trim(sTmp); // sChar=="Stuff", sTmp==" Stuff " sTmp.Trim(); // sTmp=="Stuff" String Searching I always found Basic's InStr function confusing, so I called the equivalent String function Find. It can find characters or strings, searching forward or backward, with or without case sensitivity. // sTmp="A string in a String in a String in a string" // "12345678901234567890123456789012345678901234567890" i = sTmp.Find('S'); // Found at position: 15 i = sTmp.Find('S', ffReverse); // Found at position: 27 i = sTmp.Find('S', ffIgnoreCase); // Found at position: 3 i = sTmp.Find('S', ffReverse | ffIgnoreCase); // Found at position: 39 i = sTmp.Find('Z'); // Found at position: 0 i = sTmp.Find("String"); // Found at position: 15 i = sTmp.Find("String", ffReverse); // Found at position: 27 i = sTmp.Find("String", ffIgnoreCase); // Found at position: 3 i = sTmp.Find("String", ffIgnoreCase | ffReverse); // Found at position: 39 i = sTmp.Find("Ztring"); // Found at position: 0 This method is 1-based, so C++ programmers may need to make a mental adjustment when using it. It's not too difficult to think of enhancements for the String type. Just look through the Basic and C++ run-time functions and add anything that looks interesting. It's easy to map existing C++ functions to a natural String format, and it's not much harder to write your own functions that provide string features that C++ lacks. But before you spend a lot of time on this, consider how String is used. In most DLLs, you'll be using the constructors, the conversion operators, and maybe a few logical or assignment operators. Basic already provides its own string functionality, so unless you want to replace it with your own more powerful string library, there's not much point in having a full-featured String type. On the other hand, maybe Basic does need a more powerful string library. Be my guest. How the String Class Works We've talked a lot about how to use the String type, but not much about how it is implemented. This article is not about how to write class libraries in C++, so I haven't explained the internals. However, you'll probably feel a little more comfortable using the class (and it will certainly be easier to enhance it) if you have some idea how String works, so let's take a look under the hood. class String { friend class Buffer; public: // Constructors String(); String(const String& s); // Danger! C++ can't tell the difference between BSTR and LPWSTR. If // you pass LPWSTR to this constructor, you'll get very bad results, // so don't. Instead, cast to constant before assigning. String(BSTR bs); // Any non-const LPSTR or LPWSTR should be cast to LPCSTR or LPCWSTR // so that it comes through here. String(LPCSTR sz); String(LPCWSTR wsz); // Filled with given character (default -1 means unitialized allocate). String(int cch, WCHAR wch = WCHAR(-1)); // Destructor ~String(); . . . private: BSTR m_bs; // The Unicode data LPSTR m_pch; // ANSI representation of it Boolean m_fDestroy; // Destruction flag // Implementation helpers void Concat(int c, LPCWSTR wsz); void Destroy(); void DestroyA(); }; String Construction A String consists of three pieces of data: the internal BSTR, a pointer to an array of ANSI characters, and a flag indicating how the String should be destroyed. You can see how this works by looking at a few constructors. inline String::String() : m_bs(SysAllocString(NULL)), m_pch(NULL), m_fDestroy(True) { } inline String::String(const String& s) : m_bs(SysAllocString(s.m_bs)), m_pch(NULL), m_fDestroy(True) { } // Convert BSTR to String. inline String::String(BSTR bs) : m_bs(bs), m_pch(NULL), m_fDestroy(False) { } inline String::String(LPCWSTR wsz) : m_bs(SysAllocString(wsz)), m_pch(NULL), m_fDestroy(True) { } inline String::String(LPCSTR sz) : m_bs(SysAllocStringA(sz)), m_pch(NULL), m_fDestroy(True) { } The constructors do nothing but initialize the three members. Notice that the ANSI string constructor (the one with the LPCSTR argument) uses the SysAllocStringA function to create a Unicode BSTR from an ANSI string. Another important point is that the constructors that create an internal BSTR set the m_fDestroy flag so that the BSTR will be destroyed by the destructor. The constructor that takes a BSTR parameter just wraps an existing BSTR parameter (usually passed as a parameter). The String doesn't own this BSTR and has no right to destroy it, so the m_fDestroy flag is set to false. String Translation The m_pch member is initialized to null, and it stays that way until someone asks to translate the BSTR to an ANSI string. The translation mechanism is the LPCSTR conversion operator, which is called automatically whenever you pass a String to a parameter that expects an LPCSTR. It looks like this: String::operator LPCSTR() { if ((m_pch == NULL) && (m_bs != NULL)) { // Check size. unsigned cmb = wcstombs(NULL, m_bs, SysStringLen(m_bs)) + 1; // Allocate string buffer and translate ANSI string into it. m_pch = new CHAR[cmb]; wcstombs(m_pch, m_bs, cmb); } return m_pch; } If the internal BSTR is not NULL, this operator allocates an ANSI buffer of the proper size and copies a translated string to it. This ANSI string will be maintained for reuse by subsequent calls to LPCSTR until the String is destroyed or until some member function changes the contents of the internal BSTR, thus invalidating the ANSI buffer. Any such member should destroy or update the ANSI buffer. String Destruction Here are the String destruction functions: void String::Destroy() { if (m_fDestroy) { SysFreeString(m_bs); } DestroyA(); } inline String::~String() { Destroy(); } // Invalidate ANSI buffer. inline void String::DestroyA() { delete[] m_pch; m_pch = NULL; } The destruction job is broken into parts so that member functions can destroy the whole String or just invalidate the ANSI buffer. For example, here's how the operator= members handle Unicode and ANSI strings. const String& String::operator=(LPCSTR sz) { Destroy(); m_bs = SysAllocStringA(sz); return *this; } const String& String::operator=(LPCWSTR wsz) { DestroyA(); if (SysReAllocString(&m_bs, wsz) == 0) throw E_OUTOFMEMORY; return *this; } One way or another, an operator= function must replace the previous contents of the object with the new contents being assigned. The LPCSTR version destroys the whole member and creates a new one, while the LPCWSTR version just destroys the ANSI buffer and reallocates the BSTR member. The only reason for this difference is that I didn't write a SysReAllocStringA function. A String Method Once you get construction, destruction, and ANSI conversion figured out, the methods and overloaded operators are easy. Most of them are simply calls to the wsc versions of C++ run-time functions. For example, let's look at the UCase method, which comes in two versions. Here's the member function: const String & String::UCase() { DestroyA(); // Invalidate ANSI buffer. wcsupr(m_bs); return *this; } It simply calls the wcsupr function (which you may know as strupr) to modify the internal BSTR member. Here's the function version: String UCase(String& s) { String sRet = s; sRet.UCase(); return sRet; } The version above uses a String argument (which it leaves unchanged) and returns a modified String copy. Its implementation creates a new string and uses the method version of UCase on it. A Challenge Before I leave you to figure out the rest of the String internals, let me pose a challenge. If the String class had only one member, m_bs, it would be the same size and have the same contents as a BSTR parameter. You could pass a BSTR in from Basic and receive a String in your C++ DLL. But this still wouldn't save you from doing Unicode conversion or from cleaning up correctly in destructors. You'd need to use the equivalents of m_pch and m_fDestroy without actually putting them in the class. How are you going to manage that? Well, here's an idea. Create a static class member that is an array of data structures, each of which contains a buffer for ANSI conversion and a flag for destruction. Every time you create a String object, you insert one of these items into the array. When you need to use the ANSI buffer, you look up the item in the array and allocate or use the ANSI buffer. You'll probably want to insert each item in sorted order (maybe by the value of the BSTR pointer) for faster lookup. Whenever you destroy a String, you must find and remove its corresponding data structure from the array Performance would suffer, but probably not by much because you're not going to have that many String variables active at any one time. You would end up with a more intuitive String class. From what I understand, this is how the old OLE2ANSI DLL used to work. Is it worth the extra work? I didn't think it was for this article, but perhaps it would be for your projects.Friday, August 22, 2008 3:08 PM
https://social.msdn.microsoft.com/Forums/en-US/88f6f6ce-46cb-4d19-8b7b-c92f5f34775c/bstrings?forum=vblanguage
CC-MAIN-2019-35
refinedweb
10,382
61.77
Steve, 2009/9/29 Gaëtan Lehmann <gaetan.lehmann@jouy.inra.fr>: > > Le 29 sept. 09 à 09:27, Mathieu Malaterre a écrit : > >> Hi there, >> >> I am reading through the code of itkPyBuffer and found: >> >> $ cat Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx >> ... >> // Deal with slight incompatibilites between NumPy (the future, >> hopefully), >> // Numeric (old version) and Numarray's Numeric compatibility module (also >> old). >> #ifndef NDARRAY_VERSION >> // NDARRAY_VERSION is only defined by NumPy's arrayobject.h >> // In non NumPy arrayobject.h files, PyArray_SBYTE is used instead of >> BYTE. >> #define PyArray_BYTE PyArray_SBYTE >> #endif >> ... >> >> There will be an issue soon in debian as python-numarray is >> deprecated so we need to transition -hopefully- to numpy. >> >> A couple of questions: >> - Does anyone use Numpy ? Is this working ? > > I do - it works. > >> - What is the difference in between (the patched) >> Wrapping/WrapITK/ExternalProjects/PyBuffer/itkPyBuffer.txx and >> Wrapping/CSwig/CommonA/itkPyBuffer.txx ? > > > I never succeeded to use the later, while the former works great :-) > The new one is a rework of what was began with the old one, but never > polished enough to be production ready. What do you think ? Should we just wait until ITK_WRAP_ITK becomes the default ? Or use the old CSWIG approach and just re-activate NUMARRAY using NUMPY (it does compile, I tested it), knowing that it is not 'production ready' ? -- Mathieu
https://lists.debian.org/debian-med/2009/09/msg00122.html
CC-MAIN-2017-04
refinedweb
218
60.72
pronunciation: imax. Okay, enough words. Let's dive straight into a transformation example. If we assume that you have two SVGs, like github.svg and quitter.svg, imacss will generate this CSS code for you. You can refer to this images by using the respective CSS classes: ... imacss comes with a command-line interface which pipes the output to stdout by default (yeah, plain old text streams FTW!). Install with npm globally. npm install -g imacss Embed all SVGs in a particular directory and all its subdirectories (will pipe the output to stdout). $ imacss "~/projects/webapp/images/**/*.svg" Embed all SVGs in a particular directory and transfer them to a CSS file which will be saved in the CWD. $ imacss "~/projects/webapp/images/*.svg" > images.svg.css Embed all SVGs and PNGs in a particular directory and transfer them to a CSS file which will be saved in the CWD. $ imacss "~/projects/webapp/images/*.{svg,png}" > images.css If you don't like the imacss selector namespace you are able to modify it as well. $ imacss "~/projects/webapp/images/*.{svg,png}" foobar > images.css will produce this selector structure in the CSS file: Important: Please note that imacss does not embed image/svg+xml as base64 strings. Instead it will use the raw utf-8 representation. If you would like to use the imacss functionality within your application, there is an API for that. npm install --save imacss Transforms the image files from the specified glob and returns a stream with the CSS selectors that can be piped to somewhere else. Arguments glob String || Vinyl file object The path to the images which should be transformed. You can use any glob pattern you want or you're also able pass single Vinyl file objects. namespace (optional; default=imacss) String || Function A string containing the css class namespace prefix, or a function to generate the entire CSS ruleset. The CSS selector namespace. var imacss = ;imacss; var imacss = ;{return '.image-' + imageslug + ' { ' + 'background-image:' + 'url(\'' + imagedatauri + '\'); }';}imacss;
https://www.npmjs.com/package/imacss
CC-MAIN-2017-47
refinedweb
334
57.98
I have no Access Control Service (ACS) installed, but I've seen on some online video demo that Salesforce is not in the list of available pre-installed identity providers. Salesforce can be configured as IdP (standard SAML 2.0 is used). Can I set up ACS so that I can use Salesforce as an identity provider? Thanks The official description SAML 2.0 says that ACS supports SAML 2.0 tokens. A list of supported protocol is OAuth 2.0, WS-Trust, and WS-Federation as given in the official statement. Also, there is currently no automated way to add identity providers that are out of predefined in the ACS. You can, however, use the ACS cmdlets to manually add IPs that have a supported protocol. If you configure the SalesFores as IdP with the use of SAML 2.0 tokens, you just need to identify the protocol and execute a PowerShell command which would look something like this: PS:\>Add-IdentityProvider –Namespace "myacsnamespace" –ManagementKey "XXXXXXXX" -Type "Manual" -Name "SalesForce" -Protocol OAuth –SignInAddress "" The list of supported protocols for this command are: OAuth, WsFederation, WsTrust, OpenId. So the SalesForce IdP configuration must use any of those protocols with SAML 2.0 tokens and it should work. I hope this helps!
https://intellipaat.com/community/7697/does-azure-acs-support-saml-2-0-idps-like-salesforce
CC-MAIN-2021-04
refinedweb
211
66.44
What is DNS? The Domain Name Systems (DNS) is the phonebook of the Internet. Humans access information online through domain names, like nytimes.com or espn.com. Web browsers interact through Internet Protocol (IP) addresses. DN Sname webpage, a translation must occur between what a user types into their web browser (example.com) and the machine-friendly address necessary to locate the example.com webpage.. There are 4 DNS servers involved in loading a webpage: - DNS recursor - The recursor can be thought of as a librarian who is asked to go find a particular book somewhere in a library. The DNS recursor is a server designed to receive queries from client machines through applications such as web browsers. Typically the recursor is then responsible for making additional requests in order to satisfy the client’s DNS query. - Root nameserver - The root server is the first step in translating (resolving) human readable host names into IP addresses. It can be thought of like an index in a library that points to different racks of books - typically it serves as a reference to other more specific locations. - TLD nameserver - The top level domain server (TLD) can be thought of as a specific rack of books in a library. This nameserver is the next step in the search for a specific IP address, and it hosts the last portion of a hostname (In example.com, the TLD server is “com”). - Authoritative nameserver - This final nameserver can be thought of as a dictionary on a rack of books, in which a specific name can be translated into its definition.. What's the difference between an authoritative DNS server and a recursive DNS resolver?. Recursive DNS resolver. Authoritative DNS server Put simply,.. What are the steps in a DNS lookup?. The 8 makes a request to. - The browser makes a HTTP request to the IP address. - The server at that IP returns the webpage to be rendered in the browser (step 10). Once the 8 steps of the DNS lookup have returned the IP address for example.com, the browser is able to make the request for the web page: . What are the types of DNS Queries?. 3 types of DNS queries: - Recursive query - In a recursive query, a DNS client requires that a DNS server (typically a DNS recursive resolver) will respond to the client with either the requested resource record or an error message if the resolver can't find the record. - Iterative query - in this situation the DNS client will allow a DNS server to return the best answer it can. If the queried DNS server does not have a match for the query name, it will return a referral to a DNS server authoritative for a lower level of the domain namespace. The DNS client will then make a query to the referral address. This process continues with additional DNS servers down the query chain until either an error or timeout. What is DNS caching? Where does DNS caching occur?). Browser DNS caching. Operating system (OS) level DNS caching: - If the resolver does not have the A records, but does have the NS records for the authoritative nameservers, it will query those name servers directly, bypassing several steps in the DNS query. This shortcut prevents lookups from the root and .com nameservers (in our search for example.com) and helps the resolution of the DNS query occur more quickly. - If the resolver does not have the NS records, it will send a query to the TLD servers (.com in our case), skipping the root server. - In the unlikely event that the resolver does not have records pointing to the TLD servers, it will then query the root servers. This event typically occurs after a DNS cache has been purged.
https://www.cloudflare.com/fr-fr/learning/dns/what-is-dns/
CC-MAIN-2019-26
refinedweb
628
65.01
by Harshad Oak 04/18/2005 As enterprise Java developers, we are routinely required to implement functionality like parsing XML, working with HTTP, validating input, and processing dates. The Jakarta Commons project is an attempt to create components that can take care of all such commonly used tasks, freeing up your time to focus only on core business solutions. In this article we will provide a quick introduction to the Jakarta Commons project and then demonstrate how the Lang component within Jakarta Commons can be used to handle and simplify everyday Java tasks such as string manipulation, working with dates and calendars, comparing data objects, and sorting objects. For all examples, we will use the latest version of Lang, version 2.1. Editor's Note: The code in this article is written to the RC1 release of Commons Lang. The final release is due out soon. Jakarta Commons is a project meant solely for reusable Java components. The project has dozens of components for simplifying Java development and addressing one particular requirement well. The range of available components is huge, and they aren't limited for use only in Java applications of a particular type. The projects are classified into two parts: There are currently 33 projects in the Commons Proper and 22 projects in the works in the Commons Sandbox so there is something in there for every kind of Java project. The Lang component is one of the more popular components in Jakarta Commons. Lang is a set of classes that you wish were present in J2SE itself. In this article we will look at some of the most useful features of Lang. Note that you can do everything that Lang does using just the basic Java classes, however it is far easier to use Lang than it is to study, understand, and write the code yourself. Even if you can write superb code, using the tried and tested capabilities of Lang will be quicker and will save considerable review and testing cycle time. Lang comes with proper JUnit test cases and as it is used so widely, it has been well tested by its creators as well as by the real world. An important feature of Lang is its simplicity. New Java components generally are so complex that unless you know A, B, C, and D technologies, you will not be able to use that component. Often, it is difficult to even understand what a component is trying to achieve, let alone actually use the component. This is not the case with most of the Commons components.. Let's start with string manipulation with Lang, a task that most Java developers have to do almost every day. Any application irrespective of whether it is a Swing-, J2EE-, or J2ME-based one, has to work with strings. So although working with a string in Java is fairly simple, if you wish to modify and manipulate the string based on certain conditions, things don't stay that simple. You have to hunt for obscure methods in the various string-related classes and then somehow get them to work together to get you the desired result. While there are some Lang methods that do overlap with methods present in J2SE, in most cases one Lang method provides the functionality of many J2SE methods from various classes, working together to get you the desired output. The Lang component has many classes dedicated to string manipulation. We will now use a basic Java application to demonstrate some of the more useful classes and methods. String manipulation is generally involved when your application takes input from a user and you either do not trust what the user will enter or the user might enter data in various formats but you only wish to work and store in one format.Credit card number rules work somewhat like this, so if I tell you I have a MasterCard and the card number begins with 4, you'll know I am lying right away. Refer to Anatomy of Credit Card Numbers As an example, you have a form with an input box for the user to enter a license key. You wish to allow a key in the format 1111-JAVA. The things you have to provide for are: Only if the key fulfills all these conditions do you want your application to go to the trouble of going to the database and checking if the key is a legitimate one. Can you do all this without spending a fair amount of time browsing through the API documentation for the String, StringTokenizer, and other classes? I can't, so I will now try to manage the validation using the Lang component. Listing 1. The checkLicenseKey() method /** * Check if the key is valid * @param key license key value * @return true if key is valid, false otherwise. */ public static boolean checkLicenseKey(String key){ //checks if empty or null if(StringUtils.isBlank(key)){ return false; } //delete all white space key= StringUtils.deleteWhitespace(key); //Split String using the - separator String[] keySplit = StringUtils.split(key, "-"); //check lengths of whole and parts if(keySplit.length != 2 || keySplit[0].length() != 4 || keySplit[1].length() != 4) { return false; } //Check if first part is numeric if(!StringUtils.isNumeric(keySplit[0])){ return false; } //Check if second part contains only //the four characters 'J', 'A', 'V' and 'A' if(! StringUtils.containsOnly(keySplit[1] ,new char[]{'J', 'A', 'V', 'A'})){ return false; } //Check if the fourth character //in the first part is a '0' if(StringUtils.indexOf(keySplit[0], '0') != 3){ return false; } //If all conditions are fulfilled, key is valid. return true; } In Listing 1, we utilize various methods provided in the org.apache.commons.lang.StringUtils class to validate a string according to all the rules that we defined earlier. The isBlank()method checks if the string is empty or null. The deleteWhitespace() method ensures that the string is free of white spaces. We then split the string using the split() method and validate the two portions using the isNumeric(), containsOnly(), and indexOf() methods. Note that even though the indexOf() method is already present in J2SE, using the indexOf() in StringUtils is a better choice. Unlike the J2SE indexOf() method, with the StringUtils indexOf() you do not have to worry about null. Triggering NullPointerException is believed to be the most common error committed by Java programmers. Lang will ensure that you do not commit the same mistake. Even if you pass a null to the indexOf() method or any other method for that matter, it will not throw a NullPointerException. In the case of indexOf(), it will simply return -1. So in just a few lines of pretty straightforward code, we have been able to achieve what would otherwise have taken many more lines of code and a lot more trouble. If we execute the checkLicenseKey() method using a main method as shown in Listing 2, you will get an output as shown in Listing 3. Listing 2. The main() method public static void main(String[] args) { String []key= {"1210-JVAJ","1211-JVAJ", "210-JVAJ", "1210-ZVAJ"}; for (int i=0; i < key.length; i++){ if(checkLicenseKey(key[i])){ System.out.println(key[i]+ " >> Is Valid"); } else{ System.out.println(key[i]+ " >> Is InValid"); } } } Listing 3. The output 1210-JVAJ >> Is Valid 1211-JVAJ >> Is InValid 210-JVAJ >> Is InValid 1210-ZVAJ >> Is InValid While org.apache.commons.lang.StringUtils has most of the methods meant for string manipulation, there are other classes that can also help. CharUtils and CharSetUtils provide utility methods for working with characters and character sets respectively. WordUtils is a class first seen in version 2.0 and is meant to house utility methods specifically for working with words. However, as there is significant overlap between what you can do with strings and words, this class does seem a little unnecessary. RandomStringUtils is a class that can help generate random strings based on various rules. We will now look at another useful facet of Lang: the ability to work with dates and times. Working with dates and times in Java is quite a tricky task. Using java.text.SimpleDateFormat, java.util.Calendar, java.util.Date, and so on, takes some getting used to, and it requires a pretty sound understanding of each of the classes and interfaces involved to be able to play with dates and times. The Lang component drastically simplifies working with dates and formatting them. You can easily format a date for display, compare dates, round or truncate dates, or even get all dates in a certain range. Listing 4. Working with dates and times public static void main(String[] args) throws InterruptedException, ParseException { //date1 created Date date1= new Date(); //Print the date and time at this instant System.out.println("The time right now is >>"+date1); //Thread sleep for 1000 ms Thread.currentThread().sleep(DateUtils.MILLIS_IN_SECOND); //date2 created. Date date2= new Date(); //Check if date1 and date2 have the same day System.out.println("Is Same Day >> " + DateUtils.isSameDay(date1, date2)); //Check if date1 and date2 have the same instance System.out.println("Is Same Instant >> " +DateUtils.isSameInstant(date1, date2)); //Round the hour System.out.println("Date after rounding >>" +DateUtils.round(date1, Calendar.HOUR)); //Truncate the hour System.out.println("Date after truncation >>" +DateUtils.truncate(date1, Calendar.HOUR)); //Three dates in three different formats String [] dates={"2005.03.24 11:03:26", "2005-03-24 11:03", "2005/03/24"}; //Iterate over dates and parse strings to java.util.Date objects for(int i=0; i < dates.length; i++){ Date parsedDate= DateUtils.parseDate(dates[i], new String []{"yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm"}); System.out.println("Parsed Date is >>"+parsedDate); } //Display date in HH:mm:ss format System.out.println("Now >>" +DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(System.currentTimeMillis())); } Listing 4 demonstrates some of the capabilities of the org.apache.commons.lang.DateUtils and org.apache.commons.lang.DateFormatStringUtils classes. There are many other methods that do the same thing but take various forms of input. So in all probability, if you have to parse or format a date, you should be able to do that in a single line using one of the methods provided. The output on executing the code in Listing 4 is shown in Listing 5. Listing 5. The output The time right now is >>Sat Apr 09 14:40:41 GMT+05:30 2005 Is Same Day >> true Is Same Instant >> false Date after rounding >>Sat Apr 09 15:00:00 GMT+05:30 2005 Date after truncation >>Sat Apr 09 14:00:00 GMT+05:30 2005 Parsed Date is >>Thu Mar 24 11:03:26 GMT+05:30 2005 Parsed Date is >>Thu Mar 24 11:03:00 GMT+05:30 2005 Parsed Date is >>Thu Mar 24 00:00:00 GMT+05:30 2005 Now >>14:40:43 In Listing 4, we have created two dates with a difference of one second between them. Then we check if the dates are the same using the isSameInstant() and the isSameDay() method. Next we round off and truncate the date before we take up the special case of date parsing using various formats specified in an array. Often when you are integrating your application with third-party applications, you are not one hundred-percent sure of what the input might be. I had once worked on integration with a legacy application that always seemed to have three answers to every question. So if you have to parse dates provided by such an application, you need to provide for three or four different date formats. The parseDate() method usage in Listing 4 does just this. So even if the input varies, it is able to parse the date. Also note that the patterns in the array are not in the same order as the input and yet the method finds the appropriate pattern and parses accordingly. Finally, we format and print the date as per the ISO_TIME_NO_T_FORMAT format, which is HH:mm:ss. We will now look at using Lang to generate the commonly used method, toString(). toString()Method Methods like equals(), toString(), and hashCode() are used on a regular basis. However, when it comes to actually writing implementations for these methods, not only are most of us reluctant to do that but we are also not sure how exactly and easily to write them. The builder package provides utility classes that can help you easily create implementations for these methods. In most cases it just takes one line of code. We will look at the toString capabilities of Lang. You might have noticed in Listing 4 that even if we just pass an object of java.util.Date to System.out.println(), the output we get is a proper display of the date and time. This is possible because when you just pass an object reference, the toString() method gets called automatically. So in our example we are essentially calling the toString() method of the java.util.Date class and the proper output we get is because someone has taken the trouble to override the toString() method from the java.lang.Object class in the java.util.Date class. If the toString() method is not overridden, the output you get is just the name of the class and the hashcode. No data in the class will get displayed. So if you have written a new class and wish to get a proper output on print, you need to override the toString() method in your class. Listing 6. The toString() method public class Computer { String processor; String color; int cost; /** Creates a new instance of Computer */ public Computer(String processor, String color, int cost) { this.processor=processor; this.color=color; this.cost=cost; } public static void main(String[] args) { Computer myComp=new Computer("Pentium","black",1000); System.out.println(myComp); } public String toString(){ return ToStringBuilder.reflectionToString(this); /* return ToStringBuilder.reflectionToString(this , ToStringStyle.SHORT_PREFIX_STYLE); return ToStringBuilder.reflectionToString(this , ToStringStyle.MULTI_LINE_STYLE); return new ToStringBuilder(this) .append("processor", processor).toString(); */ } } Listing 6 shows a Computer class that has three fields in it. The toString() method is what is special. The call to the reflectionToString() method is able to figure out which are the fields in the class, and then prints their name and value. In the main() method, we simply create an instance of the class and then print it. The output in this case is dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000]. So if you don't wish to put too much effort into it and yet require toString() implementations for your classes, there is no easier way than to copy and paste these two lines of code into all your classes. If you wish to have more control over what is generated, look at the commented options. You can apply various styles to the output or even build the entire output by creating a new instance of ToStringBuilder. The output, if you were to execute each of the four return statements in the listed order, is shown in Listing 7. Listing 7. The four possible outputs based on the ToStringBuilder method used 1) dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000] 2) Computer[processor=Pentium,color=black,cost=1000] 3) dev2dev.Computer@f6a746[ processor=Pentium color=black cost=1000 ] 4) dev2dev.Computer@192d342[processor=Pentium] Having to compare data objects and sort them accordingly is a pretty common requirement. So how do you think we can compare and sort objects of the Computer class we saw in Listing 6? You guessed it! Let's use Lang to sort Computer objects based on the cost of the computer. To compare objects, you need to implement the java.lang.Comparable interface. This interface has a single method compareTo(Object). The method implementation is expected to compare the current object with the object that is passed to the method. The method returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified object. So to compare Computer objects, implement the compareTo() method in the class Computer, as shown in Listing 8. Listing 8. A compareTo() method public int compareTo(Object obj) { Computer anotherComputer = (Computer)obj; //return new CompareToBuilder().reflectionCompare(this, anotherComputer); return new CompareToBuilder(). append(this.cost, anotherComputer.cost).toComparison(); } Then, to actually try out the comparison, we write a simple class named ComputerSort, as shown in Listing 9. We just add three objects to an ArrayList and then sort it. Listing 9. ComputerSort class public class ComputerSort { public static void main(String[] args) { ArrayList computerList = new ArrayList(); computerList.add(new Computer("Pentium","black", 1000)); computerList.add(new Computer("Pentium","chocolate", 334)); computerList.add(new Computer("Pentium","darkgray", 2234)); Collections.sort(computerList); System.out.println(computerList); } } When we execute ComputerSort, we will see that the objects get sorted by the value of the field cost. The CompareToBuilder like the ToStringBuilder also has a reflection-based usage option. We have commented that bit in the compareTo() method in Listing 8 because in this case the reflection option will compare all fields and get us an incorrect result. CompareToBuilder also has methods that can be used if you not only wish to compare fields in the current class but also its super class. The output on execution of the ComputerSort class is as shown in Listing 10. Listing 10. Sorted Computer objects [dev2dev.Computer@cf2c80[processor=Pentium,color=chocolate,cost=334] , dev2dev.Computer@12dacd1[processor=Pentium,color=black,cost=1000] , dev2dev.Computer@1ad086a[processor=Pentium,color=darkgray,cost=2234]] In this article we took a look at some of the key capabilities of the Jakarta Commons Lang component. The Commons project as a whole is a very useful yet underutilized project. While open source projects do use many Commons components, their adoption outside the open source world isn't nearly as widespread. Now that you have an understanding of what Lang has to offer, you should look at adopting it right away. You can also look at the Commons project for useful components that can simplify XML parsing, enable your application to talk HTTP, systematize validations, and perform many other functions.
http://www.oracle.com/technetwork/articles/entarch/commons-lang-094361.html
CC-MAIN-2014-52
refinedweb
3,031
54.93
Nesting Instinct I: def flatten(tpl): return eval(repr(tpl).replace('(', '').replace(')', '')) t= (1, (1, 2, (1, 2, 3), 3)) print flatten(t) This flatten function would actually work in the context of our app, but I would never use it in production code. My challenge today, is to tell me why this code should never be used! One must hope nobody starts devising malicious objects with exploitive repr()s. Cute idea, though. Not quite as concise as the the other flatten, but less of a crime against Python! def flatten(tpl): return tuple( map(int, repr(tpl).replace('(', ‘').replace(’)', ‘').split(’, ')) ) Remember: Don't do this at home folks :-) - Paddy. flatten = lambda t: sum(map(flatten, t), ()) if hasattr(t, ‘__iter__’) else (t,)
https://www.willmcgugan.com/blog/tech/post/nesting-instinct/
CC-MAIN-2018-30
refinedweb
123
76.11
PDL - the Perl Data Language PDL is the Perl Data Language, a perl extension that is designed for scientific and bulk numeric data processing and display. It extends perl's syntax and includes fully vectorized, multidimensional array handling, plus several paths for device-independent graphics output. For basic information on the PDL language, see the pdl(1) (lowercase) man page. You can run PDL programs directly as perl scripts that include the PDL module (with "use PDL;"), or via an interactive shell (see the perldl(1) man page). The PDL language extension includes about a dozen perl modules that form the core of the language, plus additional modules that add further functionality. The perl module "PDL" loads all of the core modules automatically, making their functions available in the current perl namespace. See also PDL::Lite or PDL::LiteF if start-up time becomes an issue. Lite and;
http://search.cpan.org/~csoe/PDL-2.4.1/Basic/PDL.pm
CC-MAIN-2014-15
refinedweb
148
51.07
Middleware that enables you to upload objects to a cluster by using an HTML form POST. The format of the form is: <![CDATA[ <form action="<swift>]]> In the form: action="<swift-url>" The URL to the Object Storage destination, such as. The name of each uploaded file is appended to the specified swift-url. So, you can upload directly to the root of container with a URL like. Optionally, you can include an object prefix to separate different users' uploads, such as. method="POST" The form methodmust be POST. enctype="multipart/form-data The enctypemust be set to multipart/form-data. name="redirect" The URL to which to redirect the browser after the upload completes. The URL has status and message query parameters added to it that indicate the HTTP status code for the upload and, optionally, additional error information. The 2nn status code indicates success. If an error occurs, the URL might include error information, such as "max_file_size exceeded". name="max_file_size" Required. The maximum number of bytes that can be uploaded in a single file upload. name="max_file_count" Required. The maximum number of files that can be uploaded with the form. name="expires" The expiration date and time for the form in UNIX Epoch time stamp format. After this date and time, the form is no longer valid. For example, 1440619048is equivalent to Mon, Wed, 26 Aug 2015 19:57:28 GMT. name="signature" The HMAC-SHA1 signature of the form. This sample Python code shows how to compute the signature: import hmac from hashlib import sha1 from time import time path = '/v1/account/container/object_prefix' redirect = ''() The key is the value of the X-Account-Meta-Temp-URL-Keyheader on the account. Use the full path from the /v1/value and onward. During testing, you can use the swift-form-signature command-line tool to compute the expiresand signaturevalues. name="x_delete_at" The date and time in UNIX Epoch time stamp format when the object will be removed. For example, 1440619048is equivalent to Mon, Wed, 26 Aug 2015 19:57:28 GMT. This attribute enables you to specify the X-Delete- Atheader value in the form POST. name="x_delete_after" The number of seconds after which the object is removed. Internally, the Object Storage system stores this value in the X-Delete-Atmetadata item. This attribute enables you to specify the X-Delete-Afterheader value in the form POST. type="file" name="filexx" Optional. One or more files to upload. Must appear after the other attributes to be processed correctly. If attributes come after the fileattribute, they are not sent with the sub- request because on the server side, all attributes in the file cannot be parsed unless the whole file is read into memory and the server does not have enough memory to service these requests. So, attributes that follow the fileattribute are ignored.
https://docs.openstack.org/liberty/config-reference/content/object-storage-form-post.html
CC-MAIN-2021-17
refinedweb
475
57.67
glControl QuestionPosted Saturday, 22 March, 2008 - 04:37 by tuennes in Hello, I am very excited about the glControl and its capabilities. I followed the tutorial but unfortunately my glControl still only shows junk, even though I cleaned the view port. This is my program: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using OpenTK.OpenGL; using OpenTK.OpenGL.Enums; namespace WindowsApplication3 { public partial class Form1 : Form { bool loaded = false; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { loaded = true; GL.ClearColor(Color.SkyBlue); // Yey! .NET Colors can be used directly! SetupViewport(); } private void glControl1_Load(object sender, EventArgs e) { } private void glControl1_Resize(object sender, EventArgs e) { if (!loaded) return; } private void glControl1_Paint(object sender, PaintEventArgs e) { if (!loaded) // Play nice(); } private void SetupViewport() { int w = glControl1.Width; int h = glControl1.Height; GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(0, w, 0, h, -1, 1); // Bottom-left corner pixel has coordinate (0, 0) GL.Viewport(0, 0, w, h); // Use all of the glControl painting area } } } Can someone give me an advice why I still only see junk ? Thanks in advance [moderator edit: code tags :)] Re: glControl Question Ok, first things first: what operating system are you using and which video card? Are the drivers for the video card up to date? The code looks correct, but double-check that glControl1.Visible is true, and that it is not partially or fully obscured/overlapped by some other control. Can you post a screenshot of the problem? (you can attach it at the opening post, preferrably as a jpeg or gif) Also, do the Windows.Forms examples work on your computer? (check Examples.exe under the Binaries directory) Re: glControl Question I am using Windows XP Pro 2002 SP 2 along with Visual Studio 2005 Pro. The graphics card is a NVidia GeForce Go 7400. Drivers are up to date. I double checked that glControl1.Visible is true, and it is not overlapped or obscured by any other control. The Windows.Forms example work fine. Screenshot is here. Thanks Re: glControl Question Does minimizing/unminimizing or moving the form out of the desktop area and into it again have any effect..? If it does, it might be that the Paint event isn't fired often enough. For example, try adding a MouseDown event handler for glControl, something like this: .. and see if glControl is repainted when clicked. Re: glControl Question No, it has no effect whatsoever. :-( Re: glControl Question Have you tried copying the whole example from the tutorial..? It's in the end of the tutorial. Does it work..? Re: glControl Question I copied and pasted the entire code from the tutorial. Same result. I think I am gonna try the whole thing on another machine. Re: glControl Question Ok, can you start from scratch? Create a new project (Windows Application), add OpenTK.dll, drag & drop the GLControl from the toolbox to the main Form. Then hook GLControl.Paint and clear / swap buffers. This should work! If it doesn't, it might be a good idea to build a debug version of OpenTK, to check what's going wrong. This is easy enough: execute "build vs" in the Build/ directory, and open the resulting solution with Visual Studio. Re: glControl Question Seems, the paint event is not connected ? This part should be in the Designer file (which was not uploaded). Try to set a breakpoint at the first line of , and see, if it pops up? If not, look into the Form1.Designer.cs for a line saying something like . If that fails, I would suggest to follow Fiddler and start from scratch. Re: glControl Question This is crazy. I set the breakpoint in glControl1_Paint and it did NOT pop up. So I looked for the PaintEventHandler in Form1.Designer.cs and it wasn't there. Please bare with me because I am coming from C/C++ and I am not yet that fluent w. C#. Re: glControl Question Glad that you found a solution! The tutorial assumes some familiarity with Windows.Forms programming under Visual Studio 2005. The most popular way of implementing a Paint event handler is double-clicking the Paint event in the Properties window of the IDE (second tab; Events IIRC). Doing that adds the glControl.Paint +=...; .. row in the Form1.Designer.cs file -- ie. creates the "hook" to the glControl_Paint() event handler method of the Form1.cs file. This was good feedback; maybe I should add a picture of the Properties window of Visual Studio to make this more clear in the tutorial.
http://www.opentk.com/node/351
CC-MAIN-2015-11
refinedweb
774
69.48
Programming FAQ¶ Contents -? What does the slash(/) in the parameter list of a function mean?odeDecodeError’ or ‘UnicodeEncodeError’ error mean? - How do I convert between tuples and lists? -? I want to do a complicated sort: can you do a Schwartzian Transform in Python? How can I sort one list by values from another list? - - - How do I check if an object is an instance of a given class or of a subclass of it? -? - General Questions¶ Is there a source code level debugger with breakpoints, single-stepping, etc.?¶ Yes. Several debuggers for Python are described below, and the built-in function breakpoint() allows you to drop into any of them.. Static type checkers such as Mypy, Pyre, and Pytype can check type hints in Python source code. You can do a similar thing in a nested scope using the nonlocal keyword: >>> def foo(): ... x = 10 ... def bar(): ... nonlocal x ... print(x) ... x += 1 ... bar() ... print(x) >>> foo() 10 object at 0x16D07CC> >>> print(a) <__main__.A object,?¶! What does the slash(/) in the parameter list of a function mean?¶ A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, pow() is a function that accepts positional-only parameters. Its documentation looks like this: >>>. The slash at the end of the parameter list means that all three parameters are positional-only. Thus, calling pow() with keyword aguments would lead to an error: >>> pow(x=3, y=4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pow() takes no keyword arguments Note that as of this writing this is only documentational and no valid syntax in Python, although there is PEP 570, which proposes a syntax for position-only parameters in Python. does not allow leading ‘0’ in a decimal number (except ‘0’). Formatted string literals and Format String Syntax sections, e.g. "{:04d}".format(144) yields '0144' and "{:.3f}".format(1.0/3.0) yields '0.333'. How do I modify a string in place?¶() . Performance¶ My program is too slow. How do I speed it up?¶ That’s a tough one, in general. First, here are a list of things to remember before diving further: Performance characteristics vary across Python implementations. This FAQ focuses on CPython. Behaviour can vary across operating systems, especially when talking about I/O or multi-threading. You should always find the hot spots in your program before attempting to optimize any code (see the profilemodule). Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the timeitmodule).module. HOW TO?¶ set keys (i.e. they are all hashable) this is often faster list.sort() method: Isorted = L[:] Isorted.sort(key=lambda s: int(s[10:15])) How can I sort one list by values from another list?¶')] >>> Use the built-in super() function: class Derived(Base): def meth(self): super(Derived, self).meth() For version prior to 3.0, you mayobjects. – a __pycache__ subdirectory-reading of a changed module, do this: import importlib import modname importlib importlib >>> import cls >>> c = cls.C() # Create an instance of C >>> importlib'
https://docs.python.org/3.7/faq/programming.html
CC-MAIN-2022-27
refinedweb
551
59.3
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello again, since the members of this list are usually remarkably quick in responding to issues, I presume that this one got a little lost in the recent OXF and release management discussions. Perhaps now someone can find a little time to look into this. If this topic happens to have been covered previously, I'd be very grateful for any pointers. Best regards and many thanks in advance, Florian - ---------- Forwarded Message ---------- Subject: Failing miserably at nailing a suspected bug in Excalibur xmlutils or Cocoon TraxTransformer Date: Thursday 18 September 2003 00:46 From: "Florian G. Haas" <f.g.haas@gmx.net> To: dev@cocoon.apache.org Hello, since I recently introduced myself in my first post to the users list, which I suppose many of you are reading at least occasionally, here's the brief version: my name is Florian, I am currently using Cocoon in order to build web sites from XML topic maps, among other things. For about three weeks now, I'm trying to dig up the reason for the behavior described on August 30 in my post "2.1: Neither LinkSerializer nor LinkGatherer producing a complete link list" to the users list.[1] Upayavira provided lots of help and I have a hunch that the namespace-related issues described in the thread really have nothing to do with the ExtendedXLinkPipe as both he and I originally supposed, but that its due to a bug buried somewhere in the Excalibur JAXP parser wrapper, the Cocoon TraxTransformer, or a combination of both. To illustrate the issue, I'll take a DocBook example. I'm quite certain that most of you are familiar with DocBook XML 4.2, and with Norm Walsh's docbook-xsl stylesheets. So for brevity's sake, I'll only post a source and output code snippet. Source DocBook XML (this is an excerpt of a document I've written to put on my personal web site): <para>This entire process is automated using the <ulink url="">Cocoon XML publishing framework</ulink> brought to you courtesy of the <ulink url="">Apache Cocoon project</ulink>. Currently, I run Cocoon off-line (using the <ulink url="">Cocoon command line interface</ulink>), and upload the generated pages onto a web server serving static content.</para> Here's the output when running Xalan 2.5.1 from the command line with the unaltered XHTML style sheet from Norm's docbook-xsl package, version 1.62: <p>This entire process is automated using the <a href="" target="_top">Cocoon XML publishing framework</a> brought to you courtesy of the <a href="" target="_top">Apache Cocoon project</a>. Currently, I run Cocoon off-line (using the <a href="" target="_top">Cocoon command line interface</a>), and upload the generated pages onto a web server serving static content.</p> This is just what's expected. Now, here's the output when using the same stylesheet in a simple Cocoon pipeline (file generator, xslt transformer using Xalan 2.5.1, XHTML serializer)[2]: <p>This entire process is automated using the <Cocoon XML publishing framework</a> brought to you courtesy of the <Apache Cocoon project</a>. Currently, I run Cocoon off-line (using the <Cocoon command line interface</a>), and upload the generated pages onto a web server serving static content.</p> Something is really not quite right here. What swallows the href attributes? Not only their values, but also their names are empty -- strange IMHO, particularly because this type of behavior seems to be limited to <a> elements. I've run into a couple of other issues as well, e.g. xmlns attributes on some elements where they aren't strictly necessary, but nothing else as bad as this. I've already spent hours debugging the transformation and serialization process, but I've been unable to nail this apparent bug. Perhaps someone with more TraxTransformer or Excalibur experience could look into it. I haven't yet filed a bug on Bugzilla about this as I'm currently only observing symptoms and can't even confirm whether it's a real issue. If I should suspect it to be, I'd be grateful for a shove in the right direction where to look closer. Currently I must confess I'm stuck. Best regards, Florian [1] thread archived at: [2] My setup is a current Cocoon CVS checkout, J2 SDK 1.4.2_01, and Tomcat 4.1.24 for JDK 1.4 with the required XML-related jars in the endorsed directory. The same files are also in jre/lib/endorsed in my JAVA_HOME. - --/bLCkgW2VC0bQC+MRAv5sAKCYijlb251sW24VC4HLhetTjC8LjgCfWGpj RaupR1key6ql99GecwUyFpk= =Dava -----END PGP SIGNATURE-----
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200309.mbox/%3C200309202155.25327.f.g.haas@gmx.net%3E
CC-MAIN-2016-50
refinedweb
774
53.41
vmod-tls lets you query details relating to a TLS connection. If called from one of the client VCL subroutines (e.g. vcl_recv or vcl_deliver), it will provide details about the client TLS connection. If called from vcl_backend_response, vmod-tls will show details from the currently established TLS backend connection. Note that the client-side functionality relies on using Varnish’s native TLS implementation. If you are currently terminating TLS in a separate process (for example using Hitch), you should instead use the PROXY VMOD which offers similar functionality. The following example will report which TLS version and which cipher is used for the client connection. import tls; sub vcl_deliver { if (tls.is_tls()) { # Report cipher and TLS version as a response header set resp.http.tls-version = tls.version(); set resp.http.tls-cipher = tls.cipher(); # Alternatively, we can log it std.log("tls-version: " + tls.version()); std.log("tls-cipher: " + tls.cipher()); } } The following example will report information about the backend connection. This is only available from vcl_backend_response. import tls; sub vcl_backend_response { if (tls.is_tls()) { # Report cipher and TLS version as a backend response header set beresp.http.be-tls-version = tls.version(); set beresp.http.be-tls-cipher = tls.cipher(); # Also log: std.log("backend-tls-version: " + tls.version()); std.log("backend-tls-cipher: " + tls.cipher()); } } BOOL is_tls() Indicates whether the peer is connected over an SSL/TLS connection. STRING version() Returns the TLS version in use for this connection. E.g. “TLSv1.2”. STRING cipher() Returns the cipher that was chosen during the TLS handshake. STRING authority() Returns the hostname presented for Server Name Indication (SNI). STRING alpn() Returns the result of the Application Layer Protocol Negotiation (ALPN). This will contain one of “http/1.1”, “h2” or NULL if no ALPN happened. Varnish does not currently do ALPN with its backends, so if used in vcl_backend_response this will always return NULL. STRING cert_sign() Certificate signature algorithm. E.g. “SHA256”. STRING cert_key() The algorithm used to generate the certificate. E.g. “RSA2048”.
https://docs.varnish-software.com/varnish-cache-plus/vmods/tls/
CC-MAIN-2021-31
refinedweb
335
52.26
Learn more about Scribd Membership Discover everything Scribd has to offer, including books and audiobooks from major publishers. Contents0 1 2 3 4 5 Operating system interfaces The rst process Traps, interrupts, and drivers Locking Scheduling File system7 17 31 43 51 63 79 83 89 cat System call Description fork() Create process exit() Terminate current process wait() Wait for a child process kill(pid) Terminate process pid getpid() Return current processs id sleep(n) Sleep for n time units exec(lename, *argv) Load a le and execute it sbrk(n) Grow processs memory by n bytes open(lename, ags) Open a le; ags indicate read/write read(fd, buf, n) Read n byes from an open le into buf write(fd, buf, n) Write n bytes to an open le close(fd) Release open le fd dup(fd) Duplicate fd pipe(p) Create a pipe and return fds in p chdir(dirname) Change the current directory mkdir(dirname) Create a new directory mknod(name, major, minor) Create a device le fstat(fd) Return info about an open le link(f1, f2) Create another name (f2) for the le f1 unlink(lename) Remove a le The rest of this chapter outlines xv6s servicesprocesses, memory, le descriptors, pipes, and le systemand illustrates them with code snippets and discussions of how the shell uses them. The shells use of system calls illustrates how carefully they have been designed. The shell is an ordinary program that reads commands from the user and executes them, and is the primary user interface to traditional Unix-like systems. The fact that the shell is a user program, not part of the kernel, illustrates the power of the system call interface: there is nothing special about the shell. It also means that the shell is easy to replace, and modern Unix systems have a variety of shells to choose from, each with its own syntax and semantics. The xv6 shell is a simple implementation of the essence of the Unix Bourne shell. Its implementation can be found at line (7650). per-process state private to the kernel. Xv6 provides time-sharing: it transparently switches the available CPUs among the set of processes waiting to execute. When a process is not executing, xv6 saves its CPU registers, restoring them when it next runs the process. Each process can be uniquely identied by a positive integer called its process identier, or pid. A process may create a new process using the fork system call. Fork creates a new process, called the child process, with exactly the same memory contents as the calling process, called the parent process. Fork returns in both the parent and the child. In the parent, fork returns the childs pid; in the child, it returns zero. For example, consider the following program fragment:int pid; pid = fork(); if(pid > 0){ printf("parent: child=%d\n", pid); pid = wait(); printf("child %d is done\n", pid); } else if(pid == 0){ printf("child: exiting\n"); exit(); } else { printf("fork error\n"); } The exit system call causes the calling process to stop executing and to release resources such as memory and open les. The wait system call returns the pid of an exited child of the current process; if none of the callers children has exited, wait waits for one to do so. In the example, the output linesparent: child=1234 child: exiting might come out in either order, depending on whether the parent or child gets to its printf call rst. After those two, the child exits, and then the parents wait returns, causing the parent to printparent: child 1234 is done Note that the parent and child were executing with dierent memory and dierent registers: changing a variable in one does not aect the other. The exec system call replaces the calling processs memory with a new memory image loaded from a le stored in the le system. The le must have a particular format, which species which part of the le holds instructions, which part is data, at which instruction to start, etc.. The format xv6 uses is called the ELF format, which Chapter 1 discusses in more detail. When exec succeeds, it does not return to the calling program; instead, the instructions loaded from the le start executing at the entry point declared in the ELF header. Exec takes two arguments: the name of the le containing the executable and an array of string arguments. For example: char *argv[3]; argv[0] = "echo"; argv[1] = "hello"; argv[2] = 0; exec("/bin/echo", argv); printf("exec error\n"); This fragment replaces the calling program with an instance of the program /bin/echo running with the argument list echo hello. Most programs ignore the rst argument, which is conventionally the name of the program. The xv6 shell uses the above calls to run programs on behalf of users. The main structure of the shell is simple; see main on line (7801). The main loop reads the input on the command line using getcmd. Then it calls fork, which creates another running shell program. The parent shell calls wait, while the child process runs the command. For example, if the user had typed echo hello at the prompt, runcmd would have been called with echo hello as the argument. runcmd (7706) runs the actual command. For echo hello, it would call exec on line (7726). If exec succeeds then the child will execute instructions from echo instead of runcmd. At some point echo will call exit, which will cause the parent to return from wait in main (7801). You might wonder why fork and exec are not combined in a single call; we will see later that separate calls for creating a process and loading a program is a clever design. Xv6 allocates most user-space memory implicitly: fork allocates the memory required for the childs copy of the parents memory, and exec allocates enough memory to hold the executable le. A process that needs more memory at run-time (perhaps for malloc) can call sbrk(n) to grow its data memory by n bytes; sbrk returns the location of the new memory. Xv6 does not provide a notion of users or of protecting one user from another; in Unix terms, all xv6 processes run as root. 10 will return the bytes following the ones returned by the rst read. When there are no more bytes to read, read returns zero to signal the end of the le. The call write(fd, buf, n) writes n bytes from buf to the le descriptor fd and returns the number of bytes written. Fewer than n bytes are written only when an error occurs. Like read, write writes data at the current le oset and then advances that oset by the number of bytes written: each write picks up where the previous one left o. The following program fragment (which forms the essence of cat) copies data from its standard input to its standard output. If an error occurs, it writes a message to the standard error.char buf[512]; int n; for(;;){ n = read(0, buf, sizeof buf); if(n == 0) break; if(n < 0){ fprintf(2, "read error\n"); exit(); } if(write(1, buf, n) != n){ fprintf(2, "write error\n"); exit(); } } The important thing to note in the code fragment is that cat doesnt know whether it is reading from a le, console, or a pipe. Similarly cat doesnt know whether it is printing to a console, a le, or whatever. The use of le descriptors and the convention that le descriptor 0 is input and le descriptor 1 is output allows a simple implementation of cat. The close system call releases a le descriptor, making it free for reuse by a future open, pipe, or dup system call (see below). A newly allocated le descriptor is always the lowest-numbered unused descriptor of the current process. File descriptors and fork interact to make I/O redirection easy to implement. Fork copies then parents le descriptor table along with its memory, so that the child starts with exactly the same open les as the parent. The system call exec replaces the calling processs memory but preserves its le table. This behavior allows the shell to implement I/O redirection by forking, reopening chosen le descriptors, and then execing the new program. Here is a simplied version of the code a shell runs for the command cat <input.txt:char *argv[2]; argv[0] = "cat"; argv[1] = 0; if(fork() == 0) { close(0); open("input.txt", O_RDONLY); 11 exec("cat", argv); } After the child closes le descriptor 0, open is guaranteed to use that le descriptor for the newly opened input.txt: 0 will be the smallest available le descriptor. Cat then executes with le descriptor 0 (standard input) referring to input.txt. The code for I/O redirection in the xv6 shell works exactly in this way (7730). Recall that at this point in the code the shell has already forked the child shell and that runcmd will call exec to load the new program. Now it should be clear why it is a good idea that fork and exec are separate calls. This separation allows the shell to x up the child process before the child runs the intended program. Although fork copies the le descriptor table, each underlying le oset is shared between parent and child. Consider this example:if(fork() == 0) { write(1, "hello ", 6); exit(); } else { wait(); write(1, "world\n", 6); } At the end of this fragment, the le attached to le descriptor 1 will contain the data hello world. The write in the parent (which, thanks to wait, runs only after the child is done) picks up where the childs write left o. This behavior helps produce useful results from sequences of shell commands, like (echo hello; echo world) >output.txt. The dup system call duplicates an existing le descriptor, returning a new one that refers to the same underlying I/O object. Both le descriptors share an oset, just as the le descriptors duplicated by fork do. This is another way to write hello world into a le:fd = dup(1); write(1, "hello ", 6); write(fd, "world\n", 6); Two le descriptors share an oset if they were derived from the same original le descriptor by a sequence of fork and dup calls. Otherwise le descriptors do not share osets, even if they resulted from open calls for the same le. Dup allows shells to implement commands like this: ls existing-file non-existing-file > tmp1 2>&1. The 2>&1 tells the shell to give the command a le descriptor 2 that is a duplicate of descriptor 1. Both the name of the existing le and the error message for the non-existing le will show up in the le tmp1. The xv6 shell doesnt support I/O redirection for the error le descriptor, but now you can implement it. File descriptors are a powerful abstraction, because they hide the details of what they are connected to: a process writing to le descriptor 1 may be writing to a le, to a device like the console, or to a pipe. Code: PipesDRAFT as of September 7, 2011 12 A pipe is a small kernel buer exposed to processes as a pair of le descriptors, one for reading and one for writing. Writing data to one end of the pipe makes that data available for reading from the other end of the pipe. Pipes provide a way for processes to communicate. The following example code runs the program wc with standard input connected to the read end of a pipe]); } The program calls pipe, which creates a new pipe and records the read and write le descriptors in the array p. After fork, both parent and child have le descriptors referring to the pipe. The child dups the read end onto le descriptor 0, closes the le descriptors in p, and execs wc. When wc reads from its standard input, it reads from the pipe. The parent writes to the write end of the pipe and then closes both of its le descriptors. If no data is available, a read on a pipe waits for either data to be written or all le descriptors referring to the write end to be closed; in the latter case, read will return 0, just as if the end of a data le had been reached. The fact that read blocks until it is impossible for new data to arrive is one reason that its important for the child to close the write end of the pipe before executing wc above: if one of wcs le descriptors referred to the write end of the pipe, wc would never see end-of-le. The xv6 shell implements pipes in a manner similar to the above code (7750). The child process creates a pipe to connect the left end of the pipe with the right end of the pipe. Then it calls runcmd for the left part of the pipe and runcmd for the right end of the pipe, and waits for the left and the right end to nish, by calling wait twice. The right end of the pipe may be a command that itself includes a pipe (e.g., a | b | c), which itself forks two new child processes (one for b and one for c). Thus, the shell may create a tree of processes. The leaves of this tree are commands and the interior nodes are processes that wait until the left and right children complete. In principle, you could have the interior nodes run the left end of a pipe, but doing so correctly will complicate the implementation. Pipes may seem no more powerful than temporary les: the pipeline 13 There are at least three key dierences between pipes and temporary les. First, pipes automatically clean themselves up; with the le redirection, a shell would have to be careful to remove /tmp/xyz when done. Second, pipes can pass arbitrarily long streams of data, while le redirection requires enough free space on disk to store all the data. Third, pipes allow for synchronization: two processes can use a pair of pipes to send messages back and forth to each other, with each read blocking its calling process until the other process has sent data with write. The rst changes the processs current directory to /a/b; the second neither refers to nor modies the processs current directory. There are multiple system calls to create a new le or directory: mkdir creates a new directory, open with the O_CREATE ag creates a new data le, and mknod creates a new device le. This example illustrates all three:mkdir("/dir"); fd = open("/dir/file", O_CREATE|O_WRONLY); close(fd); mknod("/console", 1, 1); Mknod creates a le in the le system, but the le has no contents. Instead, the les metadata marks it as a device le and records the major and minor device numbers (the two arguments to mknod), which uniquely identify a kernel device. When a process later opens the le, the kernel diverts read and write system calls to the kernel device implementation instead of passing them to the le system. fstat retrieves information about the object a le descriptor refers to. It lls in a struct stat, dened in stat.h as: 14 #define T_DIR 1 #define T_FILE 2 #define T_DEV 3 struct stat { short type; int dev; uint ino; short nlink; uint size; }; // // // // // Type of file Device number Inode number on device Number of links to file Size of file in bytes A les name is distinct from the le itself; the same underlying le, called an inode, can have multiple names, called links. The link system call creates another le system name referring to the same inode as an existing le. This fragment creates a new le named both a and b.open("a", O_CREATE|O_WRONLY); link("a", "b"); Reading from or writing to a is the same as reading from or writing to b. Each inode is identied by a unique inode number. After the code sequence above, it is possible to determine that a and b refer to the same underlying contents by inspecting the result of fstat: both will return the same inode number (ino), and the nlink count will be set to 2. The unlink system call removes a name from the le system. The les inode and the disk space holding its content are only freed when the les link count is zero and no le descriptors refer to it. Thus addingunlink("a"); to the last code sequence leaves the inode and le content accessible as b. Furthermore,fd = open("/tmp/xyz", O_CREATE|O_RDWR); unlink("/tmp/xyz"); is an idiomatic way to create a temporary inode that will be cleaned up when the process closes fd or exits. Xv6 commands for le system operations are implemented as user-level programs such as mkdir, ln, rm, etc. This design allows anyone to extend the shell with new user commands. In hind-sight this plan seems obvious, but other systems designed at the time of Unix often built such commands into the shell (and built the shell into the kernel). One exception is cd, which built into the shell (7816). The reason is that cd must change the current working directory of the shell itself. If cd were run as a regular command, then the shell would fork a child process, the child process would run cd, change the childs working directory, and then return to the parent. The parents (i.e., the shells) working directory would not change. Real worldDRAFT as of September 7, 2011 15 Unixs combination of the standard le descriptors, pipes, and convenient shell syntax for operations on them was a major advance in writing general-purpose reusable programs. The idea sparked a whole culture of software tools that was responsible for much of Unixs power and popularity, and the shell was the rst so-called scripting language. The Unix system call interface persists today in systems like BSD, Linux, and Mac OS X. Modern kernels provide many more system calls, and many more kinds of kernel services, than xv6. For the most part, modern Unix-derived operating systems have not followed the early Unix model of exposing devices as special les, like the console device le discussed above. The authors of Unix went on to build Plan 9, which applied the resources are les concept to modern facilities, representing networks, graphics, and other resources as les or le trees. The le system as an interface has been a very powerful idea, most recently applied to network resources in the form of the World Wide Web. Even so, there are other models for operating system interfaces. Multics, a predecessor of Unix, blurred the distinction between data in memory and data on disk, producing a very dierent avor of interface. The complexity of the Multics design had a direct inuence on the designers of Unix, who tried to build something simpler. This book examines how xv6 implements its Unix-like interface, but the ideas and concepts apply to more than just Unix. Any operating system must multiplex processes onto the underlying hardware, isolate processes from each other, and provide mechanisms for controlled inter-process communication. After studying xv6, you should be able to look at other, more complex operating systems and see the concepts underlying xv6 in those systems as well. 16 Paging hardwareXv6 runs on Intel 80386 or later (x86) processors on a PC platform, and much of its low-level functionality (for example, its virtual memory implementation) is x86specic. This book assumes the reader has done a bit of machine-level programming on some architecture, and will introduce x86-specic ideas as they come up. Appendix A briey outlines the PC platform. The x86 paging hardware uses a page table to translate (or map) a virtual address (the address that an x86 instruction manipulates) to a physical address (an address that the processor chip sends to main memory). An x86 page table is logically an array of 2^20 (1,048,576) page table entries (PTEs). Each PTE contains a 20-bit physical page number (PPN) and some ags. The paging hardware translates a virtual address by using its top 20 bits to index into the page table to nd a PTE, and replacing those bits with the PPN in the PTE. The paging hardware copies the low 12 bits unchanged from the virtual to the translated physical address. Thus a page table gives the operating system control over virtual-to-physical address translations at the granularity of aligned chunks of 4096 (2^12) bytes. Such a chunk is called a page. As shown in Figure 1-1, the actual translation happens in two steps. A page table is stored in physical memory as a two-level tree. The root of the tree is a 4096-byte page directory that contains 1024 PTE-like references to page table pages. Each page table page is an array of 1024 32-bit PTEs. The paging hardware uses the top 10 bits of a virtual address to select a page directory entry. If the page directory entry is present, the paging hardware uses the next 10 bits of the virtual address to select a PTE from the page table page that the page directory entry refers to. If either the page directory entry or the PTE is not present, the paging hardware raises a fault. This two-level structure allows a page table to omit entire page table pages in the common case in which large ranges of virtual addresses have no mappings. 17 VIrtual address10 10 12 Physical Address20 12 Dir Table Offset PPN Offset 20 1023 1 CR3 0 31 12 11 10 9 8 7 6 5 4 3 2 1 0 Physical Page Number Page table and page directory entries are identical except for the D bit. A V L DA CW UW P DT PWUWT CD ADAVL Present Writable User 1=Write-through, 0=Write-back Cache Disabled Accessed Dirty (0 in page directory) Available for system use Each PTE contains ag bits that tell the paging hardware how the associated virtual address is allowed to be used. PTE_P indicates whether the PTE is present: if it is not set,. Figure 1-1 shows how it all works. A few notes about terms. Physical memory refers to storage cells in DRAM. A byte of physical memory has an address, called a physical address. A program uses virtual addresses, which the paging hardware translate to physical addresses, and then send to the DRAM hardware to read or write storage. At this level of discussion there is no such thing as virtual memory, only virtual addresses. 18 cutes in the kernel mappings of the processs address space. This arrangement exists so that the kernels system call code can directly refer to user memory. In order to leave room for user memory to grow, xv6s address spaces map the kernel at high addresses, starting at 0x80100000. Virtual4. Layout of a virtual address space and the physical address space. struction after the one that enabled paging. Now entry needs to transfer to the kernels C code, and run it in high memory. First it must make the stack pointer, %esp, point to a stack so that C code will work (1054). All symbols have high addresses, including stack, so the stack will still be valid even when the low mappings are removed. Finally entry jumps to main, which is also a high address. The indirect jump is needed because the assembler would generate a PC-relative direct jump, which would execute the low-memory version of main. Main cannot return, since the theres no return PC on the stack. Now the kernel is running in high addresses in the function main (1216). lowing a process to address up to 2 GB of memory. When a process asks xv6 for more memory, xv6 rst nds free physical pages to provide the storage, and then adds PTEs to the processs page table that point to the new physical pages. xv6 sets the PTE_U, PTE_W, and PTE_P ags in these PTEs. Most processes do not use the entire user address space; xv6 leaves PTE_P clear in unused PTEs. Dierent processes page tables translate user addresses to dierent pages of physical memory, so that each process has private user memory. Xv6 includes all mappings needed for the kernel to run in every processs page table; these mappings all appear above KERNBASE. It maps virtual addresses KERNBASE:KERNBASE+PHYSTOP to 0:PHYSTOP. One reason for this mapping is so that the kernel can use its own instructions and data. Another reason is that the kernel sometimes needs to be able to write a given page of physical memory, for example when creating page table pages; having every physical page appear at a predictable virtual address makes this convenient. A defect of this arrangement is that xv6 cannot make use of more than 2 GB of physical memory. Some devices that use memory-mapped I/O appear at physical addresses starting at 0xFE000000, so xv6 page tables including a direct mapping for them. Xv6 does not set the PTE_U ag in the PTEs above KERNBASE, so only the kernel can use them. Having every processs page table contain mappings for both user memory and the entire kernel is convenient when switching from user code to kernel code during system calls and interrupts: such switches do not require page table switches. For the most part the kernel does not have its own page table; it is almost always borrowing some processs page table. To review, xv6 ensures that each process can only use its own memory, and that a process sees its memory as having contiguous virtual addresses. xv6 implements the rst by setting the PTE_U bit only on PTEs of virtual addresses that refer to the processs own memory. It implements the second using the ability of page tables to translate successive virtual addresses to whatever physical pages happen to be allocated to the process. walkpgdir (1654) mimics the actions of the x86 paging hardware as it looks up the PTE for a virtual address (see Figure 1-1). walkpgdir uses the upper 10 bits of the virtual address to nd the page directory entry (1659). If the page directory entry isnt present, then the required page table page hasnt yet been allocated; if the alloc argument is set, walkpgdir allocates it and puts its physical address in the page directory. Finally it uses the next 10 bits of the virtual address to nd the address of the PTE in the page table page (1672). 22 pages in kinit), and sometimes uses addresses as pointers to read and write memory (e.g., manipulating the run structure stored in each page); this dual use of addresses is the main reason that the allocator code is full of C type casts. The other reason is that freeing and allocation inherently change the type of the memory. The function kfree (275 rst element in the free list. When creating the rst kernel page table, setupkvm and walkpgdir use enter_alloc (2725) instead of kalloc. This memory allocator moves the end of the kernel by 1 page. enter_alloc uses the symbol end, which the linker causes to have an address that is just beyond the end of the kernels data segment. A PTE can only refer to a physical address that is aligned on a 4096-byte boundary (is a multiple of 4096), so enter_alloc uses PGROUNDUP to ensure that it allocates only aligned physical addresses. Memory allocated with enter_alloc is never freed. top of new stack esp ... eip ... p->tf address forkret will return to edi trapret eip ... p->context edi (empty) p->kstack to allocate a slot (a struct proc) in the process table and to initialize the parts of the processs state required for its kernel thread to execute. Allocproc is called for all new processes, while userinit is called only for the very rst process. Allocproc scans the table for a process with state UNUSED (2161-2163). When it nds an unused process, allocproc sets the state to EMBRYO to mark it as used and gives the process a unique pid (2151-2169). Next, it tries to allocate a kernel stack for the processs kernel thread. If the memory allocation fails, allocproc changes the state back to UNUSED and returns zero to signal failure. Now allocproc must set up the new processs kernel stack. Ordinarily processes are created only. The layout of the prepared kernel stack will be as shown in Figure 1-3. allocproc does part of this work by setting up return program counter values that will cause the new processs kernel thread to rst execute in forkret and then in trapret (2186-2191). The kernel thread will start executing with register contents copied from p->context. Thus setting p->context->eip to forkret will cause the kernel thread to execute at the start of forkret (2483). This function will return to whatever address is at the bottom of the stack. The context switch code (2658) 24 (2927). This setup is the same for ordinary fork and for creating the rst process, though in the latter case the process will start executing at location zero rather than at a return from fork. As we will see in Chapter 2,s kernel stack. userinit writes values at the top of the new stack that look just like those that would be there if the process had entered the kernel via an interrupt (2214-2220), so that the ordinary code for returning from the kernel back to the processs user code will work. These values are a struct trapframe which stores the user registers. Now the new processs kernel stack is completely prepared as shown in Figure 1-3. The rst process is going to execute a small program (initcode.S; (7500)). The process needs physical memory in which to store this program, the program needs to be copied to that memory, and the process needs a page table that refers to that memory. userinit calls setupkvm (1734) to create a page table for the process with (at rst) mappings only for memory that the kernel uses. This function is the same one that the kernel used to setup its page table. The initial contents of the rst processs memory are the compiled form of initcode.S; as part of the kernel build process, the linker embeds that binary in the kernel and denes two special symbols _binary_initcode_start and _binary_initcode_size telling the location and size of the binary. Userinit copies that binary into the new processs memory by calling inituvm, which allocates one page of physical memory, maps virtual address zero to that memory, and copies the binary to that page (1786). 2. The stack pointer %esp is the processs largest valid virtual address, p->sz. The instruction pointer is the entry point for the initcode, address 0. The function userinit sets p->name to initcode mainly for debugging. Setting p->cwd sets the processs current working directory; we will examine namei in detail in Chapter 5. Once the process is initialized, userinit marks it available for scheduling by setting p->state to RUNNABLE. vm to tell the hardware to start using the target processs page table (1764).s kernel stack. We will reexamine the task state segment in Chapter 2. scheduler now sets p->state to RUNNING and calls swtch (2658) to perform a context switch to the target processsuler) rather than in any processs kernel thread context. Well examine switch in more detail in Chapter 4. The nal ret instruction (2677) pops a new %eip from the stack, nishing the context switch. Now the processor is running the kernel thread of process p. Allocproc set initprocs p->context->eip to forkret, so the ret starts executing forkret. Forkret releases the ptable.lock (see Chapter 3). On the rst invocation (that is this one), forkret (2483) runs initialization functions that cannot be run from main because they must be run in the context of a regular process with its own kernel stack. Then, forkret returns. Allocproc arranged that the top word on the stack after p->context is popped o would be trapret, so now trapret begins executing, with %esp set to p->tf. Trapret (2927) uses pop instructions to walk up the trap frame just as swtch did with the kernel context: popal restores the general registers, then the popl instructions restore %gs, %fs, %es, and %ds. The addl skips over the two elds trapno and errcode. Finally, the iret instructions pops %cs, %eip, and %flags o the stack. The contents of the trap frame have been transferred to the CPU state, so the processor continues at the %eip specied in the trap frame. For initproc, that means virtual address zero, the rst instruction of initcode.S. At this point, %eip holds zero and %esp holds 4096. These are virtual addresses in the processs address space. The processors paging hardware translates them into physical addresses. allocuvm set up the PTE for the page at virtual address zero to point to the physical memory allocated for this process, and marked that PTE with PTE_U so that the process can use it. No other PTEs in the processs page table have the PTE_U bit set. The fact that userinit (2214) set up the low bits of %cs to run the processs user code at CPL=3 means that the user code can only use PTE entries with PTE_U set, and cannot modify sensitive hardware registers such as %cr3. So the process is constrained to using only its own memory. Initcode.S (7508) begins by pushing three values on the stack$argv, $init, and $0 (7521-7523). If the exec fails and does return, initcode loops calling the exit system call, which denitely should not return (7515-7519). 26 KERNBASE heap PAGESIZE argument 0 ... argument N 0 address of argument 0 ... address of argument N address of address of argument 0 argc 0xFFFFFFF (empty) nul-terminated string argv[argc] argv[0] argv argument of main argc argument of main return PC for main text 0 Figure 1-4. Memory layout of a user process with its initial stack. The arguments to the exec system call are $init and $argv. The nal zero makes this hand-written system call look like the ordinary system calls, as we will see in Chapter 2. As before, this setup avoids special-casing the rst process (in this case, its rst system call), and instead reuses code that xv6 must provide for standard operation. ExecAs we saw in Chapter 0, exec replaces the memory and registers of the current process with a new program, but it leaves the le descriptors, process id, and parent process the same. Figure 1-4 shows the user memory image of an executing process. The heap is above the stack so that it can expand (with sbrk). The stack is a single page, and is shown with the initial contents as created by exec. Strings containing the commandline arguments, as well as an array of pointers to them, are at the very top of the stack. Just under that are values that allow a program to start at main as if the function call main(argc, argv) had just started. Code: execWhen the system call arrives (Chapter 2 will explain how that happens), syscall invokes sys_exec via the syscalls table (3250). Sys_exec (5620) parses the system call arguments (also explained in Chapter 2), and invokes exec (5642).DRAFT as of September 7, 2011 27 Exec (5710) opens the named binary path using namei (5720), which is explained in Chapter 5, and then reads the ELF header. Xv6 applications are described in the widely-used ELF format, dened in elf.h. An ELF binary consists of an ELF header, struct elfhdr (0955), followed by a sequence of program section headers, struct proghdr (0974). Each proghdr describes a section of the application that must be loaded into memory; xv6 programs have only one program section header, but other systems might have separate sections for instructions and data. The rst step is a quick check that the le probably contains an ELF binary. An ELF binary starts with the four-byte magic number 0x7F, E, L, F, or ELF_MAGIC (0952). If the ELF header has the right magic number, exec assumes that the binary is well-formed. Then exec allocates a new page table with no user mappings with setupkvm (5731), allocates memory for each ELF segment with allocuvm (5743), and loads each segment into memory with loaduvm (5745).. loaduvm (1803) uses walkpgdir to nd the physical address of the allocated memory at which to write each page of the ELF segment, and readi to read from the le. The program section headers filesz may be less than the memsz, indicating that the gap between them should be lled with zeroes (for C global variables) rather than read from the le. For /init, filesz is 2240 bytes and memsz is 2252 bytes, and thus allocuvm allocates enough physical memory to hold 2252 bytes, but reads only 2240 bytes from the le /init. Now exec allocates and initializes the user stack. It allocates just one stack page. It also places an inaccessible page just below the stack page, so that programs that try to use more than one page will fault. This inaccessible page also allows exec to deal with arguments that are too large; in that situation, the copyout function that exec uses to copy arguments to the stack will notice that the destination page in not accessible, and will return 1. Exec copies the argument strings to the top of the stack one at a time, recording the pointers to them in ustack. It places a null pointer at the end of what will be the argv list passed to main. The rst three entries in ustack are the fake return PC, argc, and argv pointer. During the preparation of the new memory image, if exec detects an error like an invalid program segment, it jumps to the label bad, frees the new image, and returns 1. Exec must wait to free the old image until it is sure that the system call will succeed: if the old image is gone, the system call cannot return 1 to it. The only error cases in exec happen during the creation of the image. Once the image is complete, exec can install the new image (5789) and free the old one (5790). Finally, execDRAFT as of September 7, 2011 28 returns 0. Success! Now the initcode (7500) is done. Exec has replaced it with the /init binary, loaded out of the le system. Init (7610) creates a new console device le if needed and then opens it as le descriptors 0, 1, and 2. Then it loops, starting a console shell, handles orphaned zombies until the shell exits, and repeats. The system is up. Although the system is up, we skipped over some important subsystems of xv6. The next chapter examines how xv6 congures the x86 hardware to handle the system call interrupt caused by int $T_SYSCALL. The rest of the book explains process management and the le system. Real worldMost operating systems have adopted the process concept, and most processes look similar to xv6s. A real operating system would nd free proc structures with an explicit free list in constant time instead of the linear-time search in allocproc; xv6 uses the linear scan (the rst of many) for simplicity. Like most operating systems, xv6 uses the paging hardware for memory protection and mapping. Most operating systems make far more sophisticated use of paging than xv6; for example, xv6 lacks demand paging from disk, copy-on-write fork, shared memory, and automatically extending stacks. The x86 also supports address translation using segmentation (see Appendix B), but xv6 uses them only for the common trick of implementing per-cpu variables such as proc that are at a xed address but have dierent values on dierent CPUs (see seginit). Implementations of per-CPU (or per-thread) storage on non-segment architectures would dedicate a register to holding a pointer to the per-CPU data area, but the x86 has so few general registers that the extra eort required to use segmentation is worthwhile. xv6s address space layout has the defect that it cannot make use of more than 2 GB of physical RAM. Its possible to x this, though the best plan would be to switch to a machine with 64-bit addresses. Xv6 should determine the actual RAM conguration, instead of assuming 240 MB. On the x86, there are at least three common algorithms: the rst is to probe the physical address space looking for regions that behave like memory, preserving the values written to them; the second is to read the number of kilobytes of memory out of a known 16-bit location in the PCs non-volatile RAM; and the third is to look in BIOS memory for a memory layout table left as part of the multiprocessor tables. Reading the memory layout table is complicated. Memory allocation was a hot topic a long time ago, the basic problems being ecient use of very limited memory and preparing for unknown future requests. See Knuth. Today people care more about speed than space-eciency. In addition, a more elaborate kernel would likely allocate many dierent sizes of small blocks, rather than (as in xv6) just 4096-byte blocks; a real kernel allocator would need to handle small allocations as well as large ones. Exec is the most complicated code in xv6. It involves pointer translation (in sys_exec too), many error cases, and must replace one running process with another. Real world operationg systems have even more complicated exec implementations. 29 They handle shell scripts (see exercise below), more complicated ELF binaries, and even multiple binary formats. Exercises1. Set a breakpoint at swtch. Single step with gdbs stepi through the ret to forkret, then use gdbs finish to proceed to trapret, then stepi until you get to initcode at virtual address zero. 2. Look at real operating systems to see how they size memory. 3. If xv6 had not used super pages, what would be the right declaration for entrypgdir? 4. Unix implementations of exec traditionally include special handling for shell scripts. If the le to execute begins with the text #!, then the rst line is taken to be a program to run to interpret the le. For example, if exec is called to run myprog arg1 and myprogs rst line is #!/interp, then exec runs /interp with command line /interp myprog arg1. Implement support for this convention in xv6. 5. KERNBASE limits the amount of memory a single process can use, which might be irritating on a machine with a full 4 GB of RAM. Would raising KERNBASE allow a process to use more memory? 30 program invokes a system call by generating an interrupt using the int instruction. Similarly, exceptions generate an interrupt too. Thus, if the operating system has a plan for interrupt handling, then the operating system can handle system calls and exceptions too. The basic plan is as follows. An interrupts stops the normal processor loop and starts executing a new sequence called an interrupt handler. Before starting the interrupt handler, the processor saves its registers, so that the operating system can restore them when it returns from the interrupt. A challenge in the transition to and from the interrupt handler is that the processor should switch from user mode to kernel mode, and back. A word on terminology: Although the ocial x86 term is interrupt, x86 refers to all of these as traps, largely because it was the term used by the PDP11/40 and therefore is the conventional Unix term. This chapter uses the terms trap and interrupt interchangeably, but it is important to remember that traps are caused by the current process running on a processor (e.g., the process makes a system call and as a result generates a trap), and interrupts are caused by devices and may not be related to the currently running process. For example, a disk may generate an interrupt when it is done retrieving a block for one process, but at the time of the interrupt some other process may be running. This property of interrupts makes thinking about interrupts more dicult than thinking about traps, because interrupts happen concurrently with other activities. Both rely, however, on the same hardware mechanism to transfer control between user and kernel mode securely, which we will discuss next. X86 protectionThe x86 has 4 protection levels, numbered 0 (most privilege) to 3 (least privilege). In practice, most operating systems use only 2 levels: 0 and 3, which are then called kernel mode and user mode, respectively. The current privilege level with which the x86 executes instructions is stored in %cs register, in the eld CPL. On the x86, interrupt handlers are dened in the interrupt descriptor table (IDT). The IDT has 256 entries, each giving the %cs and %eip to be used when handling the corresponding interrupt. To make a system call on the x86, a program invokes the int n instruction, where n species the index into the IDT. The int instruction performs the following steps: Fetch the nth descriptor from the IDT, where n is the argument of int. Check that CPL in %cs is <= DPL, where DPL is the privilege level in the descriptor. Save %esp and %ss in a CPU-internal registers, but only if the target segment selectors PL < CPL. Load %ss and %esp from a task segment descriptor. Push %ss. 32 esp Push %esp. Push %eflags. Push %cs. Push %eip. Clear some bits of %eflags. Set %cs and %eip to the values in the descriptor. The int instruction is a complex instruction, and one might wonder whether all these actions are necessary. The check CPL <= DPL allows the kernel to forbid systems for some privilege levels. For example, for a user program to execute int instruction succesfully, the DPL must be 3. If the user program doesnt have the appropriate privilege, then int instruction will result in int 13, which is a general protection fault. As another example, the int instruction cannot use the user stack to save values, because the user might not have set up an appropriate stack so that hardware uses the stack specied in the task segments, which is setup in kernel mode. Figure 2-1 shows the stack after an int instruction completes and there was a privilege-level change (the privilege level in the descriptor is lower than CPL). If the int instruction didnt require a privilege-level change, the x86 wont save %ss and %esp. After both cases, %eip is pointing to the address specied in the descriptor table, and the instruction at that address is the next instruction to be executed and the rst instruction of the handler for int n. It is job of the operating system to implement these handlers, and below we will see what xv6 does. An operating system can use the iret instruction to return from an int instruction. It pops the saved values during the int instruction from the stack, and resumes execution at the saved %eip. 33 again (7513). The process pushed the arguments for an exec call on the processs stack, and put the system call number in %eax. The system call numbers match the entries in the syscalls array, a table of function pointers (3250). We need to arrange that the int instruction switches the processor from user mode to kernel mode, that the kernel invokes the right kernel function (i.e., sys_exec), and that the kernel can retrieve the arguments for sys_exec. The next few subsections describes how xv6 arranges this for system calls, and then we will discover that we can reuse the same code for interrupts and exceptions. cpu->ts.esp0 %gs, and the general-purpose registers (2905-2910). The result of this eort is that the kernel stack now contains a struct trapframe (0602) containing the processor registers at the time of the trap (see Figure 2-2). The processor pushes %ss, %esp, %eflags, %cs, and %eip. The processor or the trap vector pushes an error number, and alltraps pushes the rest. The trap frame contains all the information necessary to restore the user mode processor registers when the kernel returns to the current process, so that the processor can continue exactly as it was when the trap started. Recall from Chapter 1, that userinit build a trapframe by hand to achieve this goal (see Figure 1-3). In the case of the rst system call, the saved %eip is the address of the instruction right after the int instruction. %cs is the user code segment selector. %eflags is the content of the eags register at the point of executing the int instruction. As part of saving the general-purpose registers, alltraps also saves %eax, which contains the system call number for the kernel to inspect later. Now that the user mode processor registers are saved, alltraps can nishing setting up the processor to run kernel C code. The processor set the selectors %cs and %ss before entering the handler; alltraps sets %ds and %es (2913-2915). It sets %fs and %gs to point at the SEG_KCPU per-CPU data segment (2916-2918). Once the segments are set properly, alltraps can call the C trap handler trap. It pushes %esp, which points at the trap frame it just constructed, onto the stack as an argument to trap (2921). Then it calls trap (2922). After trap returns, alltraps popsDRAFT as of September 7, 2011 trapno ds es fs gs eax ecx edx ebx oesp ebp esi edi (empty) 35 the argument o the stack by adding to the stack pointer (2923) and then starts executing the code at label trapret. We traced through this code in Chapter 1 when the rst user process ran it to exit to user space. The same sequence happens here: popping through the trap frame restores the user mode registers and then iret jumps back into user space. The discussion so far has talked about traps occurring in user mode, but traps can also happen while the kernel is executing. In that case the hardware does not switch stacks or save the stack pointer or stack segment selector; otherwise the same steps occur as in traps from user mode, and the same xv6 trap handling code executes. When iret later restores a kernel mode %cs, the processor continues executing in kernel mode. 36 nism left: nding the system call arguments. The helper functions argint and argptr, argstr retrieve the nth system call argument, as either an integer, pointer, or a string. argint uses the user-space %esp register to locate the nth argument: %esp points at the return address for the system call stub. The arguments are right above it, at %esp+4. Then the nth argument is at %esp+4+4*n. argint calls fetchint to read the value at that address from user memory and write it to *ip. fetchint can simply cast the address to a pointer, because the user and the kernel share the same page table, but the kernel must verify that the pointer by the user is indeed a pointer in the user part of the address space. The kernel has set up the page-table hardware to make sure that the process cannot access memory outside its local private memory: if a user program tries to read or write memory at an address of p->sz or above, the processor will cause a segmentation trap, and trap will kill the process, as we saw above. Now though, the kernel is running and it can derefence any address that the user might have passed, so it must check explicitly that the address is below p->sz argptr is similar in purpose to argint: it interprets the nth system call argument. argptr calls argint to fetch the argument as an integer and then checks if the integer as a user pointer is indeed in the user part of the address space. Note that two checks occur during a call to code argptr . First, the user stack pointer is checked during the fetching of the argument. Then the argument, itself a user pointer, is checked. argstr is the nal member of the system call argument trio. It interprets the nth argument as a pointer. It ensures that the pointer points at a NUL-terminated string and that the complete string is located below the end of the user part of the address space. The system call implementations (for example, sysproc.c and sysle.c) are typically wrappers: they decode the arguments using argint, argptr, and argstr and then call the real implementations. In chapter 1, sys_exec uses these functions to get at its arguments. Code: InterruptsDevices on the motherboard can generate interrupts, and xv6 must setup the hardware to handle these interrupts. Without device support xv6 wouldnt be usable; a user couldnt type on the keyboard, a le system couldnt store data on disk, etc. Fortunately, adding interrupts and support for simple devices doesnt require much additional complexity. As we will see, interrupts can use the same code as for systems calls and exceptions. Interrupts are similar to system calls, except devices generate them at any time. There is hardware on the motherboard to signal the CPU when a device needs attention (e.g., the user has typed a character on the keyboard). We must program the device to generate an interrupt, and arrange that a CPU receives the interrupt. Lets look at the timer device and timer interrupts. We would like the timer hardware to generate an interrupt, say, 100 times per second so that the kernel can track the passage of time and so the kernel can time-slice among multiple running processes. The choice of 100 times per second allows for decent interactive performance 37 while not swamping the processor with handling interrupts. Like the x86 processor itself, PC motherboards have evolved, and the way interrupts are provided has evolved too. The early boards had a simple programmable interrupt controler (called the PIC), and you can nd the code to manage it in picirq.c. With the advent of multiprocessor PC boards, a new way of handling interrupts was needed, because each CPU needs an interrupt controller to handle interrupts send to it, and there must be a method for routing interrupts to processors. This way consists of two parts: a part that is in the I/O system (the IO APIC, ioapic.c), and a part that is attached to each processor (the local APIC, lapic.c). Xv6 is designed for a board with multiple processors, and each processor must be programmed to receive interrupts. To also work correctly on uniprocessors, Xv6 programs the programmable interrupt controler (PIC) (6732). Each PIC can handle a maximum of 8 interrupts (i.e., devices) and multiplex them on the interrupt pin of the processor. To allow for more than 8 devices, PICs can be cascaded and typically boards have at least two. Using inb and outb instructions Xv6 programs the master to generate IRQ 0 through 7 and the slave to generate IRQ 8 through 16. Initially xv6 programs the PIC to mask all interrupts. The code in timer.c sets timer 1 and enables the timer interrupt on the PIC (7374). This description omits some of the details of programming the PIC. These details of the PIC (and the IOAPIC and LAPIC) are not important to this text but the interested reader can consult the manuals for each device, which are referenced in the source les. On multiprocessors, xv6 must program the IOAPIC, and the LAPIC on each processor. The IO APIC has a table and the processor can program entries in the table through memory-mapped I/O, instead of using inb and outb instructions. During initialization, xv6 programs to map interrupt 0 to IRQ 0, and so on, but disables them all. Specic devices enable particular interrupts and say to which processor the interrupt should be routed. For example, xv6 routes keyboard interrupts to processor 0 (7316). Xv6 routes disk interrupts to the highest numbered processor on the system, as we will see below. The timer chip is inside the LAPIC, so that each processor can receive timer interrupts independently. Xv6 sets it up in lapicinit (6451). The key line is the one that programs the timer (6464). This line tells the LAPIC to periodically generate an interrupt at IRQ_TIMER, which is IRQ 0. Line (6493) enables interrupts on a CPUs LAPIC, which will cause it to deliver interrupts to the local processor. A processor can control if it wants to receive interrupts through the IF ag in the eags register. The instruction cli disables interrupts on the processor by clearing IF, and sti enables interrupts on a processor. Xv6 disables interrupts during booting of the main cpu (8212) and the other processors (1126). The scheduler on each processor enables interrupts (2414). To control that certain code fragments are not interrupted, xv6 disables interrupts during these code fragments (e.g., see switchuvm (1769)). The timer interrupts through vector 32 (which xv6 chose to handle IRQ 0), which xv6 setup in idtinit (1265). The only dierence between vector 32 and vector 64 (the one for system calls) is that vector 32 is an interrupt gate instead of a trap gate. Inter- 38 rupt gates clears IF, so that the interrupted processor doesnt receive interrupts while it is handling the current interrupt. From here on until trap, interrupts follow the same code path as system calls and exceptions, building up a trap frame. Trap when its called for a time interrupt, does just two things: increment the ticks variable (2963), and call wakeup. The latter, as we will see in Chapter 4, may cause the interrupt to return in a dierent process. DriversA driver is the piece of code in an operating system that manage a particular device: it provides interrupt handlers for a device, causes a device to perform operations, causes a device to generate interrupts, etc. Driver code can be tricky to write because a driver executes concurrently with the device that it manages. In addition, the driver must understand the devices interface (e.g., which I/O ports do what), and that interface can be complex and poorly documented. The disk driver provides a good example in xv6. The disk driver copies data from and back to the disk. Disk hardware traditionally presents the data on the disk as a numbered sequence of 512-byte blocks (also called sectors): sector 0 is the rst 512 bytes, sector 1 is the next, and so on. To represent disk sectors an operating system has a structure that corresponds to one sector. The data stored in this structure is often out of sync with the disk: it might have not yet been read in from disk (the disk is working on it but hasnt returned the sectors content yet), or it might have been updated but not yet written out. The driver must ensure that the rest of xv6 doesnt get confused when the structure is out of sync with the disk. 39 Next, ideinit probes the disk hardware. It begins by calling idewait (3708) to wait for the disk to be able to accept commands. A PC motherboard presents the status bits of the disk hardware on I/O port 0x1f7. Idewait (3683) polls the status bits until the busy bit (IDE_BSY) is clear and the ready bit (IDE_DRDY) is set. Now that the disk controller is ready, ideinit can check how many disks are present. It assumes that disk 0 is present, because the boot loader and the kernel were both loaded from disk 0, but it must check for disk 1. It writes to I/O port 0x1f6 to select disk 1 and then waits a while for the status bit to show that the disk is ready (3710-3717). If not, ideinit assumes the disk is absent. After ideinit, the disk is not used again until the buer cache calls iderw, which updates a locked buer as indicated by the ags. If B_DIRTY is set, iderw writes the buer to the disk; if B_VALID is not set, iderw reads the buer from the disk. Disk accesses typically take milliseconds, a long time for a processor. The boot loader issues disk read commands and reads the status bits repeatedly until the data is ready. This polling or busy waiting is ne in a boot loader, which has nothing better to do. In an operating system, however, it is more ecient to let another process run on the CPU and arrange to receive an interrupt when the disk operation has completed. Iderw takes this latter approach, keeping the list of pending disk requests in a queue and using interrupts to nd out when each request has nished. Although iderw maintains a queue of requests, the simple IDE disk controller can only handle one operation at a time. The disk driver maintains the invariant that it has sent the buer at the front of the queue to the disk hardware; the others are simply waiting their turn. Iderw (3804) adds the buer b to the end of the queue (3817-3821). If the buer is at the front of the queue, iderw must send it to the disk hardware by calling idestart (3774-3776); otherwise the buer will be started once the buers ahead of it are taken care of. Idestart (3725) issues either a read or a write for the buers device and sector, according to the ags. If the operation is a write, idestart must supply the data now (3739) and the interrupt will signal that the data has been written to disk. If the operation is a read, the interrupt will signal that the data is ready, and the handler will read it. Note that iderw has detailed knowledge about the IDE device, and writes the right values at the right ports. If any of these outb statements is wrong, the IDE will do something dierently than what we want. Getting these details right is one reason why writing device drivers is challenging. Having added the request to the queue and started it if necessary, iderw must wait for the result. As discussed above, polling does not make ecient use of the CPU. Instead, iderw sleeps, waiting for the interrupt handler to record in the buers ags that the operation is done (3829-3830). While this process is sleeping, xv6 will schedule other processes to keep the CPU busy. Eventually, the disk will nish its operation and trigger an interrupt. trap will call ideintr to handle it (3024). Ideintr (3752) consults the rst buer in the queue to nd out which operation was happening. If the buer was being read and the disk controller has data waiting, ideintr reads the data into the buer with insl (3765- 40 3767). Now the buer is ready: ideintr sets B_VALID, clears B_DIRTY, and wakes up any process sleeping on the buer (3769-3772). Finally, ideintr must pass the next waiting buer to the disk (3774-3776). Real worldSupporting all the devices on a PC motherboard in its full glory is much work, because there are many devices, the devices have many features, and the protocol between device and driver can be complex. In many operating systems, the drivers together account for more code in the operating system than the core kernel. Actual device drivers are far more complex than the disk driver in this chapter, but the basic ideas are the same: typically devices are slower than CPU, so the hardware uses interrupts to notify the operating system of status changes. Modern disk controllers typically accept multiple outstanding disk requests at a time and even reorder them to make most ecient use of the disk arm. When disks were simpler, operating system often reordered the request queue themselves. Many operating systems have drivers for solid-state disks because they provide much faster access to data. But, although a solid-state works very dierently from a traditional mechanical disk, both devices provide block-based interfaces and reading/writing blocks on a solid-state disk is still more expensive than reading/writing RAM. Other hardware is surprisingly similar to disks: network device buers hold packets, audio device buers hold sound samples, graphics card buers hold video data and command sequences. High-bandwidth devicesdisks, graphics cards, and network cardsoften use direct memory access (DMA) instead of the explicit I/O (insl, outsl) in this driver. DMA allows the disk or other controllers direct access to physical memory. The driver gives the device the physical address of the buers data eld and the device copies directly to or from main memory, interrupting once the copy is complete. Using DMA means that the CPU is not involved at all in the transfer, which can be more ecient and is less taxing for the CPUs memory caches. Most of the devices in this chapter used I/O instructions to program them, which reects the older nature of these devices. All modern devices are programmed using memory-mapped I/O. Some drivers dynamically switch between polling and interrupts, because using interrupts can be expensive, but using polling can introduce delay until the driver processes an event. For example, for a network driver that receives a burst of packets, may switch from interrupts to polling since it knows that more packets must be processed and it is less expensive to process them using polling. Once no more packets need to be processed, the driver may switch back to interrupts, so that it will be alerted immediately when a new packet arrives. The IDE driver routed interrupts statically to a particular processor. Some drivers have a sophisticated algorithm for routing interrupts to processor so that the load of processing packets is well balanced but good locality is achieved too. For example, a network driver might arrange to deliver interrupts for packets of one network connection to the processor that is managing that connection, while interrupts for packets of 41 another connection are delivered to another processor. This routing can get quite sophisticated; for example, if some network connections are short lived while others are long lived and the operating system wants to keep all processors busy to achieve high throughput. If user process reads a le, the data for that le is copied twice. First, it is copied from the disk to kernel memory by the driver, and then later it is copied from kernel space to user space by the read system call. If the user process, then sends the data on the network, then the data is copied again twice: once from user space to kernel space and from kernel space to the network device. To support applications for which low latency is important (e.g., a Web serving static Web pages), operating systems use special code paths to avoid these many copies. As one example, in real-world operating systems, buers typically match the hardware page size, so that read-only copies can be mapped into a processs address space using the paging hardware, without any copying. Exercises1. Set a breakpoint at the rst instruction of syscall() to catch the very rst system call (e.g., br syscall). What values are on the stack at this point? Explain the output of x/37x $esp at that breakpoint with each value labeled as to what it is (e.g., saved %ebp for trap, trapframe.eip, scratch space, etc.). 2. Add a new system call 3. Add a network driver 42 Chapter 3 LockingXv6 runs on multiprocessors, computers with multiple CPUs executing code independently. These multiple CPUs operate on a single physical address space and share data structures; xv6 must introduce a coordination mechanism to keep them from interfering with each other. Even on a uniprocessor, xv6 must use some mechanism to keep interrupt handlers from interfering with non-interrupt code. Xv6 uses the same low-level concept for both: a lock. A lock provides mutual exclusion, ensuring that only one CPU at a time can hold the lock. If xv6 only accesses a data structure while holding a particular lock, then xv6 can be sure that only one CPU at a time is accessing the data structure. In this situation, we say that the lock protects the data structure. The rest of this chapters why xv6 needs locks, how xv6 implements them, and how it uses them. Race conditionsAs an example on why we need locks, consider several processors sharing a single disk, such as the IDE disk in xv6. The disk driver maintains a linked list of the outstanding disk requests (3671) and processors may add new requests to the list concurrently (3804). If there were no concurrent requests, you might implement the linked list as follows:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 struct list { int data; struct list *next; }; struct list *list = 0; void insert(int data) { struct list *l; l = malloc(sizeof *l); l->data = data; l->next = list; list = l; } Proving this implementation correct is a typical exercise in a data structures and algorithms class. Even though this implementation can be proved correct, it isnt, at least not on a multiprocessor. If two dierent CPUs execute insert at the same time, it could happen that both execute line 15 before either executes 16 (see Figure 3-1). If 43 CPU 1 Memory l->next l->next list list CPU2 15 16 Time this happens, there will now be two list nodes with next set to the former value of list. When the two assignments to list happen at line 16, the second one will overwrite the rst; the node involved in the rst assignment will be lost. This kind of problem is called a race condition. The problem with races is that they depend on the exact timing of the two CPUs involved and how their memory operations are ordered by the memory system, and are consequently dicult to reproduce. For example, adding print statements while debugging insert might change the timing of the execution enough to make the race disappear. The typical way to avoid races is to use a lock. Locks ensure mutual exclusion, so that only one CPU can execute insert at a time; this makes the scenario above impossible. The correctly locked version of the above code adds just a few lines (not numbered):6 7 8 9 10 11 12 13 14 15 16 17 } struct list *list = 0; struct lock listlock; void insert(int data) { struct list *l; acquire(&listlock); l = malloc(sizeof *l); l->data = data; l->next = list; list = l; release(&listlock); When we say that a lock protects data, we really mean that the lock protects some collection of invariants that apply to the data. Invariants are properties of data structures that are maintained across operations. Typically, an operations correct behavior 44 depends on the invariants being true when the operation begins. The operation may temporarily violate the invariants but must reestablish them before nishing. For example, in the linked list case, the invariant is that list points at the rst node in the list and that each nodes next eld points at the next node. The implementation of insert vioilates this invariant temporarily: line 13 creates a new list element l with the intent that l be the rst node in the list, but ls next pointer does not point at the next node in the list yet (reestablished at line 15) and list does not point at l yet (reestablished at line 16). The race condition we examined above happened because a second CPU executed code that depended on the list invariants while they were (temporarily) violated. Proper use of a lock ensures that only one CPU at a time can operate on the data structure, so that no CPU will execute a data structure operation when the data structures invariants do not hold. Code: LocksXv6s represents a lock as a struct spinlock (1401). The critical eld in the structure is locked, a word that is zero when the lock is available and non-zero when it is held. Logically, xv6 should acquire a lock by executing code like21 22 23 24 25 26 27 28 29 30 void acquire(struct spinlock *lk) { for(;;) { if(!lk->locked) { lk->locked = 1; break; } } } Unfortunately, this implementation does not guarantee mutual exclusion on a modern multiprocessor. It could happen that two (or more) CPUs simultaneously reach line 25, see that lk->locked is zero, and then both grab the lock by executing lines 26 and 27. At this point, two dierent CPUs hold the lock, which violates the mutual exclusion property. Rather than helping us avoid race conditions, this implementation of acquire has its own race condition. The problem here is that lines 25 and 26 executed as separate actions. In order for the routine above to be correct, lines 25 and 26 must execute in one atomic (i.e., indivisible) step. To execute those two lines atomically, xv6 relies on a special 386 hardware instruction, xchg (0569). In one atomic operation, xchg swaps a word in memory with the contents of a register. The function acquire (1474) repeats this xchg instruction in a loop; each iteration reads lk->locked and atomically sets it to 1 (1483). If the lock is held, lk->locked will already be 1, so the xchg returns 1 and the loop continues. If the xchg returns 0, however, acquire has successfully acquired the locklocked was 0 and is now 1so the loop can stop. Once the lock is acquired, acquire records, for debugging, the CPU and stack trace that acquired the lock. When a process acquires a lock and forget to release it, this information can help to identify the culprit. These debugging elds are protected by the lock and must only be edited while holding theDRAFT as of September 7, 2011 45 lock. The function release (1502) is the opposite of acquire: it clears the debugging elds and then releases the lock. 46 structures, typically all of the structures need to be protected by a single lock to ensure the invariant is maintained. The rules above say when locks are necessary but say nothing about when locks are unnecessary, and it is important for eciency not to lock too much, because locks reduce parallelism. If eciency wasnt important, then one could use a uniprocessor computer and no worry at all about locks. For protecting kernel data structures, it would suce to create a single lock that must be acquired on entering the kernel and released on exiting the kernel. Many uniprocessor operating systems have been converted to run on multiprocessors using this approach, sometimes called a giant kernel lock, but the approach sacrices true concurrency: only one CPU can execute in the kernel at a time. If the kernel does any heavy computation, it would be more ecient to use a larger set of more ne-grained locks, so that the kernel could execute on multiple CPUs simultaneously. Ultimately, the choice of lock granularity is an exercise in parallel programming. Xv6 uses a few coarse data-structure specic locks; for example, xv6 uses a single lock protecting the process table and its invariants, which are described in Chapter 4. A more ne-grained approach would be to have a lock per entry in the process table so that threads working on dierent entries in the process table can proceed in parallel. However, it complicates operations that have invariants over the whole process table, since they might have to take out several locks. Hopefully, the examples of xv6 will help convey how to use locks. Lock orderingIf a code path through the kernel must take out several locks, it is important that all code paths acquire the locks in the same order. If they dont, there is a risk of deadlock. Lets functions specication: le system there are a number of examples of chains of two because the le system must, for example, acquire a lock on a directory and the lock on a le in that directory to unlink a le from its parent directory correctly. Xv6 always acquires the locks in the order rst parent directory and then the le. 47 Interrupt handlersXonly iderw can release it, and iderw will not continue running until ideintr returns disable dierent rThisDRAFT as of September 7, 2011 48 other and start instruction B before A so that it will be completed when the processor completes A. Concurrency, however, may expose this reordering to software, which lead to incorrect behavior. For example, one might wonder what happens if release just assigned 0 to lk>locked, instead of using xchg. The answer to this question is unclear, because dierent generations of x86 processors make dierent guarantees about memory ordering. If lk->locked=0, were allowed to be re-ordered say after popcli, than acquire might break, because to another thread interrupts would be enabled before a lock is released. To avoid relying on unclear processor specications about memory ordering, xv6 takes no risk and uses xchg, which processors must guarantee not to reorder. Real worldConcurrency primitives and parallel programming are active areas of of research, because programming with locks is still challenging. It is best to use locks as the base for higher-level constructs like synchronized queues, although xv6 does not do this. If you program with locks, it is wise to use a tool that attempts to identify race conditions, because it is easy to miss an invariant that requires a lock. User-level programs need locks too, but in xv6 applications have one thread of execution and processes dont share memory, and so there is no need for locks in xv6 applications. It is possible to implement locks without atomic instructions, but it is expensive, and most operating systems use atomic instructions. Atomic instructions are not free either when a lock is contented. If one processor has a lock cached in its local cache, and another processor must acquire the lock, then the atomic instruction to update the line that holds the lock must move the line from the one processors cache to the other processors cache, and perhaps invalidate any other copies of the cache line. Fetching a cache line from another processors cache can be orders of magnitude more expensive than fetching a line from a local cache. To avoid the expenses associated with locks, many operating systems use lock-free data structures and algorithms, and try to avoid atomic operations in those algorithms. For example, it is possible to implemented a link list like the one in the beginning of the chapter that requires no locks during list searches, and one atomic instruction to insert an item in a list. Exercises1. get rid o the xchg in acquire. explain what happens when you run xv6? 2. move the acquire in iderw to before sleep. is there a race? why dont you observe it when booting xv6 and run stressfs? increase critical section with a dummy loop; what do you see now? explain. 3. do posted homework question.DRAFT as of September 7, 2011 49 4. Setting a bit in a buers flags is not an atomic operation: the processor makes a copy of flags in a register, edits the register, and writes it back. Thus it is important that two processes are not writing to flags at the same time. xv6 edits the B_BUSY bit only while holding buflock but edits the B_VALID and B_WRITE ags without holding any locks. Why is this safe? 50 Chapter 4 SchedulingAny operating system is likely to run with more processes than the computer has processors, and so some plan is needed to time share the processors between the processes. An ideal plan is transparent to user processes. A common approach is to provide each process with the illusion that it has its own virtual processor, and have the operating system multiplex multiple virtual processors on a single physical processor. This chapter how xv6 multiplexes a processor among several processes. MultiplexingXv6 adopts this multiplexing approach. When a process is waiting for disk request, xv6 puts it to sleep, and schedules another process to run. Furthermore, xv6 using timer interrupts to force a process to stop running on a processor after a xedamount of time (100 msec), so that it can schedule another process on the processor. This multiplexing creates the illusion that each process has its own CPU, just as xv6 used the memory allocator and hardware page tables to create the illusion that each process has its own memory. Implementing multiplexing has a few challenges. First, how to switch from one process to another? Xv6 uses the standard mechanism of context switching; although the idea is simple, the code to implement is typically among the most opaque code in an operating system. Second, how to do context switching transparently? Xv6 uses the standard technique of using the timer interrupt handler to drive context switches. Third, many CPUs may be switching among processes concurrently, and a locking plan is necessary to avoid races. Fourth, when a process has exited its memory and other resources must be freed, but it cannot do all of this itself because (for example) it cant free its own kernel stack while still using it. Xv6 tries to solve these problems as simply as possible, but nevertheless the resulting code is tricky. xv6 must provide ways for processes to coordinate among themselves. For example, a parent process may need to wait for one of its children to exit, or a process reading on a pipe may need to wait for some other process to write the pipe. Rather than make the waiting process waste CPU by repeatedly checking whether the desired event has happened, xv6 allows a process to give up the CPU and sleep waiting for an event, and allows another process to wake the rst process up. Care is needed to avoid races that result in the loss of event notications. As an example of these problems and their solution, this chapter examines the implementation of pipes. 51 user space shell save swtch kernel space kstack shell swtch kstack scheduler kstack cat restore Kernel Figure 4-1. Switching from one user process to another. In this example, xv6 runs with one CPU (and thus one scheduler thread). context switches at a low level: from a processs kernel thread to the current CPUs scheduler thread, and from the scheduler thread to a processs kernel thread. xv6 never directly switches from one user-space process to another; this happens by way of a user-kernel transition (system call or interrupt), a context switch to the scheduler, a context switch to a new processs kernel thread, and a trap return. In this section well example the mechanics of switching between a kernel thread and a scheduler thread. Every xv6 process has its own kernel stack and register set, as we saw in Chapter 1. Each CPU has a separate scheduler thread for use when it is executing the scheduler rather than any processs kernel thread. Switching from one thread to another involves saving the old threads CPU registers, and restoring previously-saved registers of the new thread; the fact that %esp and %eip are saved and restored means that the CPU will switch stacks and switch what code it is executing. swtch doesnt directly know about threads; it just saves and restores register sets, called contexts. When it is time for the process to give up the CPU, the processs kernel thread will call swtch to save its own context and return to the scheduler context. Each context is represented by a struct context*, a pointer to a structure stored on the kernel stack involved. Swtch takes two arguments: struct context **old and struct context *new. It pushes the current CPU register onto the stack and saves the stack pointer in *old. Then swtch copies new to %esp, pops previously saved registers, and returns. Instead of following the scheduler into swtch, lets instead follow our user process back in. We saw in Chapter 2 that one possibility at the end of each interrupt is that trap calls yield. Yield in turn calls sched, which calls swtch to save the current context in proc->context and switch to the scheduler context previously saved in cpu->scheduler (2466). Swtch (2652) starts by loading its arguments o the stack into the registers %eax and %edx (2659-2660); swtch must do this before it changes the stack pointer and can no longer access the arguments via %esp. Then swtch pushes the register state, creating a context structure on the current stack. Only the callee-save registers need to be saved; the convention on the x86 is that these are %ebp, %ebx, %esi, %ebp, and %esp. 52 Swtch pushes the rst four explicitly (2663-2666); it saves the last implicitly as the struct context* written to *old (2669). There is one more important register: the program counter %eip was saved by the call instruction that invoked swtch and is on the stack just above %ebp. Having saved the old context, swtch is ready to restore the new one. It moves the pointer to the new context into the stack pointer (2670). The new stack has the same form as the old one that swtch just leftthe new stack was the old one in a previous call to swtchso swtch can invert the sequence to restore the new context. It pops the values for %edi, %esi, %ebx, and %ebp and then returns (2673-2677). Because swtch has changed the stack pointer, the values restored and the instruction address returned to are the ones from the new context. In our example, sched called swtch to switch to cpu->scheduler, the per-CPU scheduler context. That context had been saved by schedulers call to swtch (2428). When the swtch we have been tracing returns, it returns not to sched but to scheduler, and its stack pointer points at the current CPUs scheduler stack, not initprocs kernel stack. Code: SchedulingThe last section looked at the low-level details of swtch; now lets take swtch as a given and examine the conventions involved in switching from process to scheduler and back to process. A process that wants to give up the CPU must acquire the process table lock ptable.lock, release any other locks it is holding, update its own state (proc->state), and then call sched. Yield (2472) follows this convention, as do sleep and exit, which we will examine later. Sched double-checks those conditions (24572462) and then an implication of those conditions: since a lock is held, the CPU should be running with interrupts disabled. Finally, sched calls swtch to save the current context in proc->context and switch to the scheduler context in cpu->scheduler. Swtch returns on the schedulers stack as though schedulers swtch had returned (2428). The scheduler continues the for loop, nds a process to run, switches to it, and the cycle repeats. We just saw that xv6 holds ptable.lock across calls to swtch: the caller of swtch must already hold the lock, and control of the lock passes to the switched-to code. This convention is unusual with locks; the typical convention is the thread that acquires a lock is also responsible of releasing the lock, which makes it easier to reason about correctness. For context switching is necessary to break the typical convention because ptable.lock protects invariants on the processs state and context elds that are not true while executing in swtch. One example of a problem that could arise if ptable.lock were not held during swtch: a dierent CPU might decide to run the process after yield had set its state to RUNNABLE, but before swtch caused it to stop using its own kernel stack. The result would be two CPUs running on the same stack, which cannot be right. A kernel thread always gives up its processor in sched and always switches to the same location in the scheduler, which (almost) always switches to a process in sched. Thus, if one were to print out the line numbers where xv6 switches threads, one would observe the following simple pattern: (2428), (2466), (2428), (2466), and so on. The proce53 dures in which this stylized switching between two threads happens are sometimes referred to as coroutines; in this example, sched and scheduler are co-routines of each other. There is one case when the schedulers swtch to a new process does not end up in sched. We saw this case in Chapter 1: when a new process is rst scheduled, it begins at forkret (2483). Forkret exists only to honor this convention by releasing the ptable.lock; otherwise, the new process could start at trapret. Scheduler (2408) runs a simple loop: nd a process to run, run it until it stops, repeat. scheduler holds ptable.lock for most of its actions, but releases the lock (and explicitly enables interrupts) once in each iteration of its outer loop. This is important for the special case in which this CPU is idle (can nd no RUNNABLE process). If an idling scheduler looped with the lock continuously held, no other CPU that was running a process could ever perform a context switch or any process-related system call, and in particular could never mark a process as RUNNABLE so as to break the idling CPU out of its scheduling loop. The reason to enable interrupts periodically on an idling CPU is that there might be no RUNNABLE process because processes (e.g., the shell) are waiting for I/O; if the scheduler left interrupts disabled all the time, the I/O would never arrive. The scheduler loops over the process table looking for a runnable process, one that has p->state == RUNNABLE. Once it nds a process, it sets the per-CPU current process variable proc, switches to the processs page table with switchuvm, marks the process as RUNNING, and then calls swtch to start running it (2422-2428). One way to think about the structure of the scheduling code is that it arranges to enforce a set of invariants about each process, and holds ptable.lock whenever those invariants are not true. One invariant is that if a process is RUNNING, things must be set up so that a timer interrupts yield can correctly switch away from the process; this means that the CPU registers must hold the processs register values (i.e. they arent actually in a context), %cr3 must refer to the processs pagetable, %esp must refer to the processs kernel stack so that swtch can push registers correctly, and proc must refer to the processs proc[] slot. Another invariant is that if a process is RUNNABLE, things must be set up so that an idle CPUs scheduler can run it; this means that p->context must hold the processs kernel thread variables, that no CPU is executing on the processs kernel stack, that no CPUs %cr3 refers to the processs page table, and that no CPUs proc refers to the process. Maintaining the above invariants is the reason why xv6 acquires ptable.lock in one thread (often in yield) and releases the lock in a dierent thread (the scheduler thread or another next kernel thread). Once the code has started to modify a running processs state to make it RUNNABLE, it must hold the lock until it has nished restoring the invariants: the earliest correct release point is after scheduler stops using the processs page table and clears proc. Similarly, once scheduler starts to convert a runnable process to RUNNING, the lock cannot be released until the kernel thread is completely running (after the swtch, e.g. in yield). ptable.lock protects other things as well: allocation of process IDs and free process table slots, the interplay between exit and wait, the machinery to avoid lost wakeups (see next section), and probably other things too. It might be worth thinking 54 about whether the dierent functions of ptable.lock could be split up, certainly for clarity and perhaps for performance. Send loops until the queue is empty (ptr == 0) and then puts the pointer p in the queue. Recv loops until the queue is non-empty and takes the pointer out. When run in dierent processes, send and recv both edit q->ptr, but send only writes to the pointer when it is zero and recv only writes to the pointer when it is nonzero, so they do not step on each other. The implementation above may be correct, but it is expensive. If the sender sends rarely, the receiver will spend most of its time spinning in the while loop hoping for a pointer. The receivers CPU could nd more productive work if there were aDRAFT as of September 7, 2011 55 recv 215 216 sleep q->ptr q->ptr send 206 207 wakeup way for the receiver to be notied when the send had delivered a pointer. Lets imagine a pair of calls, sleep and wakeup, that work as follows. Sleep(chan) sleeps on the arbitrary value chan, called the wait channel. Sleep puts the calling process to sleep, releasing the CPU for other work. Wakeup(chan) wakes all processes sleeping on chan (if any), causing their sleep calls to return. If no processes are waiting on chan, wakeup does nothing. We can change the queue implementation to use sleep and wakeup:201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 void* send(struct q *q, void *p) { while(q->ptr != 0) ; q->ptr = p; wakeup(q); /* wake recv */ } void* recv(struct q *q) { void *p; while((p = q->ptr) == 0) sleep(q); q->ptr = 0; return p; } Recv now gives up the CPU instead of spinning, which is nice. However, it turns out not to be straightforward to design sleep and wakeup with this interface without suering from what is known as the lost wake up problem (see Figure 4-2). Suppose that recv nds that q->ptr == 0 on line 215 and decides to call sleep. Before recv 56 can sleep, send runs on another CPU: it changes q->ptr to be nonzero and calls wakeup, which nds no processes sleeping and thus does nothing. Now recv continues executing at line 216: it calls sleep and goes to sleep. This causes a problem: recv is asleep waiting for a pointer that has already arrived. The next send will sleep waiting for recv to consume the pointer in the queue, at which point the system will be deadlocked. The root of this problem is that the invariant that recv only sleeps when q->ptr == 0 is violated by send running at just the wrong moment. To protect this invariant, we introduce a lock, which sleep releases only after the calling process is asleep; this avoids the missed wakeup in the example above. Once the calling process is awake again sleep reacquires the lock before returning. We would like to be able to have the following code:300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 struct q { struct spinlock lock; void *ptr; }; void* send(struct q *q, void *p) { acquire(&q->lock); while(q->ptr != 0) ; q->ptr = p; wakeup(q); release(&q->lock); } void* recv(struct q *q) { void *p; acquire(&q->lock); while((p = q->ptr) == 0) sleep(q, &q->lock); q->ptr = 0; release(&q->lock); return p; } The fact that recv holds q->lock prevents send from trying to wake it up between recvs check of q->ptr and its call to sleep. Of course, the receiving process had better not hold q->lock while it is sleeping, since that would prevent the sender from waking it up, and lead to deadlock. So what we want is for sleep to atomically release q->lock and put the receiving process to sleep. A complete sender/receiver implementation would also sleep in send when waiting for a receiver to consume the value from a previous send. 57 58 the waiting, such as a disk buer. No harm is done if two uses of sleep/wakeup accidentally choose the same channel: they will see spurious wakeups, but looping as described above will tolerate this problem. Much of the charm of sleep/wakeup is that it is both lightweight (no need to create special data structures to act as sleep channels) and provides a layer of indirection (callers need not know what specic process they are interacting with). Code: PipesThe simple queue we used earlier in this chapter was a toy, but xv6 contains two real queues that uses sleep and wakeup to synchronize readers and writers. One is in the IDE driver: processes add a disk requests to a queue and then calls sleep. The interrupt handler uses wakeup to alert the process that its request has completed. An more complex example is the implementation of pipes. We saw the interface for pipes in Chapter 0: bytes written to one end of a pipe are copied in an in-kernel buer and then can be read out of the other end of the pipe. Future chapters will examine the le system support surrounding pipes, but lets look now at the implementations of pipewrite and piperead. Each pipe is represented by a struct pipe, which contains a lock and a data buer. The elds nread and nwrite count the number of bytes read from and written to the buer. The buer wraps around: the next byte written after buf[PIPESIZE-1] is buf[0], but the counts do not wrap. This convention lets the implementation distinguish a full buer (nwrite == nread+PIPESIZE) from an empty buer nwrite == nread), but it means that indexing into the buer must use buf[nread % PIPESIZE] instead of just buf[nread] (and similarly for nwrite). Lets suppose that calls to piperead and pipewrite happen simultaneously on two dierent CPUs. Pipewrite (5880) begins by acquiring the pipes lock, which protects the counts, the data, and their associated invariants. Piperead (5901) then tries to acquire the lock too, but cannot. It spins in acquire (1474) waiting for the lock. While piperead waits, pipewrite loops over the bytes being writtenaddr[0], addr[1], ..., addr[n-1] adding each to the pipe in turn (5894). During this loop, it could happen that the buer lls (5886). In this case, pipewrite calls wakeup to alert any sleeping readers to the fact that there is data waiting in the buer and then sleeps on &p->nwrite to wait for a reader to take some bytes out of the buer. Sleep releases p->lock as part of putting pipewrites process to sleep. Now that p->lock is available, piperead manages to acquire it and start running in earnest: it nds that p->nread != p->nwrite (5906) (pipewrite went to sleep because p->nwrite == p->nread+PIPESIZE (5886)) so it falls through to the for loop, copies data out of the pipe (5913-5917), and increments nread by the number of bytes copied. That many bytes are now available for writing, so piperead calls wakeup (5918) to wake any sleeping writers before it returns to its caller. Wakeup nds a process sleeping on &p->nwrite, the process that was running pipewrite but stopped when the buer lled. It marks that process as RUNNABLE. The pipe code uses separate sleep channels for reader and writer ( p->nread and p->nwrite); this might make the system more ecient in the unlikely event that there 59 are lots of readers and writers waiting for the same pipe. The pipe code sleeps inside a loop checking the sleep condition; if there are multiple readers or writers, all but the rst process to wake up will see the condition is still false and sleep again. Real worldThe xv6 scheduler implements a simple scheduling policy, which runs each process in turn. This policy is called round robin. Real operating systems implement more sophisticated policies that, for example, allow processes to have priorities. The idea is that a runnable high-priority process will be preferred by the scheduler over aDRAFT as of September 7, 2011 60 runnable low-priority thread. These policies can become complex quickly because there are often competing goals: for example, the operating might also want to guarantee fairness and high-throughput. In addition, complex policies may lead to unintended interactions such as priority inversion and convoys. Priority inversion can happen when a low-priority and high-priority process share a lock, which when acquired by the low-priority process can cause the high-priority process to not run. A long convoy can form when many high-priority processes are waiting for a low-priority process that acquires a shared lock; once a convoy has formed they can persist for long period of time. To avoid these kinds of problems additional mechanisms are necessary in sophisticated schedulers. Sleep and wakeup are a simple and eective synchronization method, but there are many others. The rst challenge in all of them is to avoid the missed wakeups problem we saw at the beginning of the chapter. The original Unix kernels sleep simply disabled interrupts, which suced because Unix ran on a single-CPU system. Because xv6 runs on multiprocessors, it adds an explicit lock to sleep. FreeBSDs msleep takes the same approach. Plan 9s sleep uses a callback function that runs with the scheduling lock held just before going to sleep; the function serves as a last minute check of the sleep condition, to avoid missed wakeups. The Linux kernels sleep uses an explicit process queue instead of a wait channel; the queue has its own internal lock. Scanning the entire process list in wakeup for processes with a matching chan is inecient. A better solution is to replace the chan in both sleep and wakeup with a data structure that holds a list of processes sleeping on that structure. Plan 9s sleep and wakeup call that structure a rendezvous point or Rendez. Many thread libraries refer to the same structure as a condition variable; in that context, the operations sleep and wakeup are called wait and signal. All of these mechanisms share the same avor: the sleep condition is protected by some kind of lock dropped atomically during sleep. The implementation of wakeup wakes up all processes that are waiting on a particular channel, and it might be the case that many processes are waiting for that particular channel. The operating system will schedules all these processes and they will race to check the sleep condition. Processes that behave in this way are sometimes called a thundering herd, and it is best avoided. Most condition variables have two primitives for wakeup: signal, which wakes up one process, and broadcast, which wakes up all processes waiting. Semaphores are another common coordination mechanism. A semaphore is an integer value with two operations, increment and decrement (or up and down). It is aways possible to increment a semaphore, but the semaphore value is not allowed to drop below zero: a decrement of a zero semaphore sleeps until another process increments the semaphore, and then those two operations cancel out. The integer value typically corresponds to a real count, such as the number of bytes available in a pipe buer or the number of zombie children that a process has. Using an explicit count as part of the abstraction avoids the missed wakeup problem: there is an explicit count of the number of wakeups that have occurred. The count also avoids the spurious wakeup and thundering herd problems. 61 Exercises1. Sleep has to check lk != &ptable.lock to avoid a deadlock nate the special case by replacingif(lk != &ptable.lock){ acquire(&ptable.lock); release(lk); }(2517-2520). It could elimi- withrelease(lk); acquire(&ptable.lock); Doing this would break sleep. How? 2. Most process cleanup could be done by either exit or wait, but we saw above that exit must not free p->stack. It turns out that exit must be the one to close the open les. Why? The answer involves pipes. 3. Implement semaphores in xv6. You can use mutexes but do not use sleep and wakeup. Replace the uses of sleep and wakeup in xv6 with semaphores. Judge the result. 62 OverviewThe xv6 le system implementation is organized in 6 layers, as shown in Figure 5-1. The lowest layer reads and writes blocks on the IDE disk through the buer cache, which synchronizes access to disk blocks, making sure that only one kernel process at a time can edit the le system data stored in any particular block. The second layer allows higher layers to wrap updates to several blocks in a transaction, to ensure that the blocks are updated atomically (i.e., all of them are updated or none). The third layer provides unnamed les, each represented using an inode and a sequence of blocks holding the les data. The fourth layer implements directories as a special kind of inode whose content is a sequence of directory entries, each of which contains a name and a reference to the named les inode. The fth layer provides hierarchical path names like /usr/rtm/xv6/fs.c, using recursive lookup. The nal layer abstracts many Unix resources (e.g., pipes, devices, les, etc.) using the le system interface, simplifying the lives of application programmers. The le system must have a plan for where it stores inodes and content blocks on the disk. To do so, xv6 divides the disk into several sections, as shown in Figure 5-2. The le system does not use block 0 (it holds the boot sector). Block 1 is called the superblock; it contains metadata about the le system (the le system size in blocks,DRAFT as of September 7, 2011 63 System calls Pathnames Directories Files Transactions Blocks Directory inodes Inodes and block allocator Logging Buffer cache the number of data blocks, the number of inodes, and the number of blocks in the log). Blocks starting at 2 hold inodes, with multiple inodes per block. After those come bitmap blocks tracking which data blocks are in use (i.e., which are used in of some le). Most of the remaining blocks are data blocks, which hold le and directory contents. The blocks at the very end of the disk hold the log for transactions. The rest of this chapter discusses each layer, starting from the bottom. Look out for situations where well-chosen abstractions at lower layers ease the design of higher ones. The le system is a good example of how well-designed abstractions lead to surprising generality. 64 boot super inodes bit map data .... log 2 1 0 Figure 5-2. Structure of the xv6 le system. The header fs.h tures describing the exact layout of the le system. (3550) Process 1 release wakeup Buf b sector = 4 B_BUSY !B_BUSY B_BUSY Process 2 bget(3) sleep Time Figure 5-3. A race resulting in process 3 receiving a buer containing block 4, even though it asked for block 3. refresh the buer data from disk rather than use the previous blocks contents. Because the buer cache is used for synchronization, it is important that there is only ever one buer for a particular disk sector. The assignments (3939-3941) are only safe because bgets rst loop determined that no buer already existed for that sector, and bget has not given up buf_table_lock since then. If all the buers are busy, something has gone wrong: bget panics. A more graceful response might be to sleep until a buer became free, though there would then be a possibility of deadlock. Once bread has returned a buer to its caller, the caller has exclusive use of the buer and can read or write the data bytes. If the caller does write to the data, it must call bwrite to write the changed data to disk before releasing the buer. Bwrite (3964) sets the B_DIRTY ag and calls iderw to write the buer to disk. When the caller is done with a buer, it must call brelse to release it. (The name brelse, a shortening of b-release, is cryptic but worth learning: it originated in Unix and is used in BSD, Linux, and Solaris too.) Brelse (3974) moves the buer from its position in the linked list to the front of the list (3981-3986), clears the B_BUSY bit, and wakes any processes sleeping on the buer. Moving the buer has the eect that the buers are ordered by how recently they were used (meaning released): the rst buer in the list is the most recently used, and the last is the least recently used. The two loops in bget take advantage of this: the scan for an existing buer must process the entire list in the worst case, but checking the most recently used buers rst (starting at bcache.head and following next pointers) will reduce scan time when there is good locality of reference. The scan to pick a buer to reuse picks the least recently used block by scanning backward (following prev pointers).DRAFT as of September 7, 2011 66 Logging layerOne of the most interesting aspects of le system design is crash recovery. The problem arises because many le system operations involve multiple writes to the disk, and a crash after a subset of the writes may leave the on-disk le system in an inconsistent state. For example, depending on the order of the disk writes, a crash during le deletion may either leave a directory entry pointing to a free inode, or it may leave an allocated but unreferenced inode. The latter is relatively benign, but a directory entry that refers to a freed inode is likely to cause serious problems after a reboot. Xv6 solves the problem of crashes during le system operations with a simple version of logging. An xv6 system call does not directly write the on-disk le system data structures. Instead, it places a description of all the disk writes it wishes to make in a log on the disk. Once the system call has logged its writes, it writes a special commit record to the disk indicating the the log contains a complete operation. At that point the system call copies the writes to the on-disk le system data structures. After those writes have completed, the system call erases the log on disk. If the system should crash and reboot, the le system code recovers from the crash as follows, before running any processes. If the log is marked as containing a complete operation, then the recovery code copies the writes to where they belong in the on-disk le system. If the log is not marked as containing a complete operation, the recovery code ignores it. In either case, the recovery code nishes by erasing the log. Why does xv6s log solve the problem of crashes during le system operations? If the crash occurs before the operation commits, then the log on disk will not be marked as complete, the recovery code will ignore it, and the state of the disk will be as if the operation had not even started. If the crash occurs after the operation commits, then recovery will replay all of the operations writes, perhaps repeating them if the operation had started to write them to the on-disk data structure. In either case, the log makes operations atomic with respect to crashes: after recovery, either all of the operations writes appear on the disk, or none of them appear. Log designThe log resides at a known xed location at the very end of the disk. It consists of a header block followed by a sequence of data blocks. The header block contains an array of sector number, one for each of the logged data blocks. The header block also contains the count of logged blocks. Xv6 writes the header block when a transaction commits, but not before, and sets the count to zero after copying the logged blocks to the le system. Thus a crash midway through a transaction will result in a count of zero in the logs header block; a crash after a commit will result in a non-zero count. Each system calls code indicates the start and end of the sequence of writes that must be atomic; well call such a sequence a transaction, though it is much simpler than a database transaction. Only one system call can be in a transaction at any one time: other processes must wait until any ongoing transaction has nished. Thus theDRAFT as of September 7, 2011 67 log holds at most one transaction at a time. Xv6 only allows a single transaction at a time in order to avoid the following kind of race that could occur if concurrent transactions were allowed. Suppose transaction X has written a modication to an inode into the log. Concurrent transaction Y then reads a dierent inode in the same block, updates that inode, writes the inode block to the log, and commits. It would be a disaster if the commit of Y write Xs modied inode to the le system, since X has not yet committed. There are sophisticated ways to solve this problem; xv6 solves it by outlawing concurrent transactions. Xv6 allows read-only system calls to execute concurrently with a transaction. Inode locks cause the transaction to appear atomic to the read-only system call. Xv6 dedicates a xed amount of space on the disk to hold the log. No system call can be allowed to write more distinct blocks than there is space in the log. This is not a problem for most system calls, but two of them can potentially write many blocks: write and unlink. A large le write may write many data blocks and many bitmap blocks as well as an inode block; unlinking a large le might write many bitmap blocks and an inode. Xv6s write system call breaks up large writes into multiple smaller writes that t in the log, and unlink doesnt cause problems because in practice the xv6 le system uses only one bitmap block. Code: loggingA typical use of the log in a system call looks like this:begin_trans(); ... bp = bread(...); bp->data[...] = ...; log_write(bp); ... commit_trans(); begin_trans (4125) waits until it obtains exclusive use of the log and then returns. log_write (4159) acts as a proxy for bwrite; it appends the blocks new content to the log and records the blocks sector number. log_write leaves the modied block in the in-memory buer cache, so that subsequent reads of the block during the transaction will yield the modied block. log_write notices when a block is written multiple times during a single transaction, and overwrites the blocks previous copy in the log. commit_trans (4136) rst writes the logs header block to disk, so that a crash after this point will cause recovery to re-write the blocks in the log. commit_trans then calls install_trans (4071) to read each block from the log and write it to the proper place in the le system. Finally commit_trans writes the log header with a count of zero, so that a crash after the next transaction starts will result in the recovery code ignoring the log. recover_from_log (4116) is called from initlog (4055), which is called during boot before the rst user process runs. (2494) It reads the log header, and mimics the actions of commit_trans if the header indicates that the log contains a committed transaction. 68 (5152). This code is wrapped in a loop that breaks up large writes into individual transactions of just a few sectors at a time, to avoid overowing the log. The call to writei writes many blocks as part of this transaction: the les inode, one or more bitmap blocks, and some data blocks. The call to ilock occurs after the begin_trans as part of an overall strategy to avoid deadlock: since there is eectively a lock around each transaction, the deadlock-avoiding lock ordering rule is transaction before inode. InodesThe term inode can have one of two related meanings. It might refer to the ondisk data structure containing a les size and list of data block numbers. Or inode might refer to an in-memory inode, which contains a copy of the on-disk inode as well as extra information needed within the kernel. All of the on-disk inodes are packed into a contiguous area of disk called the inode blocks. Every inode is the same size, so it is easy, given a number n, to nd the nth inode on the disk. In fact, this number n, called the inode number or i-number, is how inodes are identied in the implementation. The on-disk inode is dened by a struct dinode (3572). The type eld distinguishes between les, directories, and special les (devices). A type of zero indicates that an on-disk inode is free. The kernel keeps the set of active inodes in memory; its struct inode (3613) is the in-memory copy of a struct dinode on disk. The kernel stores an inode in memory only if there are C pointers referring to that inode. The ref eld counts the number of C pointers referring to the in-memory inode, and the kernel discards the inode from memory if the reference count drops to zero. The iget and iput functions acquire and release pointers to an inode, modifying the reference count. Pointers to an inode can come from le descriptors, current working directories, and transient kernel code such as exec. The struct inode that iget returns may not have any useful content. In order to ensure it holds a copy of the on-disk inode, code must call ilock. This locks the inode (so that no other process can ilock it) and reads the inode from the disk, if it has not already been read. iunlock releases the lock on the inode. Separating acquisition of inode pointers from locking helps avoid deadlock in some situations, for example during directory lookup. Multiple processes can hold a C pointer to an inode returned by iget, but only one process can lock the inode at a time. The inode cache only caches inodes to which kernel code or data structures hold C pointers. Its main job is really synchronizing access by multiple processes, not caching. If an inode is used frequently, the buer cache will probably keep it in mem69 Code: Inodes(4402). To allocate a new inode (for example, when creating a le), xv6 calls ialloc Ialloc is similar to balloc: it loops over the inode structures on the disk, one block at a time, looking for one that is marked free. When it nds one, it claims it by writing the new type to the disk and then returns an entry from the inode cache with the tail call to iget (4418). Like in balloc, the correct operation of ialloc depends on the fact that only one process at a time can be holding a reference to bp: ialloc can be sure that some other process does not simultaneously see that the inode is available and try to claim it. Iget (4453) looks through the inode cache for an active entry (ip->ref > 0) with the desired device and inode number. If it nds one, it returns a new reference to that inode. (4462-4466). As iget scans, it records the position of the rst empty slot (44674468), which it uses if it needs to allocate a new cache entry. In both cases, iget returns one reference to the caller: it is the callers responsibility to call iput to release the inode. It can be convenient for some callers to arrange to call iput multiple times. The function idup (4488) increments the reference count so that an additional iput call is required before the inode can be dropped from the cache. Callers must lock the inode using ilock before reading or writing its metadata or content. Ilock (4502) uses a now-familiar sleep loop to wait for ip->flags I_BUSY bit to be clear and then sets it (4511-4513). Once ilock has exclusive access to the inode, it can load the inode metadata from the disk (more likely, the buer cache) if needed.DRAFT as of September 7, 2011 70 The function iunlock (4534) clears the I_BUSY bit and wakes any processes sleeping in ilock. Iput (4552) releases a C pointer to an inode by decrementing the reference count (4568). If this is the last reference, the inodes slot in the inode cache is now free and can be re-used for a dierent le to zero bytes, freeing the data blocks; sets the inode type to 0 (unallocated); writes the change to disk; and nally unlocks the inode (4555-4567). The locking protocol in iput deserves a closer look. The r. Specically, once iupdate nishes, the on-disk structure is marked as available for use, and a concurrent call to ialloc might nd it and reallocate it before iput can nish. Ialloc will return a reference to the block by calling iget, which will nd ip in the cache, see that its I_BUSY ag). dinode type major minor nlink size address 1 ..... address 12 indirect data indirect block address 1 ..... address 128 data data data ...odes size to zero. Itrunc (4654) starts by freeing the direct blocks (4660-4665) and then the ones listed in the indirect block (4670-4673), and nally the indirect block itself (4675-4676). Bmap makes it easy to write functions to access the inodes data stream, like readi and writei. Readi (4702) reads data from the inode. It starts making sure that the oset and count are not reading beyond the end of the le. Reads that start beyond the end of the le return an error (4713-4714) while reads that start at or cross the end of the le return fewer bytes than requested (4715-4716). The main loop processes each block of the le, copying data from the buer into dst (4718-4723). The function writei (4752) is identical to readi, with three exceptions: writes that start at or cross the end of the le grow the le, up to the maximum le size (4765-4766); the loop copies data into the buers instead of out (4771); and if the write has extended the le, writei must update its size (4776-4779). Both readi and writei begin by checking for ip->type == T_DEV. This case handles special devices whose data does not live in the le system; we will return to this case in the le descriptor layer.DRAFT as of September 7, 2011 72 The function stati (4274) copies inode metadata into the stat structure, which is exposed to user programs via the stat system call. 73 name, so namex need only return the unlocked ip (4969-4973). Finally, the loop looks for the path element using dirlookup and prepares for the next iteration by setting ip.=.next (4974-4979). When the loop runs out of path elements, it returns ip. 74 references to inodes. They are another good example of the power of using transactions. Sys_link (5313) begins by fetching its arguments, two strings old and new (5318). Assuming old exists and is not a directory (5320-5330), sys_link increments its ip>nlink count. Then sys_link calls nameiparent to nd the parent directory and nal path element of new (5336) and creates a new directory entry pointing at olds inode (5339). The new parent directory must exist and be on the same device as the existing inode: inode numbers only have a unique meaning on a single disk. If an error like this occurs, sys_link must go back and decrement ip->nlink. Transactions simplify the implementation because it requires updating multiple disk blocks, but we dont have to worry about the order in which we do them. They either will all succeed or none. For example, without transactions, updating ip->nlink before creating a link, would put the le system temporarily in an unsafe state, and a crash in between could result in havoc. With transactions we dont have to worry about this. Sys_link creates a new name for an existing inode. The function create (5457) creates a new name for a new inode. It is a generalization of the three le creation system calls: open with the O_CREATE ag makes a new ordinary le, mkdir makes a new directoryy, and mkdev makes a new device le. Like sys_link, create starts by caling nameiparent to get the inode of the parent directory. It then calls dirlookup to check whether the name already exists (5467). If the name does exist, creates behavior depends on which system call it is being used for: open has dierent semantics from mkdir and mkdev. If create is being used on behalf of open (type == T_FILE) and the name that exists is itself a regular le, then open treats that as a success, so create does too (5471). Otherwise, it is an error (5472-5473). If the name does not already exist, create now allocates a new inode with ialloc (5476). If the new inode is a directory, create initializes it with . and .. entries. Finally, now that the data is initialized properly, create can link it into the parent directory (5489). Create, like sys_link, holds two inode locks simultaneously: ip and dp. There is no possibility of deadlock because the inode ip is freshly allocated: no other process in the system will hold ips lock and then try to lock dp. Using create, it is easy to implement sys_open, sys_mkdir, and sys_mknod. Sys_open (5501) is the most complex, because creating a new le is only a small part of what it can do. If open is passed the O_CREATE ag, it calls create (5512). Otherwise, it calls namei (5517). Create returns a locked inode, but namei does not, so sys_open must lock the inode itself. This provides a convenient place to check that directories are only opened for reading, not writing. Assuming the inode was obtained one way or the other, sys_open allocates a le and a le descriptor (5526) and then lls in the le (5534-5538). Note that no other process can access the partially initialized le since it is only in the current processs table. Chapter 4 examined the implementation of pipes before we even had a le system. The function sys_pipe connects that implementation to the le system by providing a way to create a pipe pair. Its argument is a pointer to space for two integers, where it will record the two new le descriptors. Then it allocates the pipe and installs the le descriptors. 75 Real worldThe buer cache in a real-world operating system is signicantly more complex than xv6s, but it serves the same two purposes: caching and synchronizing access to the disk. Xv6s buer cache, like V6s, uses a simple least recently used (LRU) eviction policy; there are many more complex policies that can be implemented, each good for some workloads and not as good for others. A more ecient LRU cache would eliminate the linked list, instead using a hash table for lookups and a heap for LRU evictions. Modern buer caches are typically integrated with the virtual memory system to support memory-mapped les. Xv6s logging system is woefully inecient. It does not allow concurrent updating system calls, even when the system calls operate on entirely dierent parts of the le system. It logs entire blocks, even if only a few bytes in a block are changed. It performs synchronous log writes, a block at a time, each of which is likely to require an entire disk rotation time. Real logging systems address all of these problems. Logging is not the only way to provide crash recovery. Early le systems used a scavenger during reboot (for example, the UNIX fsck program) to examine every le and directory and the block and inode free lists, looking for and resolving inconsistencies. Scavenging can take hours for large le systems, and there are situations where it is not possible to guess the correct resolution of an inconsistency. Recovery from a log is much faster and is correct. Xv6 uses the same basic on-disk layout of inodes and directories as early UNIX; this scheme has been remarkably persistent over the years. BSDs UFS/FFS and Linuxs ext2/ext3 use essentially the same data structures. The most inecient part of the le system layout is the directory, which requires a linear scan over all the disk blocks during each lookup. This is reasonable when directories are only a few disk blocks, but is expensive for directories holding many les. Microsoft Windowss NTFS, Mac OS Xs HFS, and Solariss ZFS, just to name a few, implement a directory as an on-disk balanced tree of blocks. This complicated but guarantees logarithmic-time directory lookups. Xv6 is naive about disk failures: if a disk operation fails, xv6 panics. Whether this is reasonable depends on the hardware: if an operating systems sits atop special hardware that uses redundancy to mask disk failures, perhaps the operating system sees failures so infrequently that panicking is okay. On the other hand, operating systems using plain disks should expect failures and handle them more gracefully, so that the loss of a block in one le doesnt aect the use of the rest of the les system. Xv6 requires that the le system t on one disk device and not change in size. As large databases and multimedia les drive storage requirements ever higher, operating systems are developing ways to eliminate the one disk per le system bottleneck. The basic approach is to combine many disks into a single logical disk. Hardware solutions such as RAID are still the most popular, but the current trend is moving toward implementing as much of this logic in software as possible. These software implementations typically allowing rich functionality like growing or shrinking the logical device by adding or removing disks on the y. Of course, a storage layer that can grow or shrink on the y requires a le system that can do the same: the xed-size array of inode blocks used by Unix le systems does not work well in such environments. SepaDRAFT as of September 7, 2011 76 rating disk management from the le system may be the cleanest design, but the complex interface between the two has led some systems, like Suns ZFS, to combine them. Xv6s le system lacks many other features in today le systems; for example, it lacks support for snapshots and incremental backup. Xv6 has two dierent le implementations: pipes and inodes. Modern Unix systems have many: pipes, network connections, and inodes from many dierent types of le systems, including network le systems. Instead of the if statements in fileread and filewrite, these systems typically give each open le a table of function pointers, one per operation, and call the function pointer to invoke that inodes implementation of the call. Network le systems and user-level le systems provide functions that turn those calls into network RPCs and wait for the response before returning. Exercises1. why panic in balloc? Can we recover? 2. why panic in ialloc? Can we recover? 3. inode generation numbers. 4. Why doesnt lealloc panic when it runs out of les? Why is this more common and therefore worth handling? 5. Suppose the le corresponding to ip gets unlinked by another process between sys_links calls to iunlock(ip) and dirlink. Will the link be created correctly? Why or why not? 6. create makes four function calls (one to ialloc and three to dirlink) that it requires to succeed. If any doesnt, create calls panic. Why is this acceptable? Why cant any of those four calls fail? 7. sys_chdir calls iunlock(ip) before iput(cp->cwd), which might try to lock cp->cwd, yet postponing iunlock(ip) until after the iput would not cause deadlocks. Why not? 77 Appendix A PC hardwareThis appendix describes personal computer (PC) hardware, the platform on which xv6 runs. A PC is a computer that adheres to several industry standards, with the goal that a given piece of software can run on PCs sold by multiple vendors. These standards evolve over time and a PC from 1990s doesnt look like a PC now. From the outside a PC is a box with a keyboard, a screen, and various devices (e.g., CD-rom, etc.). Inside the box is a circuit board (the motherboard) with CPU chips, memory chips, graphic chips, I/O controller chips, and busses through which the chips communicate. The busses adhere to standard protocols (e.g., PCI and USB) so that devices will work with PCs from multiple vendors. From our point of view, we can abstract the PC into three components: CPU, memory, and input/output (I/O) devices. The CPU performs computation, the memory contains instructions and data for that computation, and devices allow the CPU to interact with hardware for storage, communication, and other functions. You can think of main memory as connected to the CPU with a set of wires, or lines, some for address bits, some for data bits, and some for control ags. To read a value from main memory, the CPU sends high or low voltages representing 1 or 0 bits on the address lines and a 1 on the read line for a prescribed amount of time and then reads back the value by interpreting the voltages on the data lines. To write a value to main memory, the CPU sends appropriate bits on the address and data lines and a 1 on the write line for a prescribed amount of time. Real memory interfaces are more complex than this, but the details are only important if you need to achieve high performance. 79 written quickly, in a single CPU cycle. PCs have a processor that implements the x86 instruction set, which was originally dened by Intel and has become a standard. Several manufacturers produce processors that implement the instruction set. Like all other PC standards, this standard is also evolving but newer standards are backwards compatible with past standards. The boot loader has to deal with some of this evolution because every PC processor starts simulating an Intel 8088, the CPU chip in the original IBM PC released in 1981. However, for most of xv6 you will be concerned with the modern x86 instruction set. The modern x86 provides eight general purpose 32-bit registers%eax, %ebx, %ecx, %edx, %edi, %esi, %ebp, and %espand a program counter %eip (the instruction pointer). The common e prex stands for extended, as these are 32-bit extensions of the 16-bit registers %ax, %bx, %cx, %dx, %di, %si, %bp, %sp, and %ip. The two register sets are aliased so that, for example, %ax is the bottom half of %eax: writing to %ax changes the value stored in %eax and vice versa. The rst four registers also have names for the bottom two 8-bit bytes: %al and %ah denote the low and high 8 bits of %ax; %bl, %bh, %cl, %ch, %dl, and %dh continue the pattern. In addition to these registers, the x86 has eight 80-bit oating-point registers as well as a handful of special-purpose registers like the control registers %cr0, %cr2, %cr3, and %cr4; the debug registers %dr0, %dr1, %dr2, and %dr3; the segment registers %cs, %ds, %es, %fs, %gs, and %ss; and the global and local descriptor table pseudo-registers %gdtr and %ldtr. The control registers and segment registers are important to any operating system. The oating-point and debug registers are less interesting and not used by xv6. Registers are fast but expensive. Most processors provide at most a few tens of general-purpose registers. The next conceptual level of storage is the main random-access memory (RAM). Main memory is 10-100x slower than a register, but it is much cheaper, so there can be more of it. One reason main memory is relatively slow is that it is physically separate from the processor chip. An x86 processor has a few dozen registers, but a typical PC today has gigabytes of main memory. Because of the enormous dierences in both access speed and size between registers and main memory, most processors, including the x86, store copies of recently-accessed sections of main memory in on-chip cache memory. The cache memory serves as a middle ground between registers and memory both in access time and in size. Todays x86 processors typically have two levels of cache, a small rst-level cache with access times relatively close to the processors clock rate and a larger second-level cache with access times in between the rst-level cache and main memory. This table shows actual numbers for an Intel Core 2 Duo system: Intel Core 2 Duo E7200 at 2.53 GHz TODO: Plug in non-made-up numbers! storage access time size register 0.6 ns 64 bytes L1 cache 0.5 ns 64 kilobytes L2 cache 10 ns 4 megabytes main memory 100 ns 4 gigabytes 80 For the most part, x86 processors hide the cache from the operating system, so we can think of the processor as having just two kinds of storageregisters and memoryand not worry about the distinctions between the dierent levels of the memory hierarchy. I/OProcessors must communicate with devices as well as memory. The x86 processor provides special in and out instructions that read and write values from device addresses called I/O ports. The hardware implementation of these instructions is essentially the same as reading and writing memory. Early x86 processors had an extra address line: 0 meant read/write from an I/O port and 1 meant read/write from main memory. Each hardware device monitors these lines for reads and writes to its assigned range of I/O ports. A devices ports let the software congure the device, examine its status, and cause the device to take actions; for example, software can use I/O port reads and writes to cause the disk interface hardware to read and write sectors on the disk. Many computer architectures have no separate device access instructions. Instead the devices have xed memory addresses and the processor communicates with the device (at the operating systems behest) by reading and writing values at those addresses. In fact, modern x86 architectures use this technique, called memory-mapped I/O, for most high-speed devices such as network, disk, and graphics controllers. For reasons of backwards compatibility, though, the old in and out instructions linger, as do legacy hardware devices that use them, such as the IDE disk controller, which xv6 uses. 81 x GB Selector CPU Offset Logical Address 0 RAM Segment Translation Linear Address Physical Address Page Translation Figure B-1. The relationship between logical, linear, and physical addresses. 83 Xv6 pretends that an x86 instruction uses a virtual address for its memory operands, but an x86 instruction actually uses a logical address (see Figure B-1). A logical address consists of a segment selector and an oset, and is sometimes written as segment:oset. More often, the segment is implicit and the program only directly manipulates the oset. The segmentation hardware performs the translation described above to generate a linear address. If the paging hardware is enabled (see Chapter 1), it translates linear addresses to physical addresses; otherwise the processor uses linear addresses as physical addresses. The boot loader does not enable the paging hardware; the logical addresses that it uses are translated to linear addresses by the segmentation harware, and then used directly as physical addresses. Xv6 congures the segmentation hardware to translate logical to linear addresses without change, so that they are always equal. For historical reasons we have used the term virtual address to refer to addresses manipulated by programs; an xv6 virtual address is the same as an x86 logical address, and is equal to the linear address to which the segmentation hardware maps it. Once paging is enabled, the only interesting address mapping in the system will be linear to physical. The BIOS does not guarantee anything about the contents of %ds, %es, %ss, so rst order of business after disabling interrupts is to set %ax to zero and then copy that zero into %ds, %es, and %ss (8215-8218). A virtual segment:oset can yield a 21-bit physical address, but the Intel 8088 could only address 20 bits of memory, so it discarded the top bit: 0xffff0+0xffff = 0x10ffef, but virtual address 0xffff:0xffff on the 8088 referred to physical address 0x0ffef. Some early software relied on the hardware ignoring the 21st address bit, so when Intel introduced processors with more than 20 bits of physical address, IBM provided a compatibility hack that is a requirement for PC-compatible hardware. If the second bit of the keyboard controllers output port is low, the 21st physical address bit is always cleared; if high, the 21st bit acts normally. The boot loader must enable the 21st address bit using I/O to the keyboard controller on ports 0x64 and 0x60 (82208236). Real modes 16-bit general-purpose and segment registers make it awkward for a program to use more than 65,536 bytes of memory, and impossible to use more than a megabyte. x86 processors since the 80286 have a protected mode, which allows physical addresses to have many more bits, and (since the 80386) a 32-bit mode that causes registers, virtual addresses, and most integer arithmetic to be carried out with 32 bits rather than 16. The xv6 boot sequence enables protected mode and 32-bit mode as follows. In protected mode, a segment register is an index into a segment descriptor table (see Figure B-2). Each table entry species a base physical address, a maximum virtual address called the limit, and permission bits for the segment. These permissions are the protection in protected mode: the kernel can use them to ensure that a program uses only its own memory. xv6 makes almost no use of segments; it uses the paging hardware instead, as Chapter 1 describes. The boot loader sets up the segment descriptor table gdt (82828285) so that all segments have a base address of zero and the maximum possible limit (four gigabytes). The table has a null entry, one entry for executable code, and one en- 84 Logical Address16 32 Linear Address Selector try to data. The code segment descriptor has a ag set that indicates that the code should run in 32-bit mode (0660). With this setup, when the boot loader enters protected mode, logical addresses map one-to-one to physical addresses. The boot loader executes an lgdt instruction (8241) to load the processors global descriptor table (GDT) register with the value gdtdesc (8287-8289), which points to the table gdt. Once it has loaded the GDT register, the boot loader enables protected mode by setting the 1 bit (CR0_PE) in register %cr0 (8242-8244). Enabling protected mode does not immediately change how the processor translates logical to physical addresses; it is only when one loads a new value into a segment register that the processor reads the GDT and changes its internal segmentation settings. One cannot directly modify %cs, so instead the code executes an ljmp (far jump) instruction (8253), which allows a code segment selector to be specied. The jump continues execution at the next line (8256) but in doing so sets %cs to refer to the code descriptor entry in gdt. That descriptor describes a 32-bit code segment, so the processor switches into 32-bit mode. The boot loader has nursed the processor through an evolution from 8088 through 80286 to 80386. The boot loaders rst action in 32-bit mode is to initialize the data segment registers with SEG_KDATA (8258-8261). Logical address now map directly to physical addresses. The only step left before executing C code is to set up a stack in an unused region of memory. The memory from 0xa0000 to 0x100000 is typically littered with device memory regions, and the xv6 kernel expects to be placed at 0x100000. The boot loader itself is at 0x7c00 through 0x7d00. Essentially any other section of memory would be a ne location for the stack. The boot loader chooses 0x7c00 (known in this le as $start) as the top of the stack; the stack will grow down from there, toward 0x0000, away from the boot loader. Finally the boot loader calls the C function bootmain (8268). Bootmains job is to load and run the kernel. It only returns if something has gone wrong. In that case, the code sends a few output words on port 0x8a00 (8270-8276). On real hardware, there is no device connected to that port, so this code does nothing. If the boot loader is running inside a PC simulator, port 0x8a00 is connected to the simulator itself and can transfer control back to the simulator. Simulator or not, the code then executes an innite loop (8277-8278). A real boot loader might attempt to print an error message rst. 85 Code: C bootstrapThe C part of the boot loader, bootmain.c (8300), expects to nd a copy of the kernel executable on the disk starting at the second sector. The kernel is an ELF format binary, as we have seen in Chapter 1. To get access to the ELF headers, bootmain loads the rst 4096 bytes of the ELF binary (8314). It places the in-memory copy at address 0x10000. The next step is a quick check that this probably is an ELF binary, and not an uninitialized disk. Bootmain reads the sections content starting from the disk location off bytes after the start of the ELF header, and writes to memory starting at address paddr. Bootmain calls readseg to load data from disk (8338) and calls stosb to zero the remainder of the segment (8340). Stosb (0492) uses the x86 instruction rep stosb to initialize every byte of a block of memory. The kernel has been compiled and linked so that it expects to nd itself at virtual addresses starting at 0x80100000. That is, function call instructions mention destination addresses that look like 0xf01xxxxx; you can see examples in kernel.asm. This address is congured in kernel.ld. 0x80100000 is a relatively high address, towards the end of the 32-bit address space; Chapter 1 explains the reasons for this choice. There may not be any physical memory at such a high address. Once the kernel starts executing, it will set up the paging hardware to map virtual addresses starting at 0x80100000 to physical addresses starting at 0x00100000; the kernel assumes that there is physical memory at this lower address. At this point in the boot process, however, paging is not enabled. Instead, kernel.ld species that the ELF paddr start at 0x00100000, which causes the boot loader to copy the kernel to the low physical addresses to which the paging hardware will eventually point. The boot loaders nal step is to call the kernels entry point, which is the instruction at which the kernel expects to start executing. For xv6 the entry address is 0x10000c:# objdump -f kernel kernel: file format elf32-i386 architecture: i386, flags 0x00000112: EXEC_P, HAS_SYMS, D_PAGED start address 0x0010000c By convention, the _start symbol species the ELF entry point, which is dened in the le entry.S (1036). Since xv6 hasnt set up virtual memory yet, xv6s entry point is the physical address of entry (1040). Real worldThe boot loader described in this appendix compiles to around 470 bytes of machine code, depending on the optimizations used when compiling the C code. In order to t in that small amount of space, the xv6 boot loader makes a major simplifying assumption, that the kernel has been written to the boot disk contiguously starting at sector 1. More commonly, kernels are stored in ordinary le systems, where they may not be contiguous, or are loaded over a network. These complications require theDRAFT as of September 7, 2011 86 boot loader to be able to drive a variety of disk and network controllers and understand various le systems and network protocols. In other words, the boot loader itself must be a small operating system. Since such complicated boot loaders certainly wont t in 512 bytes, most PC operating systems. Perhaps a more modern design would have the BIOS directly read a larger boot loader from the disk (and start it in protected and 32-bit mode). This appendix is written as if the only thing that happens between power on and the execution of the boot loader is that the BIOS loads the boot sector. In fact the BIOS does a huge amount of initialization in order to make the complex hardware of a modern computer look like a traditional standard PC. Exercises1. Due to sector granularity, the call to readseg in the text is equivalent to readseg((uchar*)0x100000, 0xb500, 0x1000). In practice, this sloppy behavior turns out not to be a problem Why doesnt the sloppy readsect cause problems? 2. something about BIOS lasting longer + security problems 3. Suppose you wanted bootmain() to load the kernel at 0x200000 instead of 0x100000, and you did so by modifying bootmain() to add 0x100000 to the va of each ELF section. Something would go wrong. What? 4. It seems potentially dangerous for the boot loader to copy the ELF header to memory at the arbitrary location 0x10000. Why doesnt it call malloc to obtain the memory it needs? 87 Index., 73, 75 .., 73, 75 /init, 2829 _binary_initcode_size, 25 _binary_initcode_start, 25 _start, 86 acquire, 45, 48 addl, 26 address space, 18 allocproc, 23 allocuvm, 26, 28 alltraps, 3435 argc, 28 argint, 37 argptr, 37 argstr, 37 argv, 28 atomic, 45 B_BUSY, 39, 6566 B_DIRTY, 3941, 6566 B_VALID, 3941, 65 balloc, 70 bcache.head, 65 begin_trans, 6869 bfree, 70 bget, 65 binit, 65 block, 39 bmap, 71 boot loader, 19, 8385 bootmain, 85 bread, 64, 66 brelse, 64, 66 BSIZE, 71 buf_table_lock, 65 buer, 39, 64 busy waiting, 40 bwrite, 64, 66, 68 chan, 56, 58 child process, 9 cli, 38, 48 commit, 67 commit_trans, 68 conditional synchronization, 55 contexts, 52 control registers, 80 convoys, 61 copyout, 28 coroutines, 54 cp->killed, 36 cp->tf, 36 cpu->scheduler, 26, 5253 CR0_PE, 85 CR0_PG, 19 CR0_WP, 19 CR_PSE, 19 crash recovery, 63 create, 75 current directory, 14 deadlocked, 57 direct blocks, 71 dirlink, 73 dirlookup, 7375 DIRSIZ, 73 DPL_USER, 25, 34 driver, 39 dup, 74 ELF format, 28 ELF_MAGIC, 28 EMBRYO, 24 end, 2223 enter_alloc, 23 entry, 19, 86 entrypgdir, 19 exception, 31 exec, 911, 2628, 34 exit, 9, 26, 5354, 60 fetchint, 37 le descriptor, 10 filealloc, 74 fileclose, 74 filedup, 74 fileread, 74, 77 filestat, 74 filewrite, 69, 74, 77 FL, 34 FL_IF, 25 fork, 911, 74 forkret, 24, 26, 54 fsck, 76 ftable, 74 gdt, 8485 gdtdesc, 85 getcmd, 10 global descriptor table, 85 I/O ports, 81 I_BUSY, 7071 I_VALID, 71 ialloc, 7071, 75 IDE_BSY, 40 IDE_DRDY, 40 IDE_IRQ, 39 ideinit, 3940 ideintr, 40, 4748 idelock, 46, 48 iderw, 40, 46, 48, 6566 idestart, 40 idewait, 40 idt, 34 idtinit, 38 idup, 70 IF, 38 iget, 6971, 73 ilock, 6970, 73 inb, 38 indirect block, 71 initcode, 29 initcode.S, 2526, 33 initlog, 68 initproc, 26 inituvm, 25 inode, 15, 63, 69 insl, 40 install_trans, 68 instruction pointer, 80 int, 3234 interface design, 7 interrupt, 31 interrupt handler, 32 ioapicenable, 39 iput, 6971 iret, 26, 33, 36 IRQ_TIMER,, 38 itrunc, 7172 iunlock, 71 iupdate, 71 kalloc, 23 KERNBASE, 19 89 kernel, 7 kernel mode, 32 kernel space, 7 kfree, 22 kinit, 22 kmap, 21 kvmalloc, 2021 lapicinit, 38 linear address, 8384 links, 15 loaduvm, 28 lock, 43 log, 67 log_write, 68 logical address, 8384 main, 2023, 26, 34, 39, 65 malloc, 10 mappages, 21 memory-mapped I/O, 81 mkdev, 75 mkdir, 75 mpmain, 25 multiplex, 51 namei, 25, 28, 73, 75 nameiparent, 73, 75 namex, 7374 NBUF, 65 NDIRECT, 71 NINDIRECT, 71 O_CREATE, 75 open, 7475 outb, 38 p->context, 24, 26, 54 p->cwd, 25 p->kstack, 23, 60 p->name, 25 p->parent, 60 p->pgdir, 23, 60 p->state, 23 p->sz, 37 p->xxx, 23 page, 17 page directory, 17 page table entries (PTEs), 17 page table pages, 17 panic, 36 parent process, 9 path, 14 persistence, 63 PGROUNDUP, 23DRAFT as of September 7, 2011 physical address, 17, 83 PHYSTOP, 2122 picenable, 39 pid, 9, 24 pipe, 13 piperead, 59 pipewrite, 59 polling, 40 popal, 26 popcli, 48 popl, 26 printf, 9 priority inversion, 61 process, 78, 17 program counter, 79 programmable interrupt controler (PIC), 38 protected mode, 8485 ptable, 47 ptable.lock, 5354, 58, 60 PTE_P, 18 PTE_U, 18, 21, 26 PTE_W, 18 pushcli, 48 race condition, 44 read, 74 readi, 28, 7172 readsb, 70 readseg, 86 real mode, 83 recover_from_log, 68 recursive locks, 46 release, 46, 4849 ret, 26 root, 14 round robin, 60 RUNNABLE, 25, 54, 5859 sbrk, 10, 27 sched, 5254, 58, 60 scheduler, 2526, 5354 sector, 39 SEG_KCPU, 35 SEG_KDATA, 26, 85 SEG_TSS, 26 SEG_UCODE, 25 SEG_UDATA, 25 seginit, 29 segment descriptor table, 84 segment registers, 80 sequence coordination, 55 90 setupkvm, 21, 23, 2526, 28 skipelem, 73 sleep, 47, 53, 5658, 65 SLEEPING, 58 stat, 7374 stati, 7374 sti, 38, 48 stosb, 86 struct buf, 39 struct context, 52 struct dinode, 69, 71 struct dirent, 73 struct elfhdr, 28 struct file, 74 struct inode, 69 struct pipe, 59 struct proc, 23, 60 struct run, 22 struct spinlock, 45 struct trapframe, 25 superblock, 63 superpage, 19 switch, 26 switchuvm, 26, 34, 38, 54 swtch, 26, 5254, 60 sys_exec, 27, 34 SYS_exec, 26, 36 sys_link, 7475 sys_mkdir, 75 sys_mknod, 75 sys_open, 75 sys_pipe, 75 sys_sleep, 48 sys_unlink, 74 syscall, 27, 36 system calls, 7 T_DEV, 72 T_DIR, 73 T_FILE, 75 T_SYSCALL, 26, 34, 36 tf->trapno, 36 thread, 23 thundering herd, 61 ticks, 48 tickslock, 48 timer.c, 38 transaction, 63 trap, 3536, 3940, 52 trapret, 24, 26, 36 traps, 32 tvinit, 34 type cast, 23 unlink, 68 user memory, 18 user mode, 32 user space, 7 userinit, 23, 2526 ustack, 28 V2P_WO, 19 vectors[i], 34 virtual address, 17, 84 wait channel, 56 wait, 9, 54, 60 wakeup, 39, 47, 56, 58 wakeup1, 58 walkpgdir, 2123, 28 write, 68, 74 writei, 69, 7172 xchg, 45, 48 yield, 5254 ZOMBIE, 60 91 Much more than documents. Discover everything Scribd has to offer, including books and audiobooks from major publishers.Cancel anytime.
https://www.scribd.com/document/94239911/XV6-A-simple-Unix-like-teaching-operating-system-book
CC-MAIN-2019-47
refinedweb
25,942
67.38
I also need the touchForeignPtr trick in much of my code. we need to come up with a replacement if we dont have haskell finalizers. here are my canidate suggestions: * add a subset of Weak pointers (or some subset of their functionality) to the FFI spec. just get rid of the finalizer capability (for obvious reasons) and the Weak pointers work just as well, and it might have uses elsewhere? - or - * add addForeignDependency :: ForeignPtr a -> ForeignPtr b -> IO () (which on ghc is trivially implemented as 'addForeignDependency a b = mkWeak a b Nothing >> return ()') note that breaking these dependencies might be tricky/impossible depending on what we choose. with weak pointers, one can finalize the Weak that the mkWeak call returns, but then you have to keep track of them in a seperate data structure than your ForeignPtr, which doesnt seem ideal. a better solution would be some sort of breakWeakPtr :: k -> v -> IO () breakForeignDependency :: ForeignPtr a -> ForeignPtr b -> IO () hmm... John On Mon, Oct 21, 2002 at 02:50:03PM -0400, Antony Courtney wrote: >.) -- --------------------------------------------------------------------------- John Meacham - California Institute of Technology, Alum. - john at foo.net ---------------------------------------------------------------------------
http://www.haskell.org/pipermail/ffi/2002-October/000934.html
CC-MAIN-2014-35
refinedweb
185
61.56
From feature request to binary delivery in less than four hours. Here’s the timeline: Is there a way to get #CodeRush to suggest namespace usages for extension methods? Which led to the following discussion with one of our CodeRush devs on IM: [10:08] Mark: Hey Alex, I have this question in a tweet -- "Is there a way to get #CodeRush to suggest namespace usages for extension methods?" [10:09] Alex: Hi Mark, I'm not sure what he means… [10:10] Mark: I think he's talking about adding namespace imports when an extension method is at the caret. [10:10] Mark: I'm wondering if VS fails to do this. [10:10] Alex: I suppose VS does it, doesn’t it? [10:10] Mark: Check it for me. [10:12] Alex: OK, VS fails to do this. [10:13] Alex: And we don't have such feature [10:13] Mark: Can we write this as a plug-in? [10:13] Alex: Of course, but this will take time. [10:14] Mark: What's the challenging part of this? [10:14] Alex: Find and resolve all the extension methods [10:15] Mark: Create a spike -- work on this for an hour and see what you get. [10:15] Mark: Then send me that source and I can finish it up [10:15] Alex: ok [10:15] Mark: Then I'll have Rory put it on the community site. [10:15] Alex: k Which led to the development of the feature, testing, a few changes, and then this IM with Rory Becker: [13:06] Mark: I had Alex create a plug-in spike for a feature request to add missing namespace references for extension methods (something VS does not do) [13:06] Rory: cool [13:06] Mark: I'm going to send this to you. Can you get this on the community plug-in site today? [13:06] Rory: yeah sure, no problem Here’s the feature in action: Here’s the link to the feature on the CodeRush community plug-ins site: We are likely to roll this functionality into a future version of CodeRush. If you have a CodeRush question or feature request, we want to hear from you. Post a comment below or include “#CodeRush” in your tweets and we’ll respond in a timely manner. Today Rory and I presented a webinar called Creating CodeRush Plug-ins: Actions and Tool Windows. In it, we created a tool window that displays all Markers dropped throughout all open files. To see how we built this, watch the webinar here, which should be published in the next 24 hours if it isn’t available already. The source to this plug-in can be found on the CodeRush community plug-in site, located here. If you saw our Using CodeRush with MVC webinar, Rory and I introduced new templates that make it easy to exploit the MVC Extensions from DevExpress. These templates will likely be integrated into CodeRush 11.1, however you can install and start using them right now (installation instructions appear below). These templates make it easier to create elements inside the MVC controls. Copy the reference that will own these elements (e.g., “settings”, “settings.Properties”, “firstMenu”, etc.) to the clipboard before expanding. To install, follow these steps: 1. Right-click and save each of the templates below. HTML_MVC_DevEx Extensions.xml CSharp_ASP.NET_MVC_DevEx Extensions.xml IMPORTANT: For VB developers, we have two sets of templates to choose from. If you are working in CodeRush 10.2.5 or less, use these templates: Basic_ASP.NET_MVC_DevEx Extensions.xml If you are working in CodeRush 10.2.6 or greater, use these templates instead: Basic_ASP.NET_MVC_DevEx Extensions.xml HTML_MVC_DevEx Extensions.xml CSharp_ASP.NET_MVC_DevEx Extensions.xml IMPORTANT: For VB developers, we have two sets of templates to choose from. 2. Start Visual Studio if it’s not running already. 3. From the DevExpress menu, select Options. 4. Navigate to the Editor\Templates options page. 5. IMPORTANT: Change the Language combo box at the bottom of the Options dialog to HTML. 6. Right-click the template TreeView and choose Import Templates…. 7. Select the HTML_MVC_DevEx Extensions xml file downloaded in step one, and click Open. 8. If you see a Category Exists warning message, click OK. Next, we need to install the templates for adding items, groups, nodes, panes, and tab pages. These templates must be imported into the appropriate language group of templates. 1. IMPORTANT: Change the Language combo box at the bottom of the Options dialog to Basic. 2. Right-click the template TreeView and choose Import Templates…. 3. Select the Basic_ASP.NET_MVC_DevEx Extensions xml file downloaded in step one, and click Open. 4. If you see a Category Exists warning message, click OK. 1. IMPORTANT: Change the Language combo box at the bottom of the Options dialog to CSharp. 3. Select the CSharp_ASP.NET_MVC_DevEx Extensions xml file downloaded in step one, and click Open. After importing the MVC Extension templates as shown above, click OK to close the Options dialog. Inside an MVC application, open an aspx file, go to an empty line, and expand one or more of the templates on this.
https://community.devexpress.com/blogs/markmiller/archive/2011/03.aspx
CC-MAIN-2017-09
refinedweb
865
74.19
From: Terje Slettebø (tslettebo_at_[hidden]) Date: 2004-09-19 09:03:01 >From: "Tobias Schwinger" <tschwinger_at_[hidden]> By the way, nice idea with the member function pointer traits proposal (in the "[type_traits] "member_function_pointer_traits"" thread). The operator/concept traits library contains a similar, but orthogonal component, has_member_function<> (in type_traits_ext/has_member_function.hpp). E.g., to detect a member function with the signature "void A::swap(A &)", one can use: has_member_function<A, has_member_swap, void, A &>::value The parameters are: Class (A), class template for member detection ("has_member_swap", defined using macro in has_member.hpp header), return type (void), any parameters (A &). I think the components are orthogonal, because the above concerns member function _detection_, while your traits are concerned with whether or not a type T is a member function pointer, and if it is, what are the properties of the member function. In other words, if you do is_member_function_pointer<&A::swap>, and A doesn't have a swap() member, you'll get an error, rather than false. I think your proposal would nicely complement the existing Boost type traits. > I had a look at your library proposal today. > Looks like a very valuable tool for everyone into generic programming. Thanks. :) > It seems quite easy to add new concepts, which I think is one of the > most important things (the has_member family looks very promising). I'll expand the docs for that section, as well, as mentioned in a recent posting. I agree that this issue is one of the most important ones. > I was able to build the operator_traits test with GCC 3.2.3 mingw (about > 20 minutes PIII,600MHz,512MB RAM - 100% passed - guess I just had to see > it with my own eyes ;+). Ah. :) The std_concept_traits_test.cpp and boost_mpl_concept_traits_test.cpp doesn't work fully on g++ 3.2, yet, but I intend to work on that. > It failed to build on MSVC 13.10.3077 and Borland 5.4.6 (I kept the > output, in case you are interested). Strange, as it works on MSVC 12.00.8804, which is the one I've tested it on (in addition to Intel C++ 7.1 and g++ 3.2). I don't think I have any hope of getting it to work on Borland 5.x (or 6.x, for that matter). I haven't tested it there, and my aim has been Intel C++ 7.1 (maybe 6.0 and up, but I've used 7.1 for testing, so far), MSVC 7.1 and g++ 3.2 (and later for all). Of course, it would be nice if it was possible to get it to work on other compilers, as well. Sure, I'd appreciate it if you could send the compiler output to me. > It might be possible to put the prefiltering stage of the operator > traits into sort of table based form, making it easier to maintain, > eliminating a lot of inclusion dependencies and template instantiations > and covering tests for builtin operators (if they should be detected, > that is) as well. Interesting idea... Something to remove that pre-filtering "boiler plate" code with something less taylor-made for each trait could certainly be useful, and potentially speed up the compilation, as well as removing a lot of inclusion dependencies, yes. However, I haven't been able to come up with anything like that, so far. > This can probably be done with a technique in some way similar to the > one applied to the operator checking itself - defining a rule set of > overloaded functions to match the exclusions. Classes with a converting > copy constructor can be used to categorize the types matched by the > rules. The rule sets for different operator categories could be put into > nested namespaces so inner categories could 'inherit' the rules of the > outter ones. > I attached some experimental source code for the prefiltering of an > operator+ check to clearify the basic idea (compiles with GCC and MSVC > and CVS version of boost). Great. :) I'll check it out. Regards, Terje Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2004/09/72508.php
CC-MAIN-2020-45
refinedweb
689
66.03
MySQLdb 1.1.7 MySQL 4.1.7. RH Linux 9.0, 7.3 using RPM install Python 2.3.4 Create a table like this: CREATE TABLE test_table ( id int(11) NOT NULL auto_increment, name varchar(100) NOT NULL default '', PRIMARY KEY ( id) ) Type=InnoDB; Then use code like this to (try to) add new records: import MySQLdb db = MySQLdb.connect(...) c = db.cursor() c.execute("insert into test_table values ()") c.execute("SELECT LAST_INSERT_ID()") print c.fetchall() The last_insert_id value will increment, but no records will actually be created. If you change the table type from InnoDB to MyISAM, the code works just as expected. I suspect that this is a problem with MySQLdb, because when I use the "mysql" command-line client, I don't encounter any problem. Unfortunately I can't revert to MySQLdb 1.0.0 since it won't compile with MySQL 4.1.7. -Michael Andy Dustman 2004-11-24 Logged In: YES user_id=71372 The problem is almost certainly that the 1.1 series does not operate in autocommit mode by default, to comply with the DB API standard. Try either of these: import MySQLdb db = MySQLdb.connect(...) db.autocommit(True) c = db.cursor() c.execute("insert into test_table values ()") print c.lastrowid print c.fetchall() ...or... import MySQLdb db = MySQLdb.connect(...) c = db.cursor() c.execute("insert into test_table values ()") print c.lastrowid db.commit() print c.fetchall() Note use of c.lastrowid; this is the portable way to do it. Andy Dustman 2004-11-24 Logged In: YES user_id=71372 (actually you don't need those c.fetchall()s in my examples) Michael Klatt 2004-11-29 Logged In: YES user_id=1127829 Thank you for your quick and very accurate response. As soon as I turned auto-commit on by default, the problem is fixed. I've looked around the documentation and I couldn't find any reference to this change in behavior. I just found a couple posts on the mailing list, but I'm certain many more people will encounter this problem when updating MySQLdb on their systems and won't see that mailing list post. Could you please document this somewhere so people updating their system will be aware of it? Thanks! Michael
http://sourceforge.net/p/mysql-python/bugs/115/
CC-MAIN-2014-52
refinedweb
375
68.47
Good news everyone: IntelliJ IDEA 2018.1 is now ready for Public Preview! The upcoming v2018.1 will bring a lot of important improvements: support for Git partial commits, inline external annotations, merged features from Android Studio 3.0, and many more. We are excited about all these new features, and we encourage you to take the preview build for a ride right away! Enhancements in code completion Now completion in the Stream API chains is aware of the type casts. The code completion suggests not only a completion item according to the existing call filter(String.class::isInstance), but also an automatically typecasted completion item. We have also improved the postfix code completion in the upcoming release. Now the IDE allows you to create your own Java templates or edit and rename some of the predefined Java templates at Preferences | Editor | General | Postfix Completion. Improvements in data flow analysis We’ve improved the data flow analysis to detect a wider variety of potential problems in your code. First, data flow analysis now tracks relations between variables like “greater than” and “less than”. The IDE detects when a condition is always true (or false) in all the possible code paths when the variables are compared. Another enhancement is data flow analysis now works for non-terminated stream API chains. The IDE will now warn you when you try to assign a variable to the same value it already contains. This may help you detect and then remove some redundant code. The IDE also warns you about modifications of immutable collections. Read this blog post for more details an all the enhancements in data flow analysis. As always, the upcoming 2018.1 release has a bagful of new inspections and quick fixes. Now, IntelliJ IDEA detects and warns you about while-loops with an idempotent body, as in most cases this indicates a programming error and can lead to a program hang. Also, the IDE now detects while-loops with a conditional break at the end or beginning of an infinite loop. It offers a quick-fix to replace a break condition with a loop condition, because in most cases it’ll make your code look clearer. The upcoming IntelliJ IDEA now warns you about any infinite streams that weren’t short-circuited, as such operations can be completed only by throwing an exception. Such code may result in an infinite loop or a running out of memory issue. You can now sort the array content alphabetically. If there is a copy constructor that doesn’t copy all the fields in a class, you’ll get a notification about it. Note that the IDE considers fields with a transient modifier unnecessary to copy. The upcoming IntelliJ IDEA now warns you about an explicitly redundant close() call and provides a handy quick-fix to remove it. The upcoming IntelliJ IDEA features Java 9 specific inspections and quick-fixes. The IDE checks that a service loaded by ServiceLoader is declared in the module-info.java file and provides a quick-fix to add a missing statement to the module-info.java file. For an unresolved class mentioned in module-info.java, the IDE now suggests creating that missing class. It suggests creating missing exported packages as well. (The IDE creates the package with the class in the required directory, as you can’t export an empty package in Java 9.) Now when there are several different approaches on how to fix possible problems in the chosen scope, you can group all the suggested quick-fixes by their quick-fix type. To do this, click the Fix partially button in the Inspection Results Tool Window. JUnit 5 @Tag annotation support The upcoming IntelliJ IDEA 2018.1 now supports the JUnit5 @Tag annotation to let you include it in the testing scope, tagged classes, and tagged methods. Select the Tags (JUnit 5) option in the test kind field in the Run/Debug Configuration dialog. Use the Uniqueld field to filter tests according to their id. Code Generation When you generate a test class in IntelliJ IDEA, by default it adds the Test suffix to the test class name. Now it’s possible to customize a test class template so that a test class is created with a Test prefix in the test class name. Adjust this in Preferences | Editor | Code Style | Java | Code Generation. JVM Debugger The new Throw Exception action now allows you to throw an exception from a certain location in your program without changing the code. It is available from the Run | Throw Exception menu, or the frame context menu during a debugging session. Print breakpoint stacktraces The upcoming IntelliJ IDEA 2018.1 allows you to print breakpoints Stacktraces to the console. You can enable the Stacktrace option in the Breakpoints dialog box. The IDE also provides you with an ability to observe multiple breakpoints Stacktraces at the same time in the Console log. Also, you can now copy the current thread stack trace via a new Copy Stack action which is available from the frame context menu. Java Compiler There is a new Use --release option for cross-compilation (Java 9 and later) check-box on the Java Compiler page at Preferences | Build, Execution, Deployment | Compiler | Java Compiler that is enabled by default. When you need to use the --source and --target options with Java 9 and link against Java 9 classes at the same time you now can disable the new checkbox. Now you can also use a specific version of the ECJ compiler. Select Eclipse from the Use Compiler drop-down menu, and specify the path to the jar with the compiler. Editor, but now it shows these external annotations inline in your code. IntelliJ IDEA now lets you view the automatic inferences of @NotNull or @Nullable annotations right in your source code (not only in the gutter icon near the inferred annotation, as it was before). You can enable the Show inferred annotations inline check-box in the Preferences | Editor | General | Appearance. If there are any problems in your code, the upcoming IntelliJ IDEA 2018.1 will let you find them quickly. The IDE now highlights the folded code regions that contain errors or warnings, and colors such blocks according to their validation status. The IDE also highlights the folded code regions if they contain any matching occurrences when you search through the current file. When you place the caret on an identifier and the IDE highlights its usages, you can now use the new Alt + Wheel down or Alt + Wheel up shortcuts to jump to the next or previous identifier occurrence. Project Configuration There is a new Include dependencies with “Provided” scope option for the Application and Spring Boot configurations in the Run/Debug Configurations dialog. This new feature allows you to add “provided” dependencies to the classpath when needed. Please note that the Include dependencies with “Provided” scope option is enabled by default for Spring Boot applications. The new release will also let you change qualified names for several modules at the same time, by using the new Change Module Names… action from the context menu of the Project Structure dialog. Replace improvements In IntelliJ IDEA 2018.1, you’ll be able to preview a regex replacement in the Replace in Path window. Structural Search enhancements We’ve improved Structural Search to help you find method calls to annotated methods. In the Structural Search dialog, you can create your own search template or choose from the existing search templates. In the following example, the Structural Search finds all method calls to methods marked as @Deprecated. Groovy For Groovy files and modules, a new refactoring action is available from the context menu in Refactor | Convert to @CompileStatic. The Convert to @CompileStatic action annotates every groovy class in the scope of the @CompileStatic annotation. Android Here is some long awaited news for Android Developers! The upcoming IntelliJ IDEA 2018.1 merges the changes from Android Studio 3.0 and brings in dozens of new features. Here are the major new ones: First, IntelliJ IDEA now supports the latest Android Oreo APIs, and lets you build Java 8 Android applications as well as Kotlin Android applications. Second, the IDE now supports Gradle 3.0.0 for Android applications. The Layout Editor has been improved with a new toolbar layout and icons, updated layouts in the component tree, a new error panel, and more. Now you can create App Icons with the updated Image Asset Studio. Right-click the res folder in your Android project, and select New | Image Asset from the context menu. In the Asset Studio window, select Launcher Icons (Adaptive and Legacy) as the icon type. The IDE now supports building Instant Apps – lightweight Android apps that can be run without being installed. Before building Instant Apps, make sure that the Instant Apps Development SDK is installed. You can check which SDK tools are installed if you need to, in Preferences | Appearance & Behavior | System Settings | Android SDK in the SDK tab. The new Device File Explorer Tool Window displays the file and directory structure of your Android device or emulator. Use the Device File Explorer Tool Window to view, copy, or delete files on an Android device. You can access it through View | Tool Windows | Device File Explorer. The upcoming IntelliJ IDEA 2018.1 also merges Android Profiler – a brand new suite of profiling tools that provide real-time data for your app’s CPU, memory, and network activity. To learn more, please refer to the Android Studio Release Notes. Version Control System One of the highlights of the upcoming release is support for partial Git commits (git add -p). IntelliJ IDEA will allow you to associate the code chunks with a changelist. Create a changelist, put all the needed code chunks there, and then commit it. The IDE now commits only the selected changes from the file and skips all other changes. To add the required code chunks to a commit, use the check-boxes in the gutter of the Diff pane in the Commit Changes dialog. To move code chunks between changelists, bring up the context menu of the Diff pane in the Commit Changes dialog, and then click Move to another changelist. As another option, the IDE lets you add code chunks to a changelist from the editor by simply clicking a change marker in the gutter. Furthermore, the upcoming IntelliJ IDEA 2018.1 includes an ability to toggle the grouping of your local changes. To do this, go to the Local Changes tab of the Version Control Tool Window and look for the new Group by icon. Use it to group local changes by directory, module, or repository. Now you can select either a single grouping option, or all three at once. There are several improvements in the Log tab – the tab that’s available for Git and Mercurial VCS. The Commit Details pane of the Log tab has been redesigned. Now you can quickly navigate to a commit in the Log by clicking the corresponding commit hash in the Commit Details pane. For Git integration, we’ve improved the performance of the History for revision tab. The tab also has a refreshed UI. The Abort Rebase, Continue Rebase, and Skip Commit actions are now available from the Git Branches pop-up if there is an ongoing rebase process. The IDE has a new default shortcut to perform the Commit and Push… action from the Commit Changes dialog. Please use Alt + Cmd + K (on macOS) or Alt + Ctrl + K (on Windows and Linux). Moreover, the Clone Repository dialogs for Git and GitHub have been merged into one. Autocompletion for GitHub repositories is now available in the new Clone Repository dialog. You just need to log in to your GitHub account using the Log in to GitHub… button. We’ve also removed the SVNKit library. See this blog post for more details. Enhancements in Docker Compose The Docker Compose workflow has been improved. The Run/Debug Configurations dialog for the Docker Compose run configuration has been improved to make it possible to use important Docker Compose features such as support of multiple compose files, and the ability to choose a service to run. The Docker plugin now supports Multiple Docker Compose files and respects not only a docker-compose.yml, but also an optional docker-compose.override.yml file. You can add the docker-compose.override.yml as any other override file, right after the base configuration file. For Docker Compose files, you can now define an environment variable in the updated Run/Debug Configurations dialog. Also, if you want to use the --build command line options, enable the Force build checkbox. The Docker plugin allows you to choose the set of services to run after you choose configuration files in the Docker Compose Run configuration. The Spring Boot enhancement - Support for Spring Boot Devtools. - A new gutter icon lets you open methods with @RequestMapping annotations via the new REST client. OTHER - The IDE automatically resizes the graphics to fit the window. - During the import of an Eclipse project, IntelliJ IDEA is now able to import your code style configuration. - There is a new Open in terminal action that launches the integrated terminal on the folder’s path. - Better HiDPI support on multiple displays for Windows. Also, the JDK has been updated to 1.8.0_152-release-1136-b16, with the following fixes integrated: - Follow-up fix for the issue with running IDE on 32-bits Windows JRE-590. - Position of IME Composition windows was fixed JRE-668, JRE-669. - The issue with displaying UI after changing DPI was fixed JRE-660. With the upcoming IntelliJ IDEA 2018.1, we have completely reworked our focus subsystem. Many focus-related issues have been already fixed, such as: the Search Everywhere pop-up that now receives focus, and the Project tool window that now receives focus when invoked from the Select In pop-up and many others. Please check out this link. We expect that with the updated focus subsystem we can fix focus related issues much faster. A big thanks for all the bug reports, please keep them coming! Last but not least, the built-in SSH executable is now compatible with the new GitHub cryptographic standards. Learn more here. You can look through the full list of v2018.1 changes in the Public Preview release notes. Here are the release notes for the 181.3986.9 build. As this post has hopefully demonstrated, tons of improvements are coming in the upcoming release. Download the IntelliJ IDEA 2018.1 Public Preview build and see for yourself! We welcome your feedback, so please reach out to us in the EAP discussion forum, issue tracker, on twitter, or in the comments below. Happy Developing! Really good news. Thanks It is great! Thank you! I have some code like this, but I don’t see anything in the gutter: @RestController public class HealthCheckController { @RequestMapping(“/health”) public String healthCheck() { return “Service is running”; } } Always happy for a new release though Hi Matt, 1. Create Spring Boot Run Configuration in the Run/Debug Configurations dialog 2. Activate the Enable JMX agent checkbox in the Run/Debug Configurations dialog 3. In your pom.xml add dependency to spring-boot-starter-actuator Great update. Detail in first example. Prefer … filter(String.class::isInstance).map(String.class::cast), instead of lambda cast. Any chance we’re ever going to get the Mockito Recorder from Android Studio? Where’s MacBook’s touchbar support? We are working hard to implement TouchBar support as soon as possible and hopefully we’ll be able to show our first TouchBar implementation with IJ v2018.2. We plan to keep you posted about the progress in the youtrack issue. Please follow Where’s MacBook’s touchbar support? What do you mean touchbar support? Does IDEA break the touchbar? Good point. Touchbar as in IntelliJ uses the API to put special Intellij Touchbar buttons. Useful examples include debug buttons like step into, over, run, etc.. or a button to open Type, File. No Scala changes? Hi Grigori, work in progress for Scala. We have a dedicated blog for all Scala news: And as soon as there are some notable changes they will be published in the Scala blog. Here’s a dedicated blog about Scala improvements: The PHP and Python plugins don’t work with the new version, among many other plugins. Hi Charlie, Can you please share more details: OS, IntelliJ IDEA Edition, Build number thank you! IntelliJ IDEA 2018.1 (Ultimate Edition) Build #IU-181.4203.550, built on March 26, 2018 JRE: 1.8.0_152-release-1136-b20 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Linux 4.15.10-200.fc26.x86_64 Python plugin doesn’t work. Cannot determine module type (“PYTHON_MODULE”) for the following module:”ganetimgr” The module will be treated as a Unknown module. Django / flask project support does not work as well). Error Loading Project: Cannot load facet Django (ganetimgr) There are also UI glitches that did not exist before. I’m running awesome as my tiling window manager and I get overlapping submenus when trying to use the options bar. Also win17 / win9 / win[any-kind-of-number] shown as a header for each option menu. It seems that you need to update Python plugin: Help -> Check for Update. As for UI glitches, you can find a workaround here: Hopefully more of the focus regressions will get fixed before release. Things are getting better, but it’s still rough in places. IDEA-181572 IDEA-187610 What’s the expected GA release date ? Hi Svetlin, end of March. Regarding the new focus subsytem: For me (I’m running Arch Linux with i3) the open class/file/… popup stopped working correctly in this EAP: after typing some letters in the input box the focus jumped to the currently open file. Turning on focus.follows.mouse.workarounds solved the issue, but I think it would be good to when you had another look at The released version of IntelliJ IDEA doesn’t appear to support the Ruby plugin. Is this correct? If so, it should be mentioned, because it’s a deal breaker for me. That’s the 2018.1 release of IntelliJ IDEA, of course. Okay. I was wrong. It’s just that it installed (kept) a previous (incompatible) version of the Ruby plugin from my 2017.3.5 version of IntelliJ during migration. Don’t mind me, sorry about that confusion (on my part). Why does code completion not work for .groovy files in 2018 Intellij Ultimate? I type main and there are not suggestions. In a groovy script I type main it does show correct code completion but when I hit enter it fills in “main()” // missing String[] args // Why does a script not run when I right click on it if another completely different .groovy file has a compilation error? A script should be able to run on it’s own merit. In Eclipse I can right click on a class and create a jUnit test which will also import jUnit if needed. How do you do that quickly in intellij?
https://blog.jetbrains.com/idea/2018/02/intellij-idea-2018-1-public-preview/
CC-MAIN-2018-39
refinedweb
3,204
65.42
Idea: yjq_naiive Developer: yjq_naiive 1 sounds like the minimum value we can get. Why? Is it always true? When n ≤ 2, we can do nothing. When n ≥ 3, since , n - 1 isn't a divisor of n, so we can choose it and get 1 as the result. #include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); if (n == 2) { puts("2"); } else { puts("1"); } return 0; } Idea: yanQval Developer: yanQval Consider the number of people wearing hats of the same color. let bi = n - ai represent the number of people wearing the same type of hat of i-th person. Notice that the person wearing the same type of hat must have the same bs. Suppose the number of people having the same bi be t, there would be exactly kinds of hats with bi wearers. Therefore, t must be a multiple of bi. Also this is also sufficient, just give bi people a new hat color, one bunch at a time. #include <bits/stdc++.h> using namespace std; const int maxn = 100010; int n; pair<int,int> a[maxn]; int Ans[maxn],cnt; int main(){ ios::sync_with_stdio(false); cin>>n; for(int i=1;i<=n;i++){ cin>>a[i].first; a[i].first=n-a[i].first; a[i].second=i; } sort(a+1,a+n+1); for(int l=1,r=0;l<=n;l=r+1){ for(r=l;r<n&&a[r+1].first==a[r].first;++r); if((r-l+1)%a[l].first){ cout<<"Impossible"<<endl; return 0; } for(int i=l;i<=r;i+=a[l].first){ cnt++; for(int j=i;j<i+a[l].first;++j)Ans[a[j].second]=cnt; } } cout<<"Possible"<<endl; for(int i=1;i<=n;i++)cout<<Ans[i]<<' '; return 0; } Idea: fjzzq2002 Developer: fjzzq2002 No hint here :) Let f[i][j] be the ways that there're j bricks of a different color from its left-adjacent brick among bricks numbered 1 to i. Considering whether the i-th brick is of the same color of i - 1-th, we have f[i][j] = f[i - 1][j] + f[i - 1][j - 1](m - 1). f[1][0] = m and the answer is f[n][k]. Also, there is a possibly easier solution. We can first choose the bricks of a different color from its left and then choose a different color to color them, so the answer can be found to be simply . //quadratic #include <bits/stdc++.h> using namespace std; const int MOD=998244353; int n,m,k; long long f[2005][2005]; int main() { scanf("%d%d%d",&n,&m,&k); f[1][0]=m; for(int i=1;i<n;++i) for(int j=0;j<=k;++j) (f[i+1][j]+=f[i][j])%=MOD, (f[i+1][j+1]+=f[i][j]*(m-1))%=MOD; printf("%d\n",int(f[n][k])); } //linear #include <bits/stdc++.h> using namespace std; const int MOD=998244353; typedef long long ll; ll fac[2333],rfac[2333]; ll qp(ll a,ll b) { ll x=1; a%=MOD; while(b) { if(b&1) x=x*a%MOD; a=a*a%MOD; b>>=1; } return x; } int n,m,k; int main() { scanf("%d%d%d",&n,&m,&k); fac[0]=1; for(int i=1;i<=n;++i) fac[i]=fac[i-1]*i%MOD; rfac[n]=qp(fac[n],MOD-2); for(int i=n;i;--i) rfac[i-1]=rfac[i]*i%MOD; printf("%lld\n",m*qp(m-1,k)%MOD*fac[n-1]%MOD *rfac[k]%MOD*rfac[n-1-k]%MOD); } Idea: fateice Developer: fateice Sorry for the weak pretest. Consider the MST of the graph. Consider the minimum spanning tree formed from the n vertexes, we can find that the distance between two vertexes is the maximum weight of edges in the path between them in the minimum spanning tree (it's clear because of the correctness of Kruskal algorithm). Take any minimum spanning tree and consider some edge in this spanning tree. If this edge has all special vertexes on its one side, it cannot be the answer. Otherwise, it can always contribute to the answer, since for every special vertex, we can take another special vertex on the other side of this edge. Therefore, answers for all special vertexes are the maximum weight of the edges that have special vertexes on both sides. Besides implementing this directly, one can also run the Kruskal algorithm and maintain the number of special vertexes of each connected component in the union-find-set. Stop adding new edges when all special vertexes are connected together and the last edge added should be the answer. #include<bits/stdc++.h> #define L long long #define vi vector<int> #define pb push_back using namespace std; int n,m,t,f[100010],p; bool a[100010]; inline int fa(int i) { return f[i]==i?i:f[i]=fa(f[i]); } struct edge { int u,v,w; inline void unit() { u=fa(u); v=fa(v); if(u!=v) { if(a[u]) f[v]=u; else f[u]=v; if(a[u] && a[v]) p--; if(p==1) { for(int i=1;i<=t;i++) printf("%d ",w); printf("\n"); exit(0); } } } }x[100010]; inline bool cmp(edge a,edge b) { return a.w<b.w; } int main() { int i,j; scanf("%d%d%d",&n,&m,&t); p=t; for(i=1;i<=t;i++) { scanf("%d",&j); a[j]=1; } for(i=1;i<=m;i++) scanf("%d%d%d",&x[i].u,&x[i].v,&x[i].w); sort(x+1,x+m+1,cmp); for(i=1;i<=n;i++) f[i]=i; for(i=1;i<=m;i++) x[i].unit(); return 0; } Idea: fjzzq2002 Developer: fjzzq2002 How to solve n = 2? Let , xmax = 2 × 105. Since x2i = s2i - s2i - 1 = t2i2 - t2i - 12 ≥ (t2i - 1 + 1)2 - t2i - 12 = 2t2i - 1 + 1, so 2t2i - 1 + 1 ≤ xmax, t2i - 1 < xmax. For every , we can precalculate all possible (a, b)s so that x = b2 - a2: enumerate all possible a , then for every a enumerate b from small to large starting from a + 1 and stop when b2 - a2 > xmax, record this (a, b) for x = b2 - a2. Since , then , its complexity is . Now, we can try to find a possible s from left to right. Since x2i - 1 is positive, we need to ensure t2i - 2 < t2i - 1. Becuase x2i = t2i2 - t2i - 12, we can try all precalculated (a, b)s such that x2i = b2 - a2. If we have several choices, we should choose the one that a is minimum possible, because if the current sum is bigger, it will be harder for the remaining number to keep positive. Bonus: Solve n ≤ 103, x2i ≤ 109. t2i2 - t2i - 12 = (t2i - t2i - 1)(t2i + t2i + 1). Factor x2i. #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; int n; ll sq[100099]; #define S 200000 vector<pii> v[S+55]; int main() { for(int i=1;i<=S;++i) { if(i*2+1>S) break; for(int j=i+1;j*(ll)j-i*(ll)i<=S;++j) v[j*(ll)j-i*(ll)i].push_back(pii(i,j)); } scanf("%d",&n); for(int i=2;i<=n;i+=2) { int x; scanf("%d",&x); for(auto t:v[x]) if(sq[i-2]<t.first) { sq[i-1]=t.first,sq[i]=t.second; break; } if(!sq[i-1]) {puts("No"); return 0;} } puts("Yes"); for(int i=1;i<=n;++i) printf("%lld%c",sq[i]*(ll)sq[i]-sq[i-1] *(ll)sq[i-1]," \n"[i==n]); } #include <bits/stdc++.h> using namespace std; typedef long long ll; int n; vector<int> d[200099]; ll su[100099],x[100099]; int main() { for(int i=1;i<=200000;++i) for(int j=i;j<=200000;j+=i) d[j].push_back(i); scanf("%d",&n); for(int i=2;i<=n;i+=2) scanf("%lld",x+i); for(int i=2;i<=n;i+=2) { for(auto j:d[x[i]]) { int a=j,b=x[i]/j; if(((a+b)&1)||a>=b) continue; int s1=(b-a)/2; if(su[i-2]<(ll)s1*s1) x[i-1]=(ll)s1*s1-su[i-2]; } if(x[i-1]==0) { puts("No"); return 0; } su[i-1]=su[i-2]+x[i-1]; su[i]=su[i-1]+x[i]; } puts("Yes"); for(int i=1;i<=n;i++) printf("%lld%c",x[i]," \n"[i==n]); } 1081F - Tricky Interactor Idea: fjzzq2002 Developer: fateice, fjzzq2002 Yet another binary search? What about parity? Assuming the number of 1s changed from a to b after flipping a range of length s. Let the number of 1s in the range before this flip be be t, then b - a = (l - t) - t = s - 2t, so . So if we made a query l, r, the parities of the lengths of [1, r] and [l, n] are different, we can find out which one is actually flipped by parity of delta. Also if we only want [1, r] or [l, n] to be flipped and nothing else, we can keep querying l, r and record all the flips happened until it's the actual case (since flipping a range twice is equivalent to no flipping at all). The expected number of queries needed is 3. Let sa, b be, currently a ≡ the number of times [1, r] is flipped , b ≡ the number of times [r, n] is flipped , the expectation of remaining number of queries needed to complete our goal. Then s1, 0 = 0 (goal), we're going to find out s0, 0. s0, 0 = (s0, 1 + s1, 0) / 2 + 1, s0, 1 = (s0, 0 + s1, 1) / 2 + 1, s1, 1 = (s1, 0 + s0, 1) / 2 + 1. Solve this equation you'll get s0, 0 = 3, s0, 1 = 4, s1, 1 = 3. Since , it's easy to arrive at such arrangements. When , try to query (1, 1), (1, 1), (2, 2), (2, 2), (3, 3), (3, 3)...(n, n), (n, n) and use the method described above to flip [1, 1], [1, 1], [1, 2], [1, 2], [1, 3], [1, 3]...[1, n], [1, n]. Thus we'll know s1, s1 + s2, s1 + s2 + s3...s1 + s2 + ... + sn and s becomes obvious. When , try to query (2, n), (2, n), (1, 2), (1, 2), (2, 3), (2, 3)...(n - 1, n), (n - 1, n) and use the method described above to flip [2, n], [2, n], [1, 2], [1, 2][1, 3], [1, 3]...[1, n], [1, n]. Thus we'll know s2 + s3 + ... + sn, s1 + s2, s1 + s2 + s3...s1 + s2 + ... + sn and s also becomes obvious. Also, we can flip every range only once instead of twice by recording whether every element is currently flipped or not, although it will be a bit harder to write. #include <bits/stdc++.h> using namespace std; int n,ss[10005],sn=0,q[333]; bool tf(int l,int r) { cout<<"? "<<l<<" "<<r<<endl<<flush; cin>>ss[++sn]; return (ss[sn]-ss[sn-1])&1; } int main() { cin>>n>>ss[0]; q[n]=ss[0]; for(int i=1;i<n;++i) { int j=i-n%2; if(j==0) { int t[2]={0,0},u=ss[sn]; while(t[0]!=1||t[1]!=0) t[tf(2,n)]^=1; int v=ss[sn]; q[i]=q[n]-(n-1-v+u)/2; while(t[0]||t[1]) t[tf(2,n)]^=1; } else { int t[2]={0,0},u=ss[sn]; while(t[0]!=1||t[1]!=0) t[(tf(j,i)^i)&1]^=1; int v=ss[sn]; q[i]=(i-v+u)/2; while(t[0]||t[1]) t[(tf(j,i)^i)&1]^=1; } } cout<<"! "; for(int i=1;i<=n;++i) printf("%d",q[i]-q[i-1]); cout<<endl<<flush; } 1081G - Mergesort Strikes Back Idea: quailty Developer: fateice, fjzzq2002, yjq_naiive How does "merge" work? What is this "mergesort" actually doing? First, consider how "merge" will work when dealing with two arbitrary arrays. Partition every array into several blocks: find all elements that are larger than all elements before them and use these elements as the start of the blocks. Then, by 'merging' we're just sorting these blocks by their starting elements. (This is because that when we decided to put the start element of a block into the result array, the remaining elements in the block will be sequentially added too since they're smaller than the start element) Now back to the merge sort. What this "mergesort" doing is basically dividing the array into several segments (i.e. the ranges reaching the depth threshold). In every segment, the relative order stays the same when merging, so the expected number of inversions they contribute is just (for a segment of length l). Again suppose every segment is divided into blocks aforementioned, we're just sorting those blocks altogether by the beginning elements. Let's consider inversions formed from two blocks in two different segments. Say the elements forming the inversion are initially the i-th and j-th of those two segments (from left to right), then the blocks they belong start from the maximum of the first i-th and the first j-th of those two segments. Consider the maximum among these i + j numbers, if it is one of these two elements, the inversion can't be formed. The probability that the maximum is neither i nor j is , and if the maximum is chosen, there are 50% percent of odds that the order of i and j is different from that of two maximums, because these two elements' order can be changed by swapping these two elements while leaving the maximums' order unchanged. So their probability of forming an inversion is just . Enumerate two blocks and i and precalculate the partial sum of reciprocals, we can calculate the expectation of inversions formed from these two blocks in O(n) time. However, there might be O(n) blocks. But there is one more property for this problem: those segments are of at most two different lengths. By considering same length pairs only once, we can get a O(n) or solution. Do an induction on k. Suppose for k - 1 we have only segments of length a and a + 1. If 2|a, let a = 2t, from 2t and 2t + 1 only segments of length t and t + 1 will be formed. Otherwise, let a = 2t + 1, from 2t + 1 and 2t + 2 still only segments of length t and t + 1 will be formed. Bonus: solve this problem when the segments' length can be arbitary and n ≤ 105. #include <bits/stdc++.h> using namespace std; typedef long long ll; #define fi first #define se second #define SZ 123456 int n,k,MOD,ts[SZ],tn=0; ll inv[SZ],invs[SZ]; ll qp(ll a,ll b) { ll x=1; a%=MOD; while(b) { if(b&1) x=x*a%MOD; a=a*a%MOD; b>>=1; } return x; } void go(int l,int r,int h) { if(h<=1||l==r) ts[++tn]=r-l+1; else { int m=(l+r)>>1; go(l,m,h-1); go(m+1,r,h-1); } } map<ll,int> cnt; ll calc(int a,int b) { ll ans=a*(ll)b%MOD; for(int i=1;i<=a;++i) ans-=(invs[i+b]-invs[i])*2LL,ans%=MOD; return ans; } int main() { scanf("%d%d%d",&n,&k,&MOD); for(int i=1;i<=max(n,2);++i) inv[i]=qp(i,MOD-2), invs[i]=(invs[i-1]+inv[i])%MOD; go(1,n,k); ll ans=0; for(int i=1;i<=tn;++i) ++cnt[ts[i]],ans+=ts[i]*(ll)(ts[i]-1)/2,ans%=MOD; for(auto t:cnt) if(t.se>=2) ans+=calc(t.fi,t.fi)*((ll)t.se*(t.se-1)/2%MOD),ans%=MOD; for(auto a:cnt) for(auto b:cnt) if(a.fi<b.fi) ans+=calc(a.fi,b.fi)*((ll)a.se*b.se%MOD),ans%=MOD; ans=ans%MOD*inv[2]%MOD; ans=(ans%MOD+MOD)%MOD; printf("%d\n",int(ans)); } 1081H - Palindromic Magic Idea: fjzzq2002 Developer: fjzzq2002, yjq_naiive This problem is quite educational and we didn't expect anyone to pass. :P What will be counted twice? Warning: This editorial is probably new and arcane for ones who are not familiar with this field. If you just want to get a quick idea about the solution, you can skip all the proofs (they're wrapped in spoiler tags). Some symbols: All indices of strings start from zero. xR stands for the reverse of string x. (e.g. 'abc'R = 'cba'), xy stands for concatenation of x and y. (e.g. x = 'a', y = 'b', xy = 'ab'), xa stands for concatenation of a copies of x (e.g. x = 'ab', x2 = 'abab'). x[a, b] stands for the substring of x starting and ending from the a-th and b-th character. (e.g. 'abc'[1, 2] = 'bc') Border of x: strings with are common prefix & suffix of x. Formally, x has a border of length t (x[0, t - 1]) iff xi = x|x| - t + i ( ). Period of x: x has a period of length t iff xi = xi + t (0 ≤ i < |x| - t). When t||x| we also call t a full period. From the formulas it's easy to see x has a period of length t iff x has a border of length |x| - t. ( ) Power: x is a power iff the minimum full period of x isn't |x|. e.g. abab is a power. Lemma 1 (weak periodicity lemma): if p and q are periods of s, p + q ≤ |s|, gcd(p, q) is also a period of s. Suppose p < q, d = q - p. If |s| - q ≤ i < |s| - d, si = si - p = si + d. If 0 ≤ i < |s| - q, si = si + q = si + q - p = si + d. So q - p is also a period. Using Euclid algorithm we can get gcd(p, q) is a period. Lemma 2: Let S be the set of period lengths ≤ |s| / 2 of s, if S is non-empty, . Let min S = v, since v + u ≤ |s|, gcd(v, u) is also a valid period, so gcd(v, u) ≥ v, v|u. Let border(x) be the longest (not-self) border of x. e.g. border('aba') = 'a', border('ab') = ". If x is a palindrome, its palindromic prefix and suffix must be its border. Therefore, its (not-self) longest palindromic prefix (suffix) is border(x). Let |x| = a, x has a border of length b iff xi = xa - b + i ( ), x has a palindromic prefix of length b iff xi = xb - 1 - i ( ). Since xi = xa - 1 - i, they are just the same. If S = pq, p and q are palindromic and non-empty, we call (p, q) a palindromic decomposition of S. If S = pq, p and q are palindromic, q is non-empty (p can be empty) we call (p, q) a non-strict palindromic decomposition of S. Lemma 3: if S = x1 x2 = y1 y2 = z1 z2, |x1| < |y1| < |z1|, x2, y1, y2, z1 are palindromic and non-empty, then x1 and z2 are also palindromic. Let z1 = y1 v. vR is a suffix of y2, also a suffix of x2. So v is a prefix of x2, then x1v is a prefix of z1. Since y1 is a palindromic prefix of z1, z1 = y1 v, |v| is a period of z1. Since x1v is a prefix, so |v| is also a period of x1 v. Suppose t be some arbitary large number (you can think of it as ∞), then x1 is a suffix of vt. Since vR is prefix of z1, x1 is a prefix of (vR)t. So x1R is a suffix of vt, then x1 = x1R, so x1 is palindromic. z2 is palindromic similarly. Lemma 4: Suppose S has some palindromic decomposition. Let the longest palindromic prefix of S be a, S = ax, longest palindromic suffix of S be b, S = yb. At least one of x and y is palindromic. If none of them are palindromic, let S = pq be a valid palindromic decomposition of S, then S = yb = pq = ax, by Lemma 3, contradiction. Lemma 5: S = p1 q1 = p2 q2 (|p1| < |p2|, p1, q1, p2, q2 are palindromic, q1 and q2 are non-empty), then S is a power. We prove this by proving gcd(|p2| - |p1|, |S|) is a period. Let |S| = n, |p2| - |p1| = t. Because p1 is a palindromic prefix of p2, t is a period of p2. Similarly t is a period of q1. Since they have a common part of length t (namely S[p1, p2 - 1]), t is a period of S. So t is a period of S. For , sx = s|p2| - 1 - x = sn - 1 + |p1| - (|p2| - 1 - x) = sn - t + x (first two equations are because p2 and q1 and palindromic). So n - t is also a period of S. Since t + n - t = n, gcd(t, n - t) = gcd(t, n) is also a period of S. (weak periodicity lemma) Lemma 6: Let S = p1 q1 = p2 q2 = ... = pt qt be all non-strict palindromic decompositions of S, h be the minimum full period of S. When t ≠ 0, t = |S| / h. From Lemma 5, it's clear that h = |S| iff t = 1. In the following t ≥ 2 is assumed. Let α = S[0, h - 1], because α is not a power (otherwise s will have smaller full period), α has at most one non-strict palindromic decomposition (from Lemma 5). Let S = pq be any non-strict palindromic decomposition, then max(|p|, |q|) ≥ h. When |p| ≥ h, α = p[0, h - 1], so , then is palindromic. Similarly is also palindromic. When |q| ≥ h similar arguments can be applied. Therefore, and is a non-strict palindromic decomposition of α. Therefore, α has a non-strict palindromic decomposition. Let its only non-strict palindromic decomposition be α[0, g - 1] and α[g, h - 1]. Therefore, every pi must satisfy , so t ≤ |s| / h. Also, these all |s| / h decompositions can be obtained. Lemma 7: Let S = p1 q1 = p2 q2 = ... = pt qt be all non-strict palindromic decompositions of S. (|pi| < |pi + 1|) For every , at least one of pi = border(pi + 1) and qi + 1 = border(qi) is true. Instead of proving directly, we first introduce a way to compute all decompositions. Let the longest palindromic prefix of S be a (a ≠ S), S = ax, longest palindromic suffix of S be b (it may be S), S = yb. If x = b obviously S = ab is the only way to decompose. If S = pq and p ≠ a, q ≠ b, p and q are palindromic, by Lemma 3 we have x, y are also palindromic. So if neither x or y is palindromic, then S can't be composed to two palindromes. If exactly one of x and y is palindromic, it's the only way to decompose S. If both of them are palindromic, we can then find the second-longest non-self palindromic prefix of S: c. Let S = cz, if z is not palindromic or c = y, then S = ax = yb are the only non-strict palindromic decompositions. Otherwise, we can find all palindromic suffix of |S| whose lengths between |z| and |b|, their prefixes must also be palindromic (using Lemma 3 for ax and cz), then S = ax = cz = ... = yb (other palindromic suffixes and their corresponding prefixes are omitted) Back to the proof of Lemma 7, the only case we need to prove now is S = ax = yb. Suppose the claim is incorrect, let p = border(a), s = border(y), S = ax = pq = rs = yb, (|a| > |p| > |y|, |a| > |r| > |y|, p and s are palindromic) Continuing with the proof of Lemma 6, since t = 2, S = α2. If |p| ≥ |α|, , so q would also be palindromic, contradiction. Therefore, |p| < |α| and similarly |s| < |α|. Let α = pq' = r's and the non-strict palindromic decomposition of α be α = βθ. Since α = pq' = βθ = r's, by Lemma 3 q' and r' should also be palindromic, contradiction. Lemmas are ready, let's start focusing on this problem. A naive idea is to count the number of palindromes in A and in B, and multiply them. This will obviously count a string many times. By Lemma 7, suppose S = xy, to reduce counting, we can check if using border(x) or border(y) to replace x or y can also achieve S. If any of them do, reduce the answer by 1, then we're done. So for a palindromic string x in A, we want to count strings that are attainable from both x and border(x) and subtract from the answer. Finding x and border(x) themselves can be simply done by the palindromic tree. Let x = border(x)w, we want to count Ts in B that T = wS and both T and S are palindromic. Since |w| is the shortest period of x, w can't be a power. If |w| > |S|, w = S + U. S are U are both palindromes. Since w is not a power, it can be decomposed to be two palindromes in at most one way (Lemma 5). We can find that only way (by checking maximal palindromic suffix & prefix) and use hashing to check if it exists in B. If |w| ≤ |S|, if S is not maximum palindromic suffix of T, w must be a power (Lemma 2), so we only need to check maximum palindromic suffixes (i.e. S = border(T)). We need to do the similar thing to ys in B, then adding back both attainable from border(x) and border(y). Adding back can be done in a similar manner, or directly use hashing to find all matching w s. Finding maximal palindromic suffix and prefix of substrings can be done by binary-lifting on two palindromic trees (one and one reversed). Let upi, j be the resulting node after jumping through fail links for 2j steps from node i. While querying maximal palindromic suffix for s[l, r], find the node corresponding to the maximal palindromic suffix of s[1, r] (this can be stored while building palindromic tree). If it fits into s[l, r] we're done. Otherwise, enumerate j from large to small and jump 2j steps (with the help of up) if the result node is still unable to fit into s[l, r], then jump one more step to get the result. #include <bits/stdc++.h> using namespace std; const int N = 234567; const int LOG = 18; const int ALPHA = 26; const int base = 2333; const int md0 = 1e9 + 7; const int md1 = 1e9 + 9; struct hash_t { int hash0, hash1; hash_t(int hash0 = 0, int hash1 = 0):hash0(hash0), hash1(hash1) { } hash_t operator + (const int &x) const { return hash_t((hash0 + x) % md0, (hash1 + x) % md1); }; hash_t operator * (const int &x) const { return hash_t((long long)hash0 * x % md0, (long long)hash1 * x % md1); } hash_t operator + (const hash_t &x) const { return hash_t((hash0 + x.hash0) % md0, (hash1 + x.hash1) % md1); }; hash_t operator - (const hash_t &x) const { return hash_t((hash0 + md0 - x.hash0) % md0, (hash1 + md1 - x.hash1) % md1); }; hash_t operator * (const hash_t &x) const { return hash_t((long long)hash0 * x.hash0 % md0, (long long)hash1 * x.hash1 % md1); } long long get() { return (long long)hash0 * md1 + hash1; } } ha[N], hb[N], power[N]; struct palindrome_tree_t { int n, total, p[N], pos[N], value[N], parent[N], go[N][ALPHA], ancestor[LOG][N]; char s[N]; palindrome_tree_t() { parent[0] = 1; value[1] = -1; total = 1; p[0] = 1; } int extend(int p, int w, int n) { while (s[n] != s[n - value[p] - 1]) { p = parent[p]; } if (!go[p][w]) { int q = ++total, k = parent[p]; while (s[n] != s[n - value[k] - 1]) { k = parent[k]; } value[q] = value[p] + 2; parent[q] = go[k][w]; go[p][w] = q; pos[q] = n; } return go[p][w]; } void init() { for (int i = 1; i <= n; ++i) { p[i] = extend(p[i - 1], s[i] - 'a', i); } for (int i = 0; i <= total; ++i) { ancestor[0][i] = parent[i]; } for (int i = 1; i < LOG; ++i) { for (int j = 0; j <= total; ++j) { ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]]; } } } int query(int r, int length) { r = p[r]; if (value[r] <= length) { return value[r]; } for (int i = LOG - 1; ~i; --i) { if (value[ancestor[i][r]] > length) { r = ancestor[i][r]; } } return value[parent[r]]; } bool check(int r, int length) { r = p[r]; for (int i = LOG - 1; ~i; --i) { if (value[ancestor[i][r]] >= length) { r = ancestor[i][r]; } } return value[r] == length; } } A, B, RA, RB; map<long long, int> fa, fb, ga, gb; long long answer; char a[N], b[N]; int n, m; hash_t get_hash(hash_t *h, int l, int r) { return h[r] - h[l - 1] * power[r - l + 1]; } int main() { #ifdef wxh010910 freopen("input.txt", "r", stdin); #endif scanf("%s %s", a + 1, b + 1); n = strlen(a + 1); m = strlen(b + 1); A.n = RA.n = n; B.n = RB.n = m; for (int i = 1; i <= n; ++i) { A.s[i] = RA.s[n - i + 1] = a[i]; ha[i] = ha[i - 1] * base + a[i]; } for (int i = 1; i <= m; ++i) { B.s[i] = RB.s[m - i + 1] = b[i]; hb[i] = hb[i - 1] * base + b[i]; } power[0] = hash_t(1, 1); for (int i = 1; i <= max(n, m); ++i) { power[i] = power[i - 1] * base; } A.init(); B.init(); RA.init(); RB.init(); answer = (long long)(A.total - 1) * (B.total - 1); for (int i = 2; i <= A.total; ++i) { ++fa[get_hash(ha, A.pos[i] - A.value[i] + 1, A.pos[i]).get()]; int p = A.parent[i]; if (p < 2) { continue; } int l = A.pos[i] - (A.value[i] - A.value[p]) + 1, r = A.pos[i]; if (A.value[i] <= A.value[p] << 1) { ++ga[get_hash(ha, l, r).get()]; } } for (int i = 2; i <= B.total; ++i) { ++fb[get_hash(hb, B.pos[i] - B.value[i] + 1, B.pos[i]).get()]; int p = B.parent[i]; if (p < 2) { continue; } int l = B.pos[i] - B.value[i] + 1, r = B.pos[i] - B.value[p]; if (B.value[i] <= B.value[p] << 1) { ++gb[get_hash(hb, l, r).get()]; } } for (int i = 2; i <= A.total; ++i) { int p = A.parent[i]; if (p < 2) { continue; } int l = A.pos[i] - (A.value[i] - A.value[p]) + 1, r = A.pos[i]; long long value = get_hash(ha, l, r).get(); if (gb.count(value)) { answer -= gb[value]; } int longest_palindrome_suffix = A.query(r, r - l + 1); if (longest_palindrome_suffix == r - l + 1) { continue; } if (RA.check(n - l + 1, r - l + 1 - longest_palindrome_suffix)) { int length = r - l + 1 - longest_palindrome_suffix; if (fb.count(get_hash(ha, l, l + length - 1).get()) && fb.count((get_hash(ha, l, r) * power[length] + get_hash(ha, l, l + length - 1)).get())) { --answer; } continue; } int longest_palindrome_prefix = RA.query(n - l + 1, r - l + 1); if (A.check(r, r - l + 1 - longest_palindrome_prefix)) { int length = longest_palindrome_prefix; if (fb.count(get_hash(ha, l, l + length - 1).get()) && fb.count((get_hash(ha, l, r) * power[length] + get_hash(ha, l, l + length - 1)).get())) { --answer; } continue; } } for (int i = 2; i <= B.total; ++i) { int p = B.parent[i]; if (p < 2) { continue; } int l = B.pos[i] - B.value[i] + 1, r = B.pos[i] - B.value[p]; long long value = get_hash(hb, l, r).get(); if (ga.count(value)) { answer -= ga[value]; } int longest_palindrome_suffix = B.query(r, r - l + 1); if (longest_palindrome_suffix == r - l + 1) { continue; } if (RB.check(m - l + 1, r - l + 1 - longest_palindrome_suffix)) { int length = longest_palindrome_suffix; if (fa.count(get_hash(hb, r - length + 1, r).get()) && fa.count((get_hash(hb, r - length + 1, r) * power[r - l + 1] + get_hash(hb, l, r)).get())) { --answer; } continue; } int longest_palindrome_prefix = RB.query(m - l + 1, r - l + 1); if (B.check(r, r - l + 1 - longest_palindrome_prefix)) { int length = r - l + 1 - longest_palindrome_prefix; if (fa.count(get_hash(hb, r - length + 1, r).get()) && fa.count((get_hash(hb, r - length + 1, r) * power[r - l + 1] + get_hash(hb, l, r)).get())) { --answer; } continue; } } for (int i = 2; i <= A.total; ++i) { int p = A.parent[i]; if (p < 2) { continue; } int l = A.pos[i] - (A.value[i] - A.value[p]) + 1, r = A.pos[i]; if (A.value[i] > A.value[p] << 1) { ++ga[get_hash(ha, l, r).get()]; } } for (int i = 2; i <= B.total; ++i) { int p = B.parent[i]; if (p < 2) { continue; } int l = B.pos[i] - B.value[i] + 1, r = B.pos[i] - B.value[p]; if (B.value[i] > B.value[p] << 1) { ++gb[get_hash(hb, l, r).get()]; } } for (auto p : ga) { answer += (long long)p.second * gb[p.first]; } printf("%lld\n", answer); return 0; } Hope you enjoyed the round! See you next time!
https://codeforces.com/topic/64282/en6
CC-MAIN-2019-09
refinedweb
5,576
73.58
The Q3Header class provides a header row or column, e.g. for tables and listviews. More... #include <Q3Header> This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information. The Q3Header class provides a header row or column, e.g. for tables and listviews. This class provides a header, e.g. a vertical header to display row labels, or a horizontal header to display column labels. It is used by Q3Table and Q3ListView for example. A header is composed of one or more sections, each of which can display a text label and an icon. A sort indicator (an arrow) can also be displayed using setSortIndicator(). Sections are added with addLabel() and removed with removeLabel(). The label and icon33. See also Q3ListView and Q3Table. This property holds the number of sections in the header. Access functions: This property holds whether the header sections can be moved. If this property is true (the default) the user can move sections. If the user moves a section the indexChange() signal is emitted. Access functions: See also setClickEnabled() and setResizeEnabled(). This property holds the header's left-most (or top-most) visible pixel. Setting this property will scroll the header so that offset becomes the left-most (or top-most for vertical headers) visible pixel. Access functions: This property holds the header's orientation. The orientation is either Qt::Vertical or Qt::Horizontal (the default). Call setOrientation() before adding labels if you don't provide a size parameter otherwise the sizes will be incorrect. Access functions: This property holds whether the header sections always take up the full width (or height) of the header. Access functions: This property holds whether the sizeChange() signal is emitted continuously. If tracking is on, the sizeChange() signal is emitted continuously while the mouse is moved (i.e. when the header is resized), otherwise it is only emitted when the mouse button is released at the end of resizing. Tracking defaults to false. Access functions: Constructs a horizontal header called name, with parent parent. Constructs a horizontal header called name, with n sections and parent parent. Destroys the header and all its sections. Adds a new section with label text s. Returns the index position where the section was added (at the right for horizontal headers, at the bottom for vertical headers). The section's width is set to size. If size < 0, an appropriate size for the text s is chosen. This is an overloaded function. Adds a new section with icon icon and label text s. Returns the index position where the section was added (at the right for horizontal headers, at the bottom for vertical headers). The section's width is set to size, unless size is negative in which case the size is calculated taking account of the size of the text. Adjusts the size of the sections to fit the size of the header as completely as possible. Only sections for which isStretchEnabled() is true will be resized. Returns the index at which the section is displayed, which contains pos in widget coordinates, or -1 if pos is outside the header sections. Use sectionPos() instead. Returns the position in pixels of the section that is displayed at the index i. The position is measured from the start of the header. Use sectionSize() instead. Returns the size in pixels of the section that is displayed at the index i. See also setCellSize(). Reimplemented from QWidget::changeEvent(). If isClickEnabled() is true, this signal is emitted when the user clicks section section. See also pressed() and released(). Returns the total width of all the header columns. Returns the icon set for section section. If the section does not exist, 0 is returned. This signal is emitted when the user moves section section from index position fromIndex, to index position toIndex. Returns true if section section is clickable; otherwise returns false. If section is out of range (negative or larger than count() - 1): returns true if all sections are clickable; otherwise returns false. See also setClickEnabled(). Returns true if section section is resizeable; otherwise returns false. If section is -1 then this function applies to all sections, i.e. returns true if all sections are resizeable; otherwise returns false. See also setResizeEnabled(). Reimplemented from QWidget::keyPressEvent(). Reimplemented from QWidget::keyReleaseEvent(). Returns the text for section section. If the section does not exist, returns an empty string. Use mapToIndex() instead. Translates from logical index l to actual index (index at which the section l is displayed) . Returns -1 if l is outside the legal range. See also mapToLogical(). Returns the index position at which section section is displayed. Use mapToSection() instead. Translates from actual index a (index at which the section is displayed) to logical index of the section. Returns -1 if a is outside the legal range. See also mapToActual(). Returns the number of the section that is displayed at index position index. Reimplemented from QWidget::mouseDoubleClickEvent(). Reimplemented from QWidget::mouseMoveEvent(). Reimplemented from QWidget::mousePressEvent(). Reimplemented from QWidget::mouseReleaseEvent(). Use moveSection() instead. Moves the section that is currently displayed at index fromIdx to index toIdx. Moves section section to index position toIndex. Use indexChange() instead. This signal is emitted when the user has moved the section which is displayed at the index fromIndex to the index toIndex. Reimplemented from QWidget::paintEvent(). Paints the section at position index, inside rectangle fr (which uses widget coordinates) using painter p. Calls paintSectionLabel(). Paints the label of the section at position index, inside rectangle fr (which uses widget coordinates) using painter p. Called by paintSection() This signal is emitted when the user presses section section down. This signal is emitted when section section is released. Removes section section. If the section does not exist, nothing happens. Reimplemented from QWidget::resizeEvent(). Resizes section section to s pixels wide (or high). Returns the rectangle covered by the section at index index. Returns the index of the section which contains the position pos given in pixels from the left (or top). This signal is emitted when a part of the header is clicked. index is the index at which the section is displayed. In a list view this signal would typically be connected to a slot that sorts the specified column (or row). This signal is emitted when the user doubleclicks on the edge (handle) of section section. Returns the position (in pixels) at which the section starts. Returns the rectangle covered by section section. Returns the width (or height) of the section in pixels. Use resizeSection() instead. Sets the size of the section section to s pixels. Warning: does not repaint or send out signals If enable is true, any clicks on section section will result in clicked() signals being emitted; otherwise the section will ignore clicks. If section is -1 (the default) then the enable value is set for all existing sections and will be applied to any new sections that are added. See also isClickEnabled(), setMovingEnabled(), and setResizeEnabled(). Sets the text of section section to s. The section's width is set to size if size >= 0; otherwise it is left unchanged. Any icon set that has been set for this section remains unchanged. If the section does not exist, nothing happens. This is an overloaded function. Sets the icon for section section to icon and the text to s. The section's width is set to size if size >= 0; otherwise it is left unchanged. If the section does not exist, nothing happens. If enable is true the user may resize section section; otherwise the section may not be manually resized. If section is negative (the default) then the enable value is set for all existing sections and will be applied to any new sections that are added. Example: // Allow resizing of all current and future sections header->setResizeEnabled(true); // Disable resizing of section 3, (the fourth section added) header->setResizeEnabled(false, 3); If the user resizes a section, a sizeChange() signal is emitted. See also isResizeEnabled(), setMovingEnabled(), setClickEnabled(), and setTracking(). Sets a sort indicator onto the specified section. The indicator's order is either Ascending or Descending. Only one section can show a sort indicator at any one time. If you don't want any section to show a sort indicator pass a section number of -1. See also sortIndicatorSection() and sortIndicatorOrder(). This is an overloaded function. Sets the sort indicator to ascending. Use the other overload instead. Reimplemented from QWidget::showEvent(). This signal is emitted when the user has changed the size of a section from oldSize to newSize. This signal is typically connected to a slot that repaints the table or list that contains the header. Reimplemented from QWidget::sizeHint(). Returns the implied sort order of the Q3Headers sort indicator. See also setSortIndicator() and sortIndicatorSection(). Returns the section showing the sort indicator or -1 if there is no sort indicator. See also setSortIndicator() and sortIndicatorOrder().
https://doc.qt.io/archives/qt-4.7/q3header.html
CC-MAIN-2021-17
refinedweb
1,502
60.72
Converts a string to an integer #include <stdlib.h> int atoi ( const char *s ); long atol ( const char *s ); long long atoll ( const char *s ); (C99) The atoi( ) function converts a string of characters representing a numeral into a number of int. Similarly, atol( ) returns a long integer, and in C99, the atoll( ) function converts a string into an integer of type long long. The conversion ignores any leading whitespace characters (spaces, tabs, newlines). A leading plus sign is permissible; a minus sign makes the return value negative. Any character that cannot be interpreted as part of an integer, such as a decimal point or exponent sign, has the effect of terminating the numeral input, so that atoi( ) converts only the partial string to the left of that character. If under these conditions the string still does not appear to represent a numeral, then atoi( ) returns 0. char *s = " -135792468.00 Balance on Dec. 31"; printf("\"%s\" becomes %ld\n", s, atol(s)); These statements produce the output: " -135792468.00 Balance on Dec. 31" becomes -135792468 strtol( ) and strtoll( ); atof( ) and strtod( )
http://books.gigatux.nl/mirror/cinanutshell/0596006977/cinanut-CHP-17-15.html
CC-MAIN-2018-43
refinedweb
182
65.01
When using TinyMCE in your React project, you want a fast and reliable way to integrate it with your existing codebase. Thankfully, the Official TinyMCE React Component (tinymce-react) is provided to bring TinyMCE into the React world. In this article, we start with a simple integration. Also see how to enhance your React forms with our rich text editor in a controlled component. Creating a simple React project We’re going to start by setting up a simple React project with the Create React App tool. By using this tool to set up the boilerplate, we’ll be able to quickly dive into what we’re all here for, namely tinymce-react! If you already have a project set up, you may skip the following steps and jump directly to the next section to install the TinyMCE React component. To generate a new project, we’ll run the following command (assuming Node.js is already installed). $ npx create-react-app tinymce-react-demo NOTE: npx is a tool included with npm 5.2+ for executing packages without the need to install them. At the time of writing, the create-react-app package is version 3.2.0, but releases of create-react-app shouldn’t differ much – if you use a later version you should still be able to follow these steps. The create-react-app will scaffold our new project and automatically install all the dependencies it requires. When it has finished, we can enter the newly-created directory, fire up the application, and open it up in a browser at the address displayed on the command line. $ cd tinymce-react-demo # If you use npm $ npm run start # If you use Yarn $ yarn run start The project scaffolded by create-react-app uses Webpack and Babel under the hood, so there’s no need to set up any additional build tools. We can jump right into developing our app. Installing the TinyMCE React component To get started, we’ll need to install the tinymce-react component with our package manager of choice. # If you use npm $ npm install @tinymce/tinymce-react # If you use Yarn $ yarn add @tinymce/tinymce-react The tinymce-react component is a wrapper around TinyMCE and thus requires TinyMCE in order to do its work. By default, the component will load TinyMCE from Tiny Cloud, which is the simplest way to get going. The only thing we need for this is an API key which anyone can get for free at tiny.cloud (including a 30 day trial of the premium plugins)! The alternative is to self-host TinyMCE, making it available together with the assets it requires. Adding the Editor component to our project Our React project has a file called App.js, located at tinymce-react-demo/src/App.js, which is where we’ll add the editor in this demo. Import the Editor component from the library and add it with your desired configuration. Here we’ll add the Word Count plugin as an example, but there are many more Tiny plugins you can choose from to enhance the editor. import React from "react"; import { Editor } from "@tinymce/tinymce-react"; function App() { return ( <Editor apiKey="Get your free API key at tiny.cloud and paste it here" plugins="wordcount" /> ); } export default App; To find out more about the configuration options available, check out the documentation. On saving the file, TinyMCE will appear in your app. (You might have to refresh your browser.) What next? We now have TinyMCE running in a simple React project. Next, we’ll take TinyMCE-in-React to the next level by demonstrating how to emulate an online document editor. Also, once you’ve grabbed your API key, check out our range of premium plugins that are helping other developers create the best content creation experience for their users.
https://www.tiny.cloud/blog/how-to-add-tinymce-5-to-a-simple-react-project/
CC-MAIN-2021-39
refinedweb
643
62.78
Resampling time series data with pandas In this post, we’ll be going through an example of resampling time series data using pandas. We’re going to be tracking a self-driving car at 15 minute periods over a year and creating weekly and yearly summaries. Let’s start by importing some dependencies: import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('display.mpl_style', 'default') %matplotlib inline We’ll be tracking this self-driving car that travels at an average speed between 0 and 60 mph, all day long, all year long. We have the average speed over the fifteen minute period in miles per hour, distance in miles and the cumulative distance travelled. Our time series is set to be the index of a pandas DataFrame. range = pd.date_range('2015-01-01', '2015-12-31', freq='15min') df = pd.DataFrame(index = range) # Average speed in miles per hour df['speed'] = np.random.randint(low=0, high=60, size=len(df.index)) # Distance in miles (speed * 0.5 hours) df['distance'] = df['speed'] * 0.25 # Cumulative distance travelled df['cumulative_distance'] = df.distance.cumsum() Let’s take a look at our data: df.head() Now, let’s try and plot this data: fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(df.index, df['speed'], 'g-') ax2.plot(df.index, df['distance'], 'b-') ax1.set_xlabel('Date') ax1.set_ylabel('Speed', color='g') ax2.set_ylabel('Distance', color='b') plt.show() plt.rcParams['figure.figsize'] = 12,5 Oh dear… Not very pretty, far too many data points. Let’s start resampling, we’ll start with a weekly summary. The resample method in pandas is similar to its groupby method as you are essentially grouping by a certain time span. You then specify a method of how you would like to resample. So we’ll start with resampling the speed of our car: df.speed.resample()will be used to resample the speed column of our DataFrame - The 'W'indicates we want to resample by week. At the bottom of this post is a summary of different time frames. mean()is used to indicate we want the mean speed during this period. With distance, we want the sum of the distances over the week to see how far the car travelled over the week, in that case we use sum(). With cumulative distance we just want to take the last value as it’s a running cumulative total, so in that case we use weekly_summary = pd.DataFrame() weekly_summary['speed'] = df.speed.resample('W').mean() weekly_summary['distance'] = df.distance.resample('W').sum() weekly_summary['cumulative_distance'] = df.cumulative_distance.resample('W').last() #Select only whole weeks weekly_summary = weekly_summary.truncate(before='2015-01-05', after='2015-12-27') weekly_summary.head() Now we have weekly summary data. Let’s have a look at our plots now. fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(weekly_summary.index, weekly_summary['speed'], 'g-') ax2.plot(weekly_summary.index, weekly_summary['distance'], 'b-') ax1.set_xlabel('Date') ax1.set_ylabel('Speed', color='g') ax2.set_ylabel('Distance', color='b') plt.show() plt.rcParams['figure.figsize'] = 12,5 Much better We can do the same thing for an annual summary: annual_summary = pd.DataFrame() # AS is year-start frequency annual_summary['speed'] = df.speed.resample('AS').mean() annual_summary['distance'] = df.speed.resample('AS').sum() annual_summary['cumulative_distance'] = df.cumulative_distance.resample('AS').last() annual_summary Upsampling data How about if we wanted 5 minute data from our 15 minute data? In this case we would want to forward fill our speed data, for this we can use ffil() or pad. Our distance and cumulative_distance column could then be recalculated on these values. If we wanted to fill on the next value, rather than the previous value, we could use backward fill bfill(). five_minutely_data = pd.DataFrame() five_minutely_data['speed'] = df.speed.resample('5min').ffill() # 5 minutes is 1/12 hours five_minutely_data['distance'] = five_minutely_data['speed'] * (1/float(12)) five_minutely_data['cumulative_distance'] = five_minutely_data.distance.cumsum() five_minutely_data.head() Resampling options pandas comes with many in-built options for resampling, and you can even define your own methods. In terms of date ranges, the following is a table for common time period options when resampling a time series: These are some of the common methods you might use for resampling:
https://benalexkeen.com/resampling-time-series-data-with-pandas/
CC-MAIN-2021-21
refinedweb
703
52.87
On a recent project, I created a microservice in OKE where data was persisted in a database. ATP was the obvious choice because it is so easy to provision. The challenge was that to connect to an ATP instance a wallet is needed. This poses a security risk if you build the container image with the wallet in it. A solution is to store the wallet in HashiCorp Vault. This article explains how to store the wallet into Vault, how to setup Kubernetes auth authentication method and how setup the container to read secrets from Vault. Before following the instructions in this article, make sure you have HashiCorp Vault installed in a Kubernetes cluster or some other VM. I installed Vault in the same cluster as the application, but in vault namespace. Also, you should already have created an ATP database downloaded the wallet. In production you should have your applications deployed to your own namespace, not default namespace. But for this PoC I deployed the app to default. You need to setup some environment variables to connect to Vault. Use the root token obtained during Vault initialization $ export VAULT_ADDR='' $ export VAULT_SKIP_VERIFY="true" $ export VAULT_TOKEN=<Root Token from initialization> Then you need to configure port forwarding: $ kubectl -n namespace get vault service-name -o jsonpath='{.status.vaultStatus.active}'| xargs -0 -I {} kubectl -n namespace port-forward {} 8200You have to replace namespace and service-name with your own values. For example: $ kubectl -n vault-ns get vault safe-svc -o jsonpath='{.status.vaultStatus.active}'| xargs -0 -I {} kubectl -n vault-ns port-forward {} 8200 If you haven't created an ATP instance yet, do it now, obtain the ATP wallet zip file and then come back here. Unzip the wallet in a directory of your choice. Just make sure the directory is secure and not available to intruders. Then, using the following create a script to encode and upload the secrets to Vault. The reason for encoding is because some certificates are in binary format $ vault kv put secret/atp \ cwallet_sso=`cat cwallet.sso | base64` \ ojdbc_properties=`cat ojdbc.properties | base64` \ tnsnames_ora=`cat tnsnames.ora | base64` \ ewallet_p12=`cat ewallet.p12 | base64` \ truststore_jks=`cat truststore.jks | base64` \ atp_password_txt=`cat atp_password.txt | base64` \ keystore_jks=`cat keystore.jks | base64` \ sqlnet_ora=`cat sqlnet.ora | base64`You will notice that atp_password_txt is not part of the unzipped wallet. I added it here because it's needed later for authentication. Therefore, since it's a password it should be added to vault to avoid being available in config files and such. You can confirm that Vault now has the wallet content in the path secret/atp: $ vault kv get secret/atp Now you need to perform a series of tasks in OKE/Kubernetes so that the application running in a pod will be authorized to fetch secrets from Vault. $ kubectl -n default create sa vault-reader create file named vault-reader-binding.yaml with this content: apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: vault-reader-binding namespace: default roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: system:auth-delegator subjects: - kind: ServiceAccount name: vault-reader namespace: default Note: the system:auth-delegator is a cluster role, which allows delegated authentication and authorization checks.Run the following to create the cluster role binding: $ kubectl -n default create -f vault-reader-binding.yaml Run these commands to fetch the service account secret, jwt token (TR_ACCOUNT_TOKEN), and service account name. These will be used later when configuring Vault. If you want, you could create a script with this content: export VAULT_SA_NAME=$(kubectl -n default get sa vault-reader -o jsonpath="{.secrets[*]['name']}") export TR_ACCOUNT_TOKEN=$(kubectl -n default get secret ${VAULT_SA_NAME} -o jsonpath='{.data.token}' | base64 -D) export SA_CA_CRT=$(kubectl -n default get secret ${VAULT_SA_NAME} -o jsonpath="{.data['ca\.crt']}" | base64 -D; echo) Get the cluster address and port so you can use it later $ kubectl cluster-info Edit the application deployment yaml and add the following: service account: to associate the container with serviceAccountName. VAULT_ADDR environment variable: that points to a running instance of Vault. volume: setup a shared volume. A script in the init container reads the Vault secrets and write them to the shared volume. The java app in the main container reads the files (the wallet) in the shared volume during authentication to ATP. WALLET_LOCATION and ATP_CONNECTION_NAME: are used by the application to connect to ATP. Here is an example: spec: serviceAccountName: vault-reader containers: - name: priceservice image: iad.ocir.io/mytenancy/samplerepo/priceservice:latest imagePullPolicy: Always env: - name: WALLET_LOCATION value: /opt/data - name: ATP_CONNECT_NAME value: myATP_medium ports: - containerPort: 8080 volumeMounts: - mountPath: /opt/data name: wallet imagePullSecrets: - name: ocir volumes: - name: wallet emptyDir: {} initContainers: - name: install image: iad.ocir.io/mytenancy/samplerepo/init-container:latest command: ['sh', '-c', '/root/run_task.sh'] env: - name: VAULT_ADDR value: volumeMounts: - name: wallet mountPath: "/work-dir" Now you need to configure some attributes in Vault to trust the connection from the pod associated with the service account created above. $ vault auth enable kubernetes These environment variables were set in the steps above. You should also have obtained the address:port as already instructed. $ vault write auth/kubernetes/config \ token_reviewer_jwt=${TR_ACCOUNT_TOKEN} \ kubernetes_host=<address:port> \ kubernetes_ca_cert=${SA_CA_CRT} Create a policy file, atp-pol.hcl,which sets what kind of permissions the entity associated with this policy will have. path "secret/*" { capabilities = ["create", "read", "update", "delete", "list"] For PoC purposes this policy allows capabilities at the root path, i.e. secret/*. If you want more tight control, and you probably will, define a more specific path such as secret/atp, for example. Write the policy to Vault: $ vault policy write atp-pol atp-pol.hcl Create a role which associates the Kubernetes service account with the policy just created. $ vault write auth/kubernetes/role/atp-role \ bound_service_account_names=vault-reader \ bound_service_account_namespaces=default \ policies=atp-pol \ ttl=36h The process to obtain secrets now is simple, only two steps. First a script in the init container calls the login API, then a second call is done to fetch the secrets In the login call, the script passes the service account JWT token, which has been registered with Vault, and the atp-role. The response contains another token, which is used to communicate with Vault in subsequent calls or until the token expires. Here is an example: export VAULT_TOKEN=$(curl -k \ --request POST \ --data "{\"jwt\": \"`cat /var/run/secrets/kubernetes.io/serviceaccount/token`\", \"role\": \"atp-role\"}" \ | jq -r .auth.client_token) Then to fetch the wallet secrets, a second API call to /secret/atp will use the token from the login API call. export WALLET_JSON=$(curl -k -H "X-Vault-Token: $VAULT_TOKEN" \ -X GET $VAULT_ADDR/v1/secret/atp) The response is a JSON object that contains all the secret strings that were uploaded to /secret/atp. These strings are base64 encoded. So before writing them to the wallet folder they need to be decoded. echo $WALLET_JSON|jq -r .data.atp_password_txt|base64 -d > /work-dir/atp_password.txt echo $WALLET_JSON|jq -r .data.cwallet_sso|base64 -d > /work-dir/cwallet.sso echo $WALLET_JSON|jq -r .data.ewallet_p12|base64 -d > /work-dir/ewallet.p12 echo $WALLET_JSON|jq -r .data.keystore_jks|base64 -d > /work-dir/keystore.jks echo $WALLET_JSON|jq -r .data.ojdbc_properties|base64 -d > /work-dir/ojdbc.properties echo $WALLET_JSON|jq -r .data.sqlnet_ora|base64 -d > /work-dir/sqlnet.ora echo $WALLET_JSON|jq -r .data.tnsnames_ora|base64 -d > /work-dir/tnsnames.ora echo $WALLET_JSON|jq -r .data.truststore_jks|base64 -d > /work-dir/truststore.jks Here is a picture that illustrates the entire flow. I hope this has been useful to provide an alternative method to store ATP wallet secrets in OKE.
https://www.ateam-oracle.com/how-to-use-vault-to-store-atp-wallet
CC-MAIN-2020-16
refinedweb
1,271
50.12
Before you mark this as Duplicate, I have read the solutions to this question. In Django Admin I have lots of values. The team that works on that data, currently can use CTRL+F to atleast find the required field. To fix the UI I have the Dropdown rendering option available in the solution of the question tagged above. But, as I said I need it to be searchable. Answer I was struggling with the same problem some few weeks back. So this answer might be useful to some developers from the future. I managed to solve the problem by writing a custom template.html I have bundled the code in an amazing package now that does the same for you, here’s the link. Here’s how you can implement a Searchable Dropdown in place of the default List: 1. Installation: pip install django-admin-searchable-dropdown This command will install the latest version of the package in your project. Now, include the package in your project by adding admin_searchable_dropdown to your INSTALLED_APPS inside settings.py file. 2. Usage: Let’s say you have following models: from django.db import models class CarCompany(models.Model): name = models.CharField(max_length=128) class CarModel(models.Model): name = models.CharField(max_length=64) company = models.ForeignKey(CarCompany, on_delete=models.CASCADE) And you would like to filter results in CarModelAdmin on the basis of company. You need to define search_fields in CarCompany and then define filter like this: from django.contrib import admin from admin_searchable_dropdown.filters import AutocompleteFilter class CarCompanyFilter(AutocompleteFilter): title = 'Company' # display title field_name = 'company' # name of the foreign key field class CarCompanyAdmin(admin.ModelAdmin): search_fields = ['name'] # this is required for django's autocomplete functionality # ... class CarModelAdmin(admin.ModelAdmin): list_filter = [CarCompanyFilter] # ... After following these steps you may see the filter as: - This is how the list filter is rendered in the form of a dropdown when the package is used - And the dropdown filter is also Searchable Features Offered: - If you have large fields in Admin Filter, the sidebar gets widened, this package provides you the same list in a dropdown format, hence, no such hassle. - If you have more than, say 20, field items, list filter is now a long side-pane, just ruining the admin interface. The Dropdown filter fixes that. - The Dropdown is also “Searchable”, with an input text field (which utilizes Django’s own auto_completefunctionailty), so as long as the Django version you are using is greater than 2.0, you should be fine. - You can customize other list_filtersyou may have, like change the Title above the dropdown, or a custom Search logic etc. - You can customize Widget Texts to display in the Dropdown Option to use something other than the default str(obj)
https://www.tutorialguruji.com/javascript/how-to-change-the-django-admin-filter-to-use-a-dropdown-instead-of-list-that-can-also-be-searched/
CC-MAIN-2021-39
refinedweb
456
57.77
2009/12/18 Daniel Veillard <veillard redhat com>: > On Fri, Dec 18, 2009 at 12:10:08PM +0100, Matthias Bolte wrote: >> Commit 33a198c1f6a4a1bc7f34d50a31032e03bec10fee increased the gcrypt >> version requirement to 1.4.2 because the GCRY_THREAD_OPTION_VERSION >> define was added in this version. >> >> The configure script doesn't check for the gcrypt version. To support >> gcrypt versions < 1.4.2 change the virTLSThreadImpl initialization >> to use GCRY_THREAD_OPTION_VERSION only if it's defined. >> --- >> src/libvirt.c | 5 +++++ >> 1 files changed, 5 insertions(+), 0 deletions(-) >> >> diff --git a/src/libvirt.c b/src/libvirt.c >> index cad33c2..937cdb4 100644 >> --- a/src/libvirt.c >> +++ b/src/libvirt.c >> @@ -291,7 +291,12 @@ static int virTLSMutexUnlock(void **priv) >> } >> >> static struct gcry_thread_cbs virTLSThreadImpl = { >> + /* GCRY_THREAD_OPTION_VERSION was added in gcrypt 1.4.2 */ >> +#ifdef GCRY_THREAD_OPTION_VERSION >> (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)), >> +#else >> + GCRY_THREAD_OPTION_PTHREAD, >> +#endif >> NULL, >> virTLSMutexInit, >> virTLSMutexDestroy, > > I think that's the simplest. gcrypt 1.4.2 is rather old, but still > it might be preferable to not break build and keep without the fix if > on the old one. > > ACK, > > Daniel > Okay, pushed. Matthias
https://www.redhat.com/archives/libvir-list/2009-December/msg00624.html
CC-MAIN-2015-18
refinedweb
173
59.6
There seems to be an influx of devices claiming that they will change the future of Computing education. From the Arduino to the Raspberry Pi we now have a plethora of choices when it comes to getting started with physical computing. But in late 2014 there was a rumour that the BBC were keen to emulate the success of the UK's 1980s coding scene, which was led by the BBC Micro, their own micro computer. In 2011 there were a number of reports from Education advisers and Members of Parliament that the UK was now falling behind in Computer Science and that many children believed that the roles on offer meant relocating to another country. This was prevalent in the gaming industry, where the UK maintains sixth position, but with a decline in the number of developers originating from the UK. So in 2015 when the BBC announced that they would be partnering with a number of hardware, software and service suppliers to deliver a single board micro-controller powered platform, the Education sector stood up and listened. The goal of the micro:bit project was not to introduce just another single board computer or micro-controller, rather the goal is to disrupt. Put a device into the hands of children and teachers that has zero cost but maximum impact. The micro:bit is designed to work with mobile devices to spur classroom creativity, and with the micro:bit anyone can make their own smart device with very little code. Supported by the BBC and a number of service providers, the micro:bit has projects and documentation that has been designed to fit into the UK Computing curriculum. The hope of all the project partners is to rekindle the successes of the 1980s and help children to learn how rewarding Computer Science can be, with aims to generating new job roles in the future. Getting Started with Micro Python For this project you will need to connect your micro:bit to a Linux machine or Raspberry Pi. You'll also need an LED, 220 Ohm Resistor (RED-RED-BROWN-GOLD) and three Crocodile clips. In physical computing the "Hello World" introduction is traditionally to control an LED (Light Emitting Diode). This helps to test that the board and components are working correctly before we progress to something more challenging. We begin by downloading the Python software known as Mu. Ensure that you have the latest version of the software for your OS. You will need to make the downloaded file executable, in most Linux distros you can right click on the file and select "Properties" and from there make the file executable. If you prefer the terminal then you can do the following: $ chmod +x NAME OF DOWNLOADED FILE Now open the Mu application by double clicking on the downloaded file. The Mu editor looks basic but is constantly being worked on by members of the Python Software Foundation. You can see a row of buttons across the editor; pay particular notice to Flash and Repl. Flash is used to Flash your code on to an attached micro:bit, where as Repl (Read Eval Print Loop) is used to interactively hack with the micro:bit. We shall start our project by writing a few lines of code that will flash an LED on and off with a half second gap between each state. In the top windows we import the entire micro:bit Python library with: from microbit import * Now we create an infinite loop, which will contain the code that we wish to run while True. Inside of the loop, the next line of code is indented, as per Python's requirement to show that this code is inside of the loop. First we change the state of pin 0, which is currently turned off. To turn on the pin we set it to be 1. Then we sleep for half a second, before turning pin 0 off, using 0, then we sleep for half a second to create a seamless loop. You'll notice that we did not import the time library, yet we are using the sleep function. This is because Micro Python has its own sleep function inside of the micro:bit library that uses milliseconds for duration, with 500 equalling half a second. pin0.write_digital(1) sleep(500) pin0.write_digital(0) sleep(500) With the code written, it is time to flash the code on to the attached micro:bit. Click on Flash and wait until the yellow LED on the reverse of the micro:bit stops flashing. With the code loaded on to the micro:bit now we will connect the components. Attach one side of a crocodile clip to pin 0 and the other to the long leg of an LED. Connect another crocodile clip to the GND of the micro:bit and then attach the other end to one leg of a resistor. On the other resistor leg attach another crocodile clip and then attach it to the short leg of the LED. You should now see the LED flash if not, then check your wiring is correct by removing the crocodile clip from pin 0 and attach it to 3V. If the LED lights up then the wiring is correct. - Enjoyed this article? Expand your knowledge of Linux, get more from your code, and discover the latest open source developments inside Linux Format. Read our sampler today and take advantage of the offer inside.
https://www.techradar.com/au/how-to/computing/how-to-get-started-with-the-bbc-micro-bit-1317550
CC-MAIN-2021-04
refinedweb
914
66.98
Using Code Snippets in Visual Studio 2005 I want you to know that your illustrious executive editor, Brad Jones, is looking out for you. I proposed this article in my quarterly column calendar and Brad asked me if this was going to be a drag-and-drop article. I answered: No. His question illustrated why I wanted to write this article. Current versions of Visual Studio.NET support snippets—simply drag and drop some code into the toolbox and you can reuse it anytime you'd like. While useful, this function is not very exciting and it's often overlooked. Code snippets in Visual Studio 2005, however, are far more useful and deserve your attention. Based on XML, they support replaceable parameters, allow inserting assembly references and imports statements, and enable better organization. They also let you share management with other developers easily. This article is my meager effort to encourage you to take advantage of code snippets. It briefly demonstrates how to create a snippet in Visual Studio 2005 beta 2 using XML. Half-Baked Beta Bumps Beta means not quite finished. Think of beta applications as muffins pulled out of the oven before they are baked. Glaringly missing from the VS 2005 beta 2 is a code snippet editor. The official public statement is that the code snippet editor isn't quite ready for users. While waiting for the final release of VS 2005, you can download an external code snippet editor that comes complete with source code from MSDN. The examples in this article use this sample VB code snippet editor, which you can use until VS 2005 ships with its built-in editor. What Are Code Snippets? A code snippet is exactly what it sounds like: a small piece of code. Like project templates and project item templates, code snippets are discrete chunks of written code. Also, like templates, code snippets support replaceable parameters, which permit you to customize a snippet for each context. If you need whole projects or project items, you can use templates. For something smaller or just to show the code in IntelliSense and make it pluggable, use code snippets. Create a Code SnippetCode snippets are stored as XML in a file with a .snippet extension. Like all XML, these code snippet files have a specific format. Additionally, the snippet files need to be placed where Visual Studio can locate them. To this end, the snippet manager—which the final section covers—makes it easy to organize snippets. XML, being based on SGML (Standard Generalized Markup Language), is an elegant concept but an ugly language that isn't very human friendly. However, it is very useful in the Internet age because its text, its extensibility, and its predictable format-simply identify an opening tag and then fill in the blanks between the opening and closing tags. (Almost every tag has a symmetric closing tag with the same name and an additional forward slash (/).) Snippets support tags for replaceable elements, but the simplest snippets—those that contain literal code with no parameters—just need the code you want to insert. This code is an attribute of the <Code> tag. Listing 1 contains a simple Hello, World! snippet. To create additional snippets, copy and paste the literal code in the [CDATA] attribute with the new snippet code. Listing 1: XML for a Literal Snippet <?xml version="1.0"?> <CodeSnippets xmlns=" 2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>Canonical Hello, World! example</Title> </Header> <Snippet> <Code Language="VB"><![CDATA[MsgBox("Hello, World!")]]></Code> </Snippet> </CodeSnippet> </CodeSnippets> Add Imports and References You add imports and references after the <Snippet> tag. If you want to add an assembly reference, add a <Reference> tag with a nested <Assembly> tag followed by the name of the assembly (see Listing 2). Add <Import><Namespace> tags after the <Reference> tag. The <Imports> tag adds imports statements to the same module that you added the snippet to. The excerpt in Listing 2 shows how to reference the System.Data.dll assembly and add an imports statement for the System.Collections namespace. Listing 2: Elided Excerpt from a Snippet File Showing the Tags for an Assembly Reference and a Namespace Imports Statement <?xml version="1.0"?> <CodeSnippets xmlns=" 2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title /> </Header> <Snippet> <References> <Reference> <Assembly>System.dll</Assembly> </Reference> </References> <Imports> <Import> <Namespace>System.Collections</Namespace> </Import> </Imports> <Declarations> ... Add Literal and Object Replacements Replacements represent elements of your snippet that the user has to provide. To identify a replacement, add a <Declarations> tag at the same level as the <References> and <Imports> tags. If the replacement is a literal, add a <Literal> nested tag; for objects, add an <Object> nested tag. Both literal and object tags include <ID>, <ToolTip>, and <Default> child tags, and the object tag has an extra <Type> child tag that indicates the type of the object. Page 1 of 3
http://www.developer.com/net/vb/article.php/3505156/Using-Code-Snippets-in-Visual-Studio-2005.htm
CC-MAIN-2015-18
refinedweb
821
57.16
I am going to present Julia at the next ADASS (), and I would like to show its ability to fuse broadcasted operations like .+ and .*. I have found some weird results, so I would like to ask if you can help me in understanding what’s going on. I created three codes in Julia 1.0, Python3+NumPy, and C++. In each code, I run simple computations on large arrays, with an increasing number of parameters. Here are the functions as defined in Julia: f(x1, x2, x3, x4, x5, x6) = @. x1 + x2 g(x1, x2, x3, x4, x5, x6) = @. x1 + x2 - x3 h(x1, x2, x3, x4, x5, x6) = @. x1 + x2 - x3 + x4 i(x1, x2, x3, x4, x5, x6) = @. x1 + x2 - x3 + x4 - x5 j(x1, x2, x3, x4, x5, x6) = @. x1 + x2 - x3 + x4 - x5 + x6 Python functions are defined similarly, using NumPy arrays: def f(x1, x2, x3, x4, x5, x6): return x1 + x2 # and so on When each function is called, the six parameters are large arrays with 1M of elements. Each function is executed many times, and the minimum value is saved in a text file. The source codes of the Python, Julia, and C++ versions are available at- Results are shown in this plot: On the x axis, I report the number of parameters that have been actually used in the computation. So x=2 corresponds to function f, x=3 to function g, etc. On the y axis I report the minimum elapsed time as measured on my laptop (Lenovo Thinkpad Edge E540), a 64-bit system with 16 GB of RAM running Linux Mint 19 and GCC 7.3.0. There are a few things that seem reasonable: - Julia is faster than Python - Python scales badly, as it does not fuse loops - Julia and C++ scale similarly However, I cannot understand these features: - Julia is significantly faster than C++, even when using -O3with g++. In order to help C++, I cheated and modified the C++ code so that functions f, g, etc. no longer allocate the vector containing the result, which is instead allocated before the benchmark starts (see the code on GitHub). However, as you can see from the plot, Julia is still the best! - For n = 2, C++ is the slowest solution - The cases for n = 2and n = 3show equal times in Julia; this is not a statistical fluctuation, as I repeated the test many times with varying number of runs. I wonder how this is possible. Before showing this plot at ADASS, I would really like to understand everything. Can anybody give me some clue?
https://discourse.julialang.org/t/comparing-python-julia-and-c/17019
CC-MAIN-2020-40
refinedweb
436
69.82
EID is a 9-digit number that is on the front of your student ID card. Treat your username with the same privacy you would treat your e-mail address. Treat your CSUID with the same privacy as a Social Security Number (SSN). Eclipse makes programming easier by compiling and running your Java programs within a very sophisticated software application. Your TA will show you how to install Java and Eclipse on your personal computer. A personal computer is not required for this course, all work can be done on department, but it can be convenient at times to work from home. Here are are few hints: For the remainder of the lab, please use the Linux system, if provided. Your TA will help with any problems you encounter. eclipse.sh. Your TA will guide you in creating a project called P1 and class for starting the first week assignment: Your code should look like this, except with your name and email in the comments: // P1 Assignment // Author: Cam T. Ram // Date: 8/22/2017 // Class: CS163 or CS164 // Email: eid@cs.colostate.edu public class P1 { public static void main(String[ ] args) { System.out.println("Java programming is great!"); } } Your TA will now walk through logging in to the course website, submitting your code, and viewing preliminary test results. You should pass the first preliminary test. Read the assignment for P1. Now see if you can add another print statement and pass a second test. For detailed information on Eclipse, check out the Eclipse website. The website that allows you to submit progams and get them automatically graded. The TA will show you how to check the results of your preliminary and final testing, and how to retrieve your code from the Checkin tab.
http://www.cs.colostate.edu/~cs163/.Spring18/recitations/Lab2.php
CC-MAIN-2018-22
refinedweb
295
73.27
An Introduction to Object-Relational Mapping with Hibernate Implementation of object-relational mapping (O/R mapping) is a general need for many projects in software development. Usually, work with the automation process of data storage is very boring, and at manual implementation there is a danger of mistakes and bugs. Also, to add constantly varying requirements, it is necessary for the developer to take into account the complex process of synchronization of all initial code and data storage structures. More than that, taking into account the necessity of portability of application between platforms, it all becomes even more complex and confusing. Hibernate sounds like the best solution. It allows us to store the data in constant storehouse without serious consequences, thus a choice of such as storehouse, installation, and configuration do not make big difficulties. Hibernate allows us to store objects of any kind; therefore, it is not necessary for an application to know that its data will be kept with Hibernate. Clearly, with help of Hibernate we can not only keep the data in a storehouse, but also update and delete the data. Preparing the Workspace To begin, we will need to download the Hibernate distribution from. We will use version 2.1.4. As a database, we will use MySQL version 4.0.16, which also can be downloaded from. I need to mention that Hibernate also supports not only MySQL but different other open-source and commercial databases; for example, Hypersonic SQL, PostgreSQL, Oracle, DB2, and others. After you download all necessary packages, you must adjust your environment to include, generally, everything that we need to make it include all downloaded JAR files into our CLASSPATH. It should consist of at least two files: hibernate2.jar from a directory in which you have unpacked Hibernate, and mysql-connector-java-3.0.9-stable-bin.jar (which is JDBC Connector/J to MySQL database server; it could be downloaded from the MySQL Web site). Hibernate requires few more additional libraries that are in a directory, called <hibernate-dir>/lib /, where <hibernate-dir> is a directory with the unpacked Hibernate package. From this directory, we do not need all JAR files, but it is better to use them all now. Before we start work with Hibernate, we shall formulate a problem all over again and we try to solve it with the help of Hibernate. Formulate a Problem Certainly, every developer has faced the problem of creating a client servicing system. The general circuit can look as follows: We create an object for Order, we set into it Product objects, which by then becomes Order Items, and then we save Order. To build a database structure, we will use the following SQL script (or you can just simply type these commands in the MySQL console client): DROP DATABASE HIBERNATE; CREATE DATABASE HIBERNATE; USE HIBERNATE; CREATE TABLE PRODUCTS (ID VARCHAR(32) NOT NULL PRIMARY KEY, NAME VARCHAR(32) NOT NULL, PRICE DOUBLE NOT NULL, AMOUNT INTEGER NOT NULL); Apparently, this model of the data is very simple. In the case of a data model for real projects, we first will need to add all tables of other classes, and also to define FOREIGN KEY fields, indexes, additional fields, and other items. However, for our example, such a model will be quite good. Now, we will result a Java code that will be the Product class. For brevity, we will not give the results for the full getter/setter methods. You can add them easily. public class Product { private String id; private String name; private double price; private int amount; public String getId() { return this.id; } public void setId(String s) { this.id = s; } // default constructor // and usual getter/setter methods ... ... ... ... ... ... } Note: Hibernate works with any kind of Java objects if they support the JavaBeans specification. Page 1 of 3
http://www.developer.com/java/data/article.php/3391131
CC-MAIN-2016-36
refinedweb
639
52.7
27 March 2013 16:19 [Source: ICIS news] HOUSTON (ICIS)--Metabolix will distribute polyhydroxyalkanoate (PHA)-based heat shrink films for China's Tianjin GreenBio Materials in the ?xml:namespace> Under the their agreement, Tianjin GreenBio will also supply PHA resins to Metabolix, thus helping Metabolix to further extend its range of PHA products, it said. Tianjin GreenBio offers heat shrink film grades designed to replace non-compostable polyvinyl chloride (PVC) film and polyethylene (PE) films. “[Heat shrink film] complements our product slate aimed at film and bag applications, and we expect will be of interest to customers in the US and Europe seeking biobased materials and biodegradable performance," said Bob Engle, Metabolix's vice president of biopolymers business development. Financial details were not disclosed. Tianjin GreenBio is described as a producer and supplier of fully degradable biobased polymer materials from PHA. The company has a 10,000 tonne/year
http://www.icis.com/Articles/2013/03/27/9654180/us-metabolix-to-distribute-heat-shrink-films-for-tianjin.html
CC-MAIN-2015-06
refinedweb
149
51.18
Opened 4 years ago Closed 4 years ago Last modified 4 years ago #5119 closed defect (fixed) gdal_translate -sds uses incorrect subdataset filenames, simply appends a number to the end of target filename Description This was raised in the mailing list when I run: gdal_translate -sds -of "GTiff" [some.hdf] "myoutput" The output filenames do not have the .tif extension. If I set the output file to "myoutput.tif", it appends the "layer numbers" to the end of the file, e.g. myoutput.tif1. Any tricks to getting the naming working properly (myoutput1.tif would be what I'd expect)? example with a netcdf file with 2 subdatasets: tourigny@supernova: /data/src/gdal/svn/trunk/autotest/gdrivers/data/tmp $ gdal_translate -sds netcdf_2vars.nc tmp2.tif Input file size is 10, 10 0...10...20...30...40...50...60...70...80...90...100 - done. Input file size is 10, 10 0...10...20...30...40...50...60...70...80...90...100 - done. tourigny@supernova: /data/src/gdal/svn/trunk/autotest/gdrivers/data/tmp $ ls netcdf_2vars.nc tmp2.tif1 tmp2.tif2 resulting files should be tmp21.tif tmp22.tif preparing a fix which would add an underscore (for easier reading) and also zero-pad if there are more than 9 subdatasets. e.g. tmp_01.tif [...] tmp_10.tif as this would change behavior of gdal_translate, I am not sure if this should go into 1.9 and 1.10. Any thoughts? Attachments (4) Change History (17) Changed 4 years ago by patch comment:1 Changed 4 years ago by Etienne, char papszTokens = CSLTokenizeString2(pszDest,".",0); doesn't look like a relieable way of detecting the extension in case the output file is something like "odd.directory.name/odd.output.filename.tif". I'd encourage you to use CPLGetPath(), CPLGetBasename() and CPLGetExtension() to split the components, and then CPLFormFilename() to build the new filename. As this is a change of behaviour (some people might depend on the current behaviour, even if it is admittedly odd), I'd rather push that change just in trunk. Initiating a "behavioral changes" section in the NEWS file might also be appropriate. comment:2 Changed 4 years ago by This is quite a major issue when processing many hdf files which is often the case when working with hdf format and subdataset in gdal_translate (MODIS for example). We have a work around appending another .tif to the end of the filename (tif1.tif, tif2.tif). It is also referenced as a problem by others at. Im not sure why anyone would be reliant on the current method of processing of .tif1, .tif2 etc. comment:3 follow-up: 4 Changed 4 years ago by can you test the last patch attached here? comment:4 Changed 4 years ago by comment:5 follow-up: 6 Changed 4 years ago by I meant the patch attached in this ticket (see link above), patch_translate_sds2.txt comment:6 Changed 4 years ago by comment:7 Changed 4 years ago by Perfect. We ran on modis data and got the correct return (out_01.tif out_02.tif out_03.tif out_04.tif out_05.tif out_06.tif out_07.tif out_08.tif out_09.tif out_10.tif out_11.tif out_12.tif) Thanks I will look out for the update will it be in 1.9 or 1.10. comment:8 Changed 4 years ago by actually this won't make it into 1.9 or 1.10, see Even's comment above. If you say it is satisfactory then I will add it to trunk, which will make it into 1.11 or 2.0 comment:9 Changed 4 years ago by It is satisfactory. comment:10 Changed 4 years ago by comment:11 Changed 4 years ago by comment:12 Changed 4 years ago by comment:13 Changed 4 years ago by my sincere apologies for not looking into this sooner, I was away. sample dataset with 2 subdatasets
http://trac.osgeo.org/gdal/ticket/5119
CC-MAIN-2017-47
refinedweb
650
65.42
#include <hallo.h> Roland Mas wrote on Fri Apr 26, 2002 um 03:35:11PM: > So you'd propose to have, say, unstable-for-woody, testing-for-woody, > unstable-for-sarge, testing-for-sarge, unstable-for-<woody+2>, BTW, who said Sarge? I cannot find any reference about this name, at least not from any real decission makers. See attached IRC log, censored a bit. Gruss/Regards, Eduard. <Zomb> btw: what's woody+1? Sarge? <Zomb> Could we have Debian Zurg? <Oskuro_> zurg is TS2, right? <asuffield> Zomb: won't be finalised until woody releases <Oskuro_> there's many names in TS2. Oskuro Oskuro_ <Zomb> Oskuro: yes * vorlon-work scratches his head. Why is abiword x86-only? <xtifr> I'd say that sarge is probably the front-runner, tho <asuffield> well, aj has mentioned sarge once, maybe twice * xtifr nods <Zomb> hm... we should vote <Zomb> Stinky-Pete is less apropriate, I guess... * vorlon-work grins at * pgpkeys votes for zorg <Oskuro_> calling releases after slang words would rock <Zomb> or "Jessie"... <Oskuro_> Jessie would be nice. <Oskuro_> We've only had one female codename :) <xtifr> barbie! :) <pgpkeys> why not? goes right along with katie and jennifer <Zomb> Jasmin... <Zomb> Margarethe... <pgpkeys> ummm... no <pgpkeys> jasmine maybe. that last one? <pgpkeys> s/me/m/ <Zomb> too long maybe <Oskuro_> jasmine... who is she? <StevenK> Name releases after actresses on Baywatch? <pgpkeys> just doesn't sound right <pgpkeys> girl from Aladin <Oskuro_> yuck <xtifr> ick, no disney! they're trying to stamp out free software <StevenK> No! Jasmine Bleech (sp?) was on Baywatch! <pgpkeys> hey it's better than Debian GNU/Linux 3.2 (Roger Rabbit) <StevenK> You've got it all wrong! <mhp> 3.3 Elmer Fudd <pgpkeys> lol <pgpkeys> I always have it all wrong. never stopped me yet. <StevenK> 4.1 Wallcous Wabbit <StevenK> Or something <pgpkeys> 4.2 Marvin <Oskuro_> insults and slang words are great. <pgpkeys> aka Marvin the martian <mhp> 4.3 "Now you can panic" <rcw> I don't suppose I'll ever get any buyin for my addictive-painkillers-for-releasenames idea <Zomb> too long maybe <Zomb> err <pgpkeys> mhp rotfl <xtifr> how 'bout obscure characters from 17th century literature? <dilinger> <Oskuro_> haha <dilinger> we should take lessons from the gnome folks, they had good naming ideas <pgpkeys> xtifr: Debian GNU/Linux Valjean? * StevenK can think of a few choice words for Gnome releases. <rcw> dilinger: we are not naming a Debian release "excuse me have you seen my pants"! <StevenK> rcw: Bwahaha <Oskuro_> rcw: lol <pgpkeys> rcw hahaha <dilinger> rcw: at least it won't have as many misinterpretations as "woody" ;) <mhp> hmms... <pgpkeys> or "Can you get out of my pants" <mhp> 9.8 "SuSE style" <pgpkeys> well depends. will it bring mor elinux chiqs? <Zomb> lol <Joy> and point releases would be "Service Packs" eh? :) <Zomb> Joy: not a bad idea ;) <asuffield> Joy: either that or "JoeyPr0n" <pgpkeys> sickos <Oskuro_> Joy: haha <xtifr> I think we should switch right now to using nicknames for penises -- we've already got a head start on that :) <d00d> mmh.. Debian GNU/Linux "Numenor"? <pgpkeys> xtifr: hahaha <pgpkeys> oh god <pgpkeys> Debian GNU/Linux Misnomer <Zomb> Debian/Linux TheHighstNumber <pgpkeys> Debian GNU/Linux "Plain Brown Wrapper" <rcw> zomb: are we going to refer to our plans for "infinity+1" or "infinity+2" in the future? <pgpkeys> To infinity and beyond! <Zomb> rcw: why not ;) <Zomb> Debian/Linux "InfiniteLoop" <pgpkeys> ok, i need to lay off the weed or crack or wahtever I'm supposec to be on <pgpkeys> err supposed <Zomb> Debian/Linux "NeverEndingStory" <pgpkeys> oh brother <pgpkeys> I haven't heard that name i awhile <Zomb> hm, no, Nintendo would sue us because of NES abb <pgpkeys> Debian GNU/Linux "Crank" * mhp ponders quotefiling the last few minutes <pgpkeys> hehe I can here it now at the LUGs. "Yeah, I run Crank at home" <dilinger> haha <pgpkeys> yeah well I run Prozac and I can't wait for Klonopin to be released <Oskuro_> mhp: haha <pgpkeys> Wonder how many Narcs would be sittin at these meetings <Zomb> mhp: go ahead <Oskuro_> xtifr: haham, rocks * mhp cut & pastes, and goes to sleep <StevenK> pgpkeys: Ambigous. <mhp> hmms <pgpkeys> hehe <mhp> Debian GNU/Linux Yamm (since it's almost as huge as my tamagotchi) <pgpkeys> Debian GNU/Linux "Not your average CrackWhore" <rcw> xtifr: <rcw> I don't suppose I'll ever get any buyin for my addictive-painkillers-for-releasenames idea <LoRez> the morphine release? <pgpkeys> Debian GNU/Linux "Neurosis" <StevenK> Debian GNU/Linux "Crushed-by-Yamm" <pgpkeys> hey i actually like the sound of that <pgpkeys> hehe <xtifr> rcw: that'll teach you to be subtle... :) <pgpkeys> Debian GNU/Linux "Saline Drip for you rmind" <Cowboy> Kamion: ayt ? <rcw> xtifr: well, that's just the effect painkillers have <Zomb> there are still many good names from Babylon 5 series <Zomb> Debian/Linux "RangerOne" <Zomb> Debian/Linux "Crysalis" <Zomb> Debian/Linux "Valen" <pgpkeys> "Vorlon" <Zomb> yeah <pgpkeys> wait, that actually works <StevenK> Name releases after developers? <StevenK> Wierd. <Zomb> why not... <Zomb> WhiteZombie <StevenK> Debian GNU/Linux "Overfiend" <nickr> Vorlon, hah. Release is a three-edged sword. <Oskuro_> Debian GNU/Linux "lifesucks" <pgpkeys> hmm. not sure how branden would respond to a distrib after him <LoRez> StevenK: yeah, that's what we need, OF with a even bigger ego =) <StevenK> LoRez: :-) <pgpkeys> Less time to work on the X11 stuff when everyone's asking Is it really named after you?? <pgpkeys> You know we _could_ go with something simple like Debian GNU/Linux "Fried" <pgpkeys> I mean you just gotta love all the permutaions you can get out of that <xtifr> how about other distros: debian 3.2 "redhat", debian 3.3 "suse" :) <Zomb> hehe <Zomb> if so, then "RatHead", "SuXe" <pgpkeys> gotta add Killer or somthng <xtifr> the good part about naming 'em after other distros is that we'll have names to mine for *centuries* to come! :) <pgpkeys> actually I prefer Debian GNU/Linux "Optimus" <nickr> how about obscure heavenly bodies <nickr> NGC 3210 <pgpkeys> Hmm. Nebual Gas Cloud 3210 <pgpkeys> just doesn't have the same ring as NCC-1701D * Jo-Con-El_ wondered for a second that 'obscure heavenly bodies' was Satan...or something. <Zomb> what about emotions? "Optmism", "Hope", "Sympathy" <pgpkeys> hey the Enterprise alone would give us enough for 4 or 5 releases <pgpkeys> never mind the other class startships. <pgpkeys> Zomb: "Pity" <xtifr> if we mine startrek, the b5 bozos will whine, and if we mine b5, I quit! :) <LoRez> or not so obscure heavenly bodies "Katie Holmes" <pgpkeys> hey B5 rocked <Zomb> xtifr: same here <xtifr> whatever <Zomb> B5 names are the right way to go <pgpkeys> hopw can you NOT like the Shadow Wars?? <pgpkeys> s/hopw/how/ <xtifr> easily <seeS> what about calling it Debian 3.0 "star-trek-fans-are-weenies" <pgpkeys> damn. deprived souls <StevenK> LoRez: katie is already named after Katie Holmes. <Jo-Con-El_> And what about hiding some message in several releases? <StevenK> I mean, duh. <pgpkeys> come step in my house uninvited and see how much of a weenie i am <Jo-Con-El_> Debian 3.1 'Towards' <Jo-Con-El_> Debian 3.2 'Total' <Jo-Con-El_> Debian 3.2 'World' <Jo-Con-El_> Debian 3.2 'Domination' <LoRez> StevenK: I know. but we could use other "bodies" <pgpkeys> there's not a transportor that can help you then <Jo-Con-El_> Debian 3.4 'Domination' <StevenK> Jo-Con-El_: You suck. ;-) <StevenK> 3.1, 3.2, 3.2, 3.2 <pgpkeys> Dominus <Jo-Con-El_> StevenK: Heh, I saw. O:-) <Jo-Con-El_> StevenK: But when we achieve total domination...we can do whatever we want with the ordinal numbers, eh? <Jo-Con-El_> :-) <pgpkeys> Debian GNU/Linux "Twisted" ? <pgpkeys> i vote for a backwards count <pgpkeys> if you're not using Debian Linux before we reach 0.0 you get the gas chamber <Jo-Con-El_> pgpkeys: X-D <Jo-Con-El_> Hehehe <Jo-Con-El_> I'm sure that reportbug maintainer will want to make Debian releases like: <Jo-Con-El_> 3.1 <Jo-Con-El_> 3.14 <Jo-Con-El_> 3.141 <Jo-Con-El_> 3.1415 <Jo-Con-El_> etc. <nickr> haha <Oskuro_> It'd be nice to use an epoch with every release. That would piss many :) <Oskuro_> package release, I mean <pgpkeys> ok, if you don't like gas chamber idea, then we make em permenantly use HP-UX <asuffield> Oskuro: just an epoch, no version component >:) <asuffield> Oskuro: or some random text in the version component <Oskuro_> asuffield: lol <Oskuro_> yeah, that'd be nasty <asuffield> extracted from fortune <xtifr> get names from M-X spook :) <pgpkeys> the unsanitized fortune even <asuffield> 2:X-Face-<gibberish> <Oskuro_> 2:could-work-maybe-it-wont <Oskuro_> asuffield: heh <rcw> next people will want minor number support in epochs <pgpkeys> well, i still vote for releases named after sed or perl regexx <StevenK> Whta about [^.]*udhda.*+1? <StevenK> s/Whta/What/ <Oskuro_> Debian GNU/Linux/ "s/RedHat/Sucks/g" <pgpkeys> naww, not long enough. reportbug could handle that easily <StevenK> s/Red\(Hat\)/Root\1/ <pgpkeys> how about an epoch + date string + regex to reverse every other charactor <pgpkeys> starting from teh far end <nickr> epoc+date+md5sum of orig <pgpkeys> oooo, that oughta be nice <pgpkeys> better to use an unescaped gpg public key <Oskuro_> heh <pgpkeys> embed it right in the distro name <StevenK> Debian GNU/Linux 3200312067642786478236e478657826357867834658 <pgpkeys> hmm <pgpkeys> wait, wait.. this has potential <rcw> that's right, we were gonna sign our releases, weren't we? <pgpkeys> hehehe <Oskuro_> this must be one of the most irrelevant conversations in a while :) <Oskuro_> And we've been talking about it for a long while now :) <pgpkeys> measn we're slowly working to a consensus of Debian GNU/Linux "Line Noise" * doogie drops a vat of napalm on the channe <doogie> +l <pgpkeys> hmm /mode #debian +l -9999 <pgpkeys> nm <Oskuro_> doogie meant this channel, I suspect :p <pgpkeys> thus the quick nm <Zomb> Debian Gnu/Linux "Chaos" <Zomb> whatever... sleep time -- I have found little that is good about human beings. In my experience most of them are trash. -- Sigmund Freud -- To UNSUBSCRIBE, email to debian-devel-request@lists.debian.org with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
https://lists.debian.org/debian-devel/2002/04/msg02112.html
CC-MAIN-2015-35
refinedweb
1,734
63.9
CodePlexProject Hosting for Open Source Software Hi, I'm Japanese Orchard user. In the creating a new page, I input the title using Japanese. And Orchard is generate permalink automatically. But, the permalink is not match to the page title. Voice sound mark is removed. For example: (please look with Japanese font!) 1) Input title is "ぺいじてすと" then generated permalink is "へいしてすと". 2) Input title is "だあじりん" then generated permalink is "たあしりん". In Japanese, the presence of voiced sound mark is equivalent to a completely different character. I think its nice to Orchard modified the rules generate a permalink from a title. Please file a bug in the issue tracker. Thank you for your reply and leading. The issue is create in: Hi Usagi, If you want to "fix" this problem, you could create a module of your own and overwrite the slug logic to your needs by implementing a ISlugEventHandler. Also, if you want to see the logic we are using you can look at the method FillSlugFromTitle in class RoutableService in the Orchard.Core project. Hope that helps, Andre Thank you, Andre. Your hint is fit to the problem. Cause of the problem is the method of RemoveDiacritics(in Orchard.Core.Routable.Services namespace) called from the method of FillSlugFromTitle(in Orchard.Core.Routable.Services). Its good for a basic Latin character based culture. But, the function is not require by the other cultures. And especially, in Japanese culture, the function is generate strange slug. I think better if Orchard set out to the neutral for culture then the function split to a module from the core. And the module set disable for default. --- And quick-fix, I writing the module its copy from a part of FillSlugFromTitle method without RemoveDiacritics function. public class disable_core_slug_remove_diacritics : ISlugEventHandler { void ISlugEventHandler.FilledSlugFromTitle(FillSlugContext c) { var disallowed = new Regex(@"[/:?#\[\]@!$&'()*+,;=\s\""\<\>]+"); c.Slug = disallowed.Replace(c.Slug, "-").Trim('-'); if (c.Slug.Length > 1000) c.Slug = c.Slug.Substring(0, 1000); c.Slug = c.Slug.Trim('.').ToLower(); c.Adjusted = true; } void ISlugEventHandler.FillingSlugFromTitle(FillSlugContext c) { } } But, I don't know how to add the my implementation of the ISlugEventHandler to the Orchard ISlugEventHandler list. I read the HelloWorld and create module templete with Command-line. And write the code, and enable the module in a test site in IIS. But, slug is not change. Someone, could you tell me an example module of ISlugEventHandler implementing? If you use the code generation tool to create a module and implement this class anywhere: using System.Text.RegularExpressions; namespace Orchard.Core.Routable.Events { public class JapaneseSlugEventHandler : ISlugEventHandler { public void FillingSlugFromTitle(FillSlugContext context) { var disallowed = new Regex(@"[/:?#\[\]@!$&'()*+,;=\s\""\<\>]+"); context.Slug = disallowed.Replace(context.Slug, "-").Trim('-'); if (context.Slug.Length > 1000) context.Slug = context.Slug.Substring(0, 1000); context.Slug = context.Slug.Trim('.').ToLower(); // Processing is done. Don't process further. context.Adjusted = true; } public void FilledSlugFromTitle(FillSlugContext context) { // No nothing } } } Orchard will automatically detect that dependency (when the feature is enabled) and inject it. Note that I just copied the code you suggested and adapted it to make it functional. The problem you had was that you were placing your code under the "Filled" method instead of on the "Filling" method. Great thanks! It's work fine on my test environment. I was miss placing my code in the other namespace. And, I uploaded the module to Orchard Gallery: Actually it wasn't the namespace but the method you were using :) But in any case, glad it works now! :) Awesome work and thank you for uploading your module. Feel free to extend to other module contributions as you explore the platform :) I think the problem is not for only Japanese maybe. RemoveDiacrictics function is not require for Cyrillic, Greek, etc., and Japanese (non-English like character or non-Latin based character languages). These cultures text can't convert to ASCII use RemoveDiacrictics, and the function bring side-effect(difficult to read) only. Especially, the side-effect is large in non-Latin based character users(e.g. Japanese). So, I propose: * Split and remove "RemoveDiacrictics" function from Orchard core module. * Create new module with the splited "RemoveDiacrictics" function. (I think the new module bundled and enabled to Orchard default is good usability for all Orchard existing users :) ) ... But, I don't know whether this is necessary for those users. I'm use Japanese and a little English only. --- ps. I'm sure develop modules, create themes, and translate UIs for Orchard with enjoy. Thank you Andre. Sounds reasonable. Could you please open a bug with that description and include a link to this discussion ? That way we can make sure we fix it for orchard vnext. Again, thank you for taking the time into investigating this. The issue: (I rewrote the title and the description to organized the thread from copy of this thread the first post.) Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/243467
CC-MAIN-2017-04
refinedweb
844
60.31
May 08, 2012 04:30 PM|LINK Hi guys, I have a view in which the user can edit a collection of "heterogeneous" items, each of the item currently is implemented as an instance of class "WAttribute", for example: public class WAttributeViewModel { public string DisplayName; public string UserValue; ... other "meta" data properties describing the WAttribute, such as format string (0.00%), minValue, maxValue... } In the controller, I will get a list of this WAttributeViewModel as List<WAttributeViewModel> from the database, the displayname will be shown as the Label in the view, UserValue will be a text input, and the user can modify the UserValue, then I will save the UserValues back to the database, when the user hit the "Save" button/link. The problem is: different rows of WAttributeViewModel in the list can have different validation reqirements, for example: 1. for a "Field Percentage" WAttribute, it is a percentage, it should be shown as x.yz%, and I should validate its UserValue as numeric percentage (and different percentage WAttribute may have different min/max range requirements) 2. for a "Facility Location" WAttribute, it is a string, it should be shown as string, and I don't need to validate its value, i.e. the UserValue can be empty. 3. for a "Project Class" WAttribute, it is a string, and its UserValue cannot be empty. 4. for a "Installation Date" WAttribute, it is a date, it should be shown as MM-DD-YYYY, and I need to validate its value, ie. it is a date and cannot be empty. 5. the list goes on and on, and each row in the list may have different requirements for validation, these requirements are stored in the database and I can get them into the WAttributeViewModel. So, I think I cannot use DataAnnoation attributes, such as [Required], or [Range], to descorate the UserValue property in my WAttributeViewModel, because each row/instance will have different requirements for validation, some are [Required] some are not, some have a range of [1..10], and some have [100..10000]. And I think I cannot add/modify an (DataAnnoation) attribute of a property at run time. So, what is the best way to implement validation for my case? Before using MVC, we used ASP.NET web forms, and we used telerik's RadInputManager, and we create multiple inputsettings to manage the vlidation and formating of the values. Is there a similar control/method that i can use in the MVC world? Thanks! Wenbiao Star 7784 Points May 08, 2012 04:36 PM|LINK Hi, you can use IValidatableObject Interface , look at this Example , or you can create custom Vaidation attribute and and using reflection you can check the values . hope this helps All-Star 20888 Points May 08, 2012 04:51 PM|LINK Give a look to the answer I gave to a similar question: I proposed to define a BrokerAttribute plus the normal validation attributes. Probably with minor modifications the same approach might be viable also for your case. All-Star 20888 Points May 09, 2012 02:02 PM|LINK Sorry I don't have a working example, since in my software I try to avoid such a metaclasses that are diffcult to mantain. I prefer using strongly typed classses+some dependency injection+interfaces to make they "open" to new types. However the basic idea is simple, at leasdt for the server side validation (it is better you start from there, since it is easier). You implement a custom validationa attribute that just specified the name of another property whose value would be the actual validation attribute to apply. Let make an examle [Broker("ValidationType", ValidationArguments)] public string UserValue{get; set;) public Type ValidationType {get; set;} public object[] ValidationArguments {get; set} Now since the property ValidationType can accept a Type you can give it the type of a validation attribute as value: x.ValidationType=typeof(RequiredAttribute);.... x.ValidationArgument = new object[0]; Now when you write the code of the BrokerAttribute. In its IsValid method. you just access the ValidationType property that is passed as parameter of the BrokerAttribute, and via reflection you invoke its IsValid Method. You use the ValidationArgument to pass some parameters to the valòidation attribute This way you can implement a "variable" validation, whose validation rules are specified in the properties of the classes of your list. 6 replies Last post May 09, 2012 08:05 PM by WenbiaoLiang
http://forums.asp.net/p/1801520/4971229.aspx/1?Custom+Validation+on+Collection+of+heterogeneous+items
CC-MAIN-2013-20
refinedweb
734
50.06
Introduction to pass Keyword in Python A “pass” keyword refers to a null operation. Or in other words, one can say, “do nothing”. Question must have popped up in many reader’s mind “Then why do we use it?”. Python has the concept of keywords. Keywords are some reserved words in python which has special meaning with it, and hence can’t be used as variable/function names. These keywords are case-sensitive. So, “pass” and “Pass” are two different entities for Python. So, while using keywords in python, keep in mind the cases. There are so many keywords that python supports like: break, if, else, pass, finally etc. Python supports looping conditions like for loop, while loop, nested loop. During execution of these loops, there comes many inevitable conditions where code has to pass through, but without doing anything. In this kind of situation “pass” keyword plays a pivotal role. Syntax of pass: pass Examples of pass Keyword in Python Given below are the examples of pass Keyword in Python: Example #1 Code: for numb in range(1,5): if numb==2: pass else: print ("Present Number = {} ".format(numb)) Output: - As one can notice here, for number “2”, pass statement has executed. Which means, it resulted in “No Operation”(NOP). - Question might occur: Then this is what comment does. Isn’t it? - True. Comment can be used. But interpreter ignores the commented section, however pass is not ignored. Interpreter goes through it and performs nothing. Example #2 A class with two different methods. Code: class Animals: def Noise(self): print("Noise created") def Silence(self): pass # Create class and call both methods. b = Animals() b.Silence() b.Noise() Output: - One can see the class “Animals” has two kind of functions: one which prints something while another function with pass. - Output will be looking quite convincible, as “Silence” function doesn’t do anything, while “Noise” function does(it prints). Example #3 Code: for letter in 'EDUCBA': pass print('Here is the last letter :', letter) Output: - As one can notice, till the time letter was there, for loop kept on passing it. For letters: “E”,”D”,”U”,”C”,”B”,”A” it passed for all. - And last letter was stored in variable name “letter” which was printed at the end. Example #4 Code: randomChoosenList = ['a', 0, 2] for item in randomChoosenList: try: print("The entry is", item) r = 1/int(item) break except: print("Oops!","Error occured.") pass print("The reciprocal of",item,"is",r) Output: - As one can notice, pass keyword is used in exception handling here. - In case 1, where first item ‘a’ will throw exception. It will be shown “Oops!”,”Error occured.” And then passed. - In case 2 as well, similar thing happens. Exception gets shown and then passed. - However, in case 3, it passes well in try block, which doesn’t make it go through pass keyword. - One can use pass keyword in any of the block: try or except, depending on the requirement. Example #5 One can also use pass keyword for keeping empty function. It will be a function which will not do anything. This could be a temporary way keeping functionality defined related to a function, which can be implemented later. Here we can’t comment section and keep that section. Code: def Future(self): #pass Output: - Because of commented section, it has thrown error. - Question might come here: Can we have multiple pass statement in one function or logical block of python? - Answer is Yes! That’s because interpreter just goes through pass keyword and does nothing. So, one can definitely have more than one. Code: class temp: def Future(self): pass print("hi") pass print("hello") b = temp() b.Future() Output: - As one can see, here we have two pass keywords. And that’s just not doing anything. Advantages of using pass Keyword in Python - Keyword “pass” can be used as placeholder by many coders. Later with usage of code, pass can be replaced by suitable logics. It can be proved savior for future tweaks in code. - It helps programmers to come with skeleton program and logic syntactically, by blocking space for empty function or empty code. Code: class Student_Database: def Student_data_delete(self,i): #implement this function later pass def Student_data_update(self,i): #implement this function later pass def Student_data_delete(self,i): #implement this function later Pass - Other scenario could be, skeleton program can be created and can be given to other parties for implementations. Conclusion Python is great programming language which comprises of many keywords. “Pass” is one the important keyword used widely while coding and specially handling the conditions there. Python doesn’t have the concept of ending line with semicolon like in other languages. So “pass” keyword helps in indicating the empty lines or the empty logics which doesn’t have to do anything for now, but later point that can hold some logic. One who understood the concept of “pass” and examples here, can further jump to other keywords of python to get good grip over other important keywords in it. Recommended Articles This is a guide to pass Keyword in Python. Here we discuss the introduction and examples of pass keyword in Python. You may also have a look at the following articles to learn more –
https://www.educba.com/pass-keyword-in-python/?source=leftnav
CC-MAIN-2021-04
refinedweb
878
66.13
Board index » VC Debugger All times are UTC I'm using Visual C++ 5.0 and Developer Studio 97 under NT 4.0. I've got some source files with embedded SQL in them. These files have an extension of .SQC. I set up a custom build in the GUI to run the preprocessor that converts the .SQC files into .C files. However, I can't find any way in the GUI to set up dependencies for the .C files. I want to tell it that FOO.C is dependent on FOO.SQC, for example. This way, FOO.C will only be created if FOO.SQC has a later timestamp. I can do this with an external makefile, running nmake from the command line, and manually entering my own dependency rules in the makefile, but I want to do it from the GUI. The only thing I found through the GUI is that you CAN set up dependencies for a CUSTOM build. This means that if my .SQC file was dependent on some other file, I could specify it in my custom build. But this is not my situation. Can I do what I am wanting from the GUI? Brad Radaker Computer Consultant I'm just starting a project where I have to do the same thing! Did anyone ever get it figured out how to get the whole build, including pre-processing, done in VC++ 5.0 using the GUI? Any tips/help would be appreciated, we're on a very tight deadline and I have to start tackling this tomorrow. Thanks, Bill Hines >Can I do what I am wanting from the GUI? >Brad Radaker >Computer Consultant. Thanks for the reply. I got it working so that the custom build step for my .sqx file calls a batch file which has the commands: db2 connect to mydb db2 prep %1.sqx bindfile db2 bind %1.bnd db2 connect reset exit This is from memory, but you get the idea. There are a few problems I'd like to solve to make this usable. Is this the right approach? When it runs from inside VC++ 5.0, I can see the DOS box pop up, but then in the VC window it already says 0 errors 0 warnings before the DOS box is even closed. Every so often the dos box stays there and hangs, causing me to have to restart the system. I'd like to fix that problem and get the results reported back to VC - it says 0 errors even when the prep command finds errors. Thanks for any help.... 1. Newbie: separate big .cs file into small .cs files 2. Ms Studio 6 - VC++ Dependency Files 3. Hooking my help file into Developer Studio 4. resx files needed for cs - files ?? 5. CS files display in VS6 like CPP files ? 6. 2nd try: need a C library file for reading Windows-style .INI files 7. 2nd try at copying a file: copyfile() returns success but creates empty destination file 8. 2nd try at copying a file: copyfile() returns success but creates empty destination file 9. Format of dsp files (Visual Studio project files) 10. including files in Visual Studio Project files 11. Include code in other Cs files 12. Reuse of cs files, namespace, arch advice pls
http://computer-programming-forum.com/79-vc-debugger/7cc39f52957701fc.htm
CC-MAIN-2018-39
refinedweb
552
86.5
. Need Help with Grid cells (New in Vaadin) I have a Grid with an IndexedContainer. This Grid is planned to be filled with the user information and then stored. It has a button to add as many rows as the user need. The problem is that some columns have to be ComboBoxes, cells accepting only Hour format and a Button. Something like this: Column Hour (Hour format), Column JobType (ComboBox), Column EndHour(Hour Format), Column Description(String), Column ButtonRemove(Button). How can I add them? Components in grid cells aren't supported (yet) by the core framework, however there is an add-on for that (which I'm currently using): For the hour format, you'll need to use a converter (StringToIntegerConverter) and validator (IntegerRangeValidator) for each column. How you do that will depend on whether you are using Vaadin 7 or 8. Based on your other post in this forum I'm going to guess you're planning on using Vaadin 8. (I'm writing this code on the directly here, so there might be some syntax errors) (also I'm new to Vaadin 8 so there might be better/cleaner ways of doing this) // the bean in the grid public class GridRow { private int hours; // 0 - 23 // other data public int getHours() { return hours; } public void setHours(int hours) { this.hours = hours; } } // in the view/UI ... Grid<GridRow> grid = new Grid<>(GridRow.class); Binder<GridRow> binder = grid.getEditor().getBinder(); TextField hoursField = new TextField(); // in Vaadin 7 you'd add the Converter/Validator directly to the TextField Binder.Binding<GridRow, Integer> hoursBinding = binder.forField(hoursField) .withConverter(new StringToIntegerConverter) .withValidator(new IntegerRangeValidator("Value must be between 0 and 23", 0, 23)) .bind(Person::getHours, Person::setHours); // in Vaadin 7 you'd do grid.addColumn("hours").setEditorField(hoursField) grid.addColumn("hours").setEditorBinding(hoursBinding); // enable grid editing, define listeners for editing events ... Hope that helps
https://vaadin.com/forum/thread/15416573/need-help-with-grid-cells
CC-MAIN-2021-43
refinedweb
313
56.96
Hi wastrying to isolate network daemons inside empty, read-only file-systems,and I discovered that this effort was worthless. To resume, imagine anetwork daemon which does :chroot("/var/empty") (read-only directory or file-system)chdir("/")listen(), accept(), fork(), whatever...-> external code injection from a cracker : mount("none", "..", "ramfs") mkdir("../mydir") chdir("../mydir") the cracker now installs whatever he wants here.The worst is that the new directory can even become invisible from allother processes, so that the intruder has nothing to fear :-( So I read fs/namei.c and fs/namespace.c, and found a way to preventthis. Basically, the only case where it's still possible to mountsomething on the current->fs->root now, is when the process wants toremount the root fs, but no other mounts are allowed.Since I'm really clueless about VFS code, I might have done it wrong,or broken something, so I post this patch for comments. If everyoneagrees, I would really appreciate it if it was accepted in mainstream,because it's a security problem IMHO.It still applies to 2.5.66 with offset BTW.Cheers,Willy--- linux-2.4.22-pre2/fs/namespace.c Sat May 10 11:36:02 2003+++ linux-2.4.22-pre2-dotdot-mount/fs/namespace.c Sun Jun 29 14:38:16 2003@@ -732,6 +732,10 @@ if (flags & MS_REMOUNT) retval = do_remount(&nd, flags & ~MS_REMOUNT, mnt_flags, data_page);+ else if (nd.dentry == current->fs->root &&+ nd.mnt == current->fs->rootmnt)+ /* prevents someone from mounting on . or .. */+ retval = -EINVAL; else if (flags & MS_BIND) retval = do_loopback(&nd, dev_name, flags & MS_REC); else if (flags & MS_MOVE)-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
https://lkml.org/lkml/2003/6/29/36
CC-MAIN-2017-43
refinedweb
296
50.02
I am trying to read the names from a file, store them in a dynamically allocated character array then print them to the console. When I run the program I get a segmentation fault. I think it has something to do with fgets. Why is this happening? votes.txt: Almog, Nat Ngoc, Noor Hyun-Joo, Candide Ji, Yarden Celestine, Maui Li, Cande Tristen, Thoko Vijaya, Cheng Jaya, Sung-Hyun Glaw, Cahya #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { FILE* fp; fp = fopen("votes.txt","r"); char** nameArray = malloc(10 * sizeof(char *)); //Allocate row pointers int i; for(i =0; i< 10; i++) { nameArray[i] = malloc(25 * sizeof(char)); //Allocate each row separately } int j; for(j=0;j<10;j++) { fgets(nameArray[i], 25, (FILE*)fp); } int l; for (l=0; l<10; l++) { printf("nameArray[%d] = %s\n",l,nameArray[l]); } int k; for (k =0; k<10; k++) { free(nameArray[i]); } free(nameArray); } Your indices are wrong in a few places: int j; for(j=0;j<10;j++) { fgets(nameArray[j], 25, (FILE*)fp); int k; for (k =0; k<10; k++) { free(nameArray[k]); Both of these have i for the array indices in the loops of your code. I am not sure why you are using i, j, k, and l anyway. Why not just use i? This would have saved you some confusion. You should also close(fp), and add return 0 at the end of main().
https://codedump.io/share/o1Km6vlarFG0/1/why-am-i-getting-a-segmentation-fault-at-runtime
CC-MAIN-2017-13
refinedweb
248
79.8
By Gary simon - Feb 10, 2018 Note: This tutorial is a part of our free course: Vue Tutorial in 2018 - Learn Vue.js by Example Handling user input with Vue.js is fairly straight forward. With the help of the v-model directive and one of several vue validation plugins for form validation. While the app we're building will only contain a single text element, we will temporarily take a look at a few other form elements so that you have a better understanding of handling form input fields with Vue. Let's get started! Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos. When you need to capture user input, you can use the v-model directive on form inputs and textareas, which enables 2-way data binding. It's very simple to use. Open up our /src/components/Skills.vue file and adjust the template section to include the following: <template> <div class="container"> <!-- Add these two lines: --> <input type="text" placeholder="Enter a skill you have.." v- {{ skill }} <!-- Remaining HTML removed for brevity --> Next, in the <script> section, add the referenced skill property in the data section: data() { return { skill: '', // Add this line skills: [ { "skill": "Vue.js" }, { "skill": "Frontend Developer" } ] } }, While we're in this file, let's style the input button in the CSS section real quick. Add this ruleset: input { width: calc(100% - 40px); border: 0; padding: 20px; font-size: 1.3em; background-color: #323333; color: #687F7F; } Save the file and start typing in the input field. You will notice that the interpolated skill property beneath the input field will demonstrate that we've captured the user input as the user types: This doesn't really do much for us though, so let's capture the user input when a form is submitted. Modify the template of our Skills.vue file to the following: <form @submit. <input type="text" placeholder="Enter a skill you have.." v- </form> Here, we're just wrapping our input with a form element. We use @submit.prevent, which submits the form and prevents a page reload, and bind it to a method called addSkill. Let's define addSkill as a method in our component logic: export default { name: 'Skills', data() { // Removed for brevity }, // Add this section: methods : { addSkill(){ this.skills.push({skill: this.skill}); this.skill = ''; } } } Here, all we're doing is defining a method called addSkill(), and when it's called, we push to the skills array defined in the data() section, and then we clear the input by resetting the skill property to an empty string. Try entering a skill and hitting the enter key. It will add it to the list beneath the input field: While our form will only contain the current text input, we will add a checkbox just for the purpose of demonstration. Modify the template as shown: <form @submit. <input type="text" placeholder="Enter a skill you have.." v- <!-- Add this line --> <input type="checkbox" id="checkbox" v- </form> In the script section add: return { checked: false, // Add this, it sets the checked property to false skill: '', Then, update the addSkill() method: addSkill(){ this.skills.push({skill: this.skill}); this.skill = ''; console.log('The checkbox value is: '+this.checked) // Add this } If you check the checkbox and enter a string in the input and hit the enter key, the console will show you that the checkbox was checked. We don't need this checkbox, so backup from the last several steps to remove the checkbox and associated code. There are several Vue form validation packages that you can install via npm or yarn. A popular validation package is called VeeValidate. VeeValidate is a powerful plugin with a lot of options, but we will use just a couple basic options to ensure that our text input validates correctly. First, we will install it in the console with yarn: > yarn add vee-validate Next, we have to add it to our /src/main.js file: import Vue from 'vue' import App from './App.vue' import VeeValidate from 'vee-validate'; // Add this Vue.use(VeeValidate); // Add this // Other code removed for brevity Great! Now we're ready to use it. Next, in /src/components/Skills.vue, modify the template: <input type="text" placeholder="Enter a skill you have.." v- <p class="alert" v-{{ errors.first('skill') }}</p> Here, we've added v-validate set to min:5 and we gave the input a name which is required for VeeValidate. Next, we're adding a new p element with a v-if directive. This states that if the errors object that VeeValidate produces has an error for skill, show the error through interpolation. Before we give this a go, let's add a quick CSS ruleset for .alert: .alert { background: #fdf2ce; font-weight: bold; display: inline-block; padding: 5px; margin-top: -20px; } If you save this, and type fewer than 5 characters, you will see this: Great. But one problem exists, it will still allow you to submit the form despite entering less than 5 characters. We can fix that by modifying the addSkill() method: addSkill() { this.$validator.validateAll().then((result) => { if (result) { this.skills.push({skill: this.skill}); this.skill = ''; } else { console.log('Not valid'); } }) } Now, if you try to hit enter with fewer than 5 characters, it will not submit. Simple! VeeValidate offers a wide variety of options that we haven't touched on, so I suggest checking out their documentation for more examples based on your needs. Remember, this tutorial is just a part of a crash course, so we can't get too in depth into any one topic. Hopefully, however, you did gain some solid fundamental-based understanding of forms in Vue! Next Lesson: Vue Animation Note: This tutorial is a part of our free course: Vue Tutorial in 2018 - Learn Vue.js by Example
https://coursetro.com/posts/code/137/Vue-Forms-Tutorial---Capturing-and-Validating-User-Input
CC-MAIN-2020-40
refinedweb
978
64.61
Question: What is a testamentary trust What is a testamentary trust? Answer to relevant QuestionsMultiple Choice Questions1. Which of the following is not a true statement?a. Testate refers to a person having a valid will.b. The laws of descent convey personal property if an individual dies without a valid will.c. .. ...A law firm is preparing to file a federal estate tax return (Form 706). The estate's executor has elected to use the alternate valuation date. The partner in charge of filing this return is not certain about all of the ...A parent company acquires from a third party bonds that had been issued originally by one of its subsidiaries. What accounting problems are created by this purchase? Post your question
http://www.solutioninn.com/what-is-a-testamentary-trust
CC-MAIN-2017-17
refinedweb
124
60.41
See Also edit - Critcl - Compiles C code embedded in a Tcl script on the fly. It can't be used for all extension work, but for many things it's good. A variation on the methods employed by Critcl allows Fortran programmers to write extensions for Tcl - it is called Critclf (not very imaginative :), I admit) and is currently under development. Contact AM for more information. -). - Executable Modules - Commands that ship off computation to external programs. - How to debug memory faults in Tcl and extensions - How to embed Tcl in C applications - There are a few extra steps to embedding Tcl, after which extending an embedded can proceed as usual. - Mktclapp - Has an API for writing extensions. It can be used to generate a stand-alone application by generating C code, or a loadable shared object library. It can also be used to convert a Tcl script or scripts into C code for compilation with a C compiler, so its use is beyond just extensions. - Stubs - Tcl extension prototype - proto.cpp - Writing extensions for stubs and pre-stubs Tcl - extension - RPC - An alternative to extending Tcl is to offload functions to another process. - SWIG - Automates the task of generating an extension. It can generate an interface for Tcl and other languages, which can then be compiled. [How well does it work? What is it good at doing?] -. - xWizard - Generate template C/C++ code for a Tcl extension. It is a GUI program written by pure Tcl/Tk so it works for cross-platform. More details in - C++ object-style Tcl example extension, by Jos Decoster - A clean, modern example of a C++ extension - Example of a Tcl extension in Fortran - Example of a Tcl extension in Free Pascal - Example of a Tcl extension in Go - Example of a Tcl extension in Swift - Example of a Tcl extension in Terra - - Minimal Tcl Extension Example - Missing the stubs verbiage. - RPN C extension for Tcl - SampleExtension - the "official" example of a Tcl C extension - useless tcl extension Basic Template editAn extension is normally compiled and linked against the Tcl stubs static archive, not the Tcl shared object. After writing the desired function in C, add an initialisation function, to be called by load, that typically initialises the Tcl stubs tables and creates new Tcl commands with Tcl_CreateCommand or better, Tcl_CreateObjCommand.The name of the initialisation function is derived from the name of the shared object. In this case the name of the shared object is tclextinfo sharedlibextension, and therefore load looks for a function called Tclext_Init. Note the initial T has been capitalised. /* /* register your functions with Tcl */ Tcl_CreateCommand( "tclextfunction", tclextfunction ); return TCL_OK; } #ifdef __cplusplus } #endifThen, in Tcl script use load tclext[info sharedlibextension]; } Tcl C API editThe Tcl C API is powerful and for something like a new data type for a tree, threads, or other things that can not be easily done with executable modules it's a good solution. an export list for a DLL] [explain how to link using MSVC++] Wrapping Existing Functions editThe approach is essentially to write a wrapper function which calls your C code. This wrapper function is in a standard format that Tcl understands. You then call a Tcl function to "register" the wrapper function with the Tcl interpreter, creating a new command. After that, every time that command is called in the interpreter, it calls the wrapper function, which calls your C code.See Extending Tcl for some pointers to some tools to help write the interface code for you. SWIG is often used, and is highly recommended. In fact, the example code in this section was generated by SWIG.Here is a very simple C function which we will integrate into the Tcl interpreter. We will create a new command called square to call this function. The C code looks like this: int square (int i) { return i*i; }Back in the "good old days" (before Tcl 8.0) everything really was a string inside of the Tcl interpreter. That made the interface functions pretty simple. They are a little like a main() function, with argc and argv. Our interface code is pretty simple, copying the argument from argv, and returning a result string. . #include <tcl.h> static int _wrap_square(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { int _result; int _arg0; _arg0 = (int) atol(argv[1]); _result = (int )square(_arg0); sprintf(interp->result,"%ld", (long) _result); return TCL_OK; }Note: This is just an example of a simple interface function. Don't do it this way any more, even though the backward-compatibility fanatics in the Tcl community continue to support all of the syntax. In particular, copying the result string into the interp->result field is not recommended. Bad things might happen.At some point in our application, we have to start up a Tcl interpreter, and register our wrapper function with the interpreter. This is usually done with a function called Tcl_AppInit(). Once this initialization is complete, your application can execute scripts from strings or files by calling Tcl_Eval() or Tcl_EvalFile(). int Tcl_AppInit(Tcl_Interp *interp){ if (Tcl_Init(interp) == TCL_ERROR) return TCL_ERROR; /* Now initialize our functions */ Tcl_CreateCommand(interp, "square", _wrap_square, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL); return TCL_OK; }Call this initialization function somewhere in your main line. First create an interpreter, then call Tcl_AppInit(). You could do this all in one fell swoop, but the Tcl_AppInit() format is standard, and supports creating extended interpreter shells - where your application actually becomes a Tcl interpreter, which is Extremely Cool!(tm) Tcl_Interp *interp; interp = Tcl_CreateInterp(); Tcl_AppInit(interp);The more modern approach to integrating Tcl applications depends on the object interface supported in Tcl versions 8.0 and higher. The object model supports the on-the-fly bytecode compiler, and is very efficient for integrating C code. It is not necessary to shimmer values back and forth to strings. Unfortunately, the object interface is a little more complex, with special functions to convert from Tcl_Objs to basic types. You should also do a little more careful parsing of arguments, and even generate error messages if the Tcl command is malformed. Again, SWIG is a great tool that can generate all this for you. But you can still do it yourself. The new object interface function might look like this: static int _wrap_square(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { int _result; int _arg0; Tcl_Obj * tcl_result; int tempint; clientData = clientData; objv = objv; tcl_result = Tcl_GetObjResult(interp); if ((objc < 2) || (objc > 2)) { Tcl_SetStringObj(tcl_result,"Wrong # args. square i ",-1); return TCL_ERROR; } if (Tcl_GetIntFromObj(interp,objv[1],&tempint) == TCL_ERROR) return TCL_ERROR; _arg0 = (int ) tempint; _result = (int )square(_arg0); tcl_result = Tcl_GetObjResult(interp); Tcl_SetIntObj(tcl_result,(long) _result); return TCL_OK; }And, you would, of course, register this new command as an object command. The rest of the initialization remains the same Tcl_CreateObjCommand(interp, SWIG_prefix "square", _wrap_square, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL); $
http://wiki.tcl.tk/6276
CC-MAIN-2016-44
refinedweb
1,138
52.8
I'm just grepping some Xliff files for the pattern approved="no" grep 'approved="no"' FILE def grep(pattern, file_path): ret = False with codecs.open(file_path, "r", encoding="utf-8") as f: while 1 and not ret: lines = f.readlines(100000) if not lines: break for line in lines: if re.search(pattern, line): ret = True break return ret Python, being an interpreted language vs. a compiled C version of grep will always be slower. Apart from that your Python implementation is not the same as your grep example. It is not returning the matching lines, it is merely testing to see if the pattern matches the characters on any one line. A closer comparison would be: grep -q 'approved="no"' FILE which will return as soon as a match is found and not produce any output. You can substantially speed up your code by writing your grep() function more efficiently: def grep_1(pattern, file_path): with io.open(file_path, "r", encoding="utf-8") as f: while True: lines = f.readlines(100000) if not lines: return False if re.search(pattern, ''.join(lines)): return True This uses io instead of codecs which I found was a little faster. The while loop condition does not need to check ret and you can return from the function as soon as the result is known. There's no need to run re.search() for each individual ilne - just join the lines and perform a single search. At the cost of memory usage you could try this: import io def grep_2(pattern, file_path): with io.open(file_path, "r", encoding="utf-8") as f: return re.search(pattern, f.read()) If memory is an issue you could mmap the file and run the regex search on the mmap: import io import mmap def grep_3(pattern, file_path): with io.open(file_path, "r", encoding="utf-8") as f: return re.search(pattern, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) mmap will efficiently read the data from the file in pages without consuming a lot of memory. Also, you'll probably find that mmap runs faster than the other solutions. Using timeit for each of these functions shows that this is the case: 10 loops, best of 3: 639 msec per loop # grep() 10 loops, best of 3: 78.7 msec per loop # grep_1() 10 loops, best of 3: 19.4 msec per loop # grep_2() 100 loops, best of 3: 5.32 msec per loop # grep_3() The file was /usr/share/dict/words containing approx 480,000 lines and the search pattern was zymurgies, which occurs near the end of the file. For comparison, when pattern is near the start of the file, e.g. abaciscus, the times are: 10 loops, best of 3: 62.6 msec per loop # grep() 1000 loops, best of 3: 1.6 msec per loop # grep_1() 100 loops, best of 3: 14.2 msec per loop # grep_2() 10000 loops, best of 3: 37.2 usec per loop # grep_3() which again shows that the mmap version is fastest. Now comparing the grep command with the Python mmap version: $ time grep -q zymurgies /usr/share/dict/words real 0m0.010s user 0m0.007s sys 0m0.003s $ time python x.py grep_3 # uses mmap real 0m0.023s user 0m0.019s sys 0m0.004s Which is not too bad considering the advantages that grep has.
https://codedump.io/share/bw7LGxGcqxM3/1/python-grep-code-much-slower-than-command-line39s-grep
CC-MAIN-2017-09
refinedweb
558
75.91
Building a gRPC Client in .NET Introduction In this article, we will take a look at how to create a simple gRPC client with .NET and communicate with a server. This is the final post of the blog series where we talk about building gRPC services. Motivation This is the fifth part of an articles series on gRPC. If you didn’t catch the previous ones please feel free to do so. The links are down below. - Introduction to gRPC - Building a gRPC server with Go - Building a gRPC client with .NET - Building a gRPC client with Go - Building a gRPC client with .NET (You are here) Please note that this is intended for anyone who’s interested in getting started with gRPC. If you’re not, please feel free to skip this article. Plan The plan for this article is as follows. - Scaffold a .NET console project. - Implementing the gRPC client. - Communicating with the server. In a nutshell, we will be generating the client for the server we built in our previous post. 💡 As always, all the code samples documentation can be found at: Prerequisites - .NET 6 SDK - Visual Studio Code or IDE of your choice - gRPC compiler Please note that I’m using some of the commands that are macOS specific. Please follow this link to set it up if you are on a different OS. To install Protobuf compiler: brew install protobuf Project Structure We can use .NET’s tooling to generate a sample gRPC project. Run the following command at the root of your workspace. Remember how we used dotnet new grpc command to scaffold the server project? For this one though, it can simply be a console app. dotnet new console -o BookshopClient Your project structure should look like this. You must be wondering if this is a console app how does it know how to generate the client stubs? Well, it doesn’t. You have to add the following packages to the project first. dotnet add BookshopClient.csproj package Grpc.Net.Client dotnet add BookshopClient.csproj package Google.Protobuf dotnet add BookshopClient.csproj package Grpc.Tools Once everything’s installed, we can proceed with the rest of the steps. Generating the client stubs We will be using the same Protobuf files that we generated in our previous step. If you haven’t seen that already head over to my previous post. Open up the BookshopClient.csproj file you need to add the following lines: ... <ItemGroup> <Protobuf Include="../proto/bookshop.proto" GrpcServices="Client" /> </ItemGroup> ... As you can see we will be reusing our Bookshop.proto file. in this example too. One thing to note here is that we have updated the GrpcServices attribute to be Client. Implementing the gRPC client Let’s update the Program.cs file to connect to and get the response from the server. using System.Threading.Tasks; using Grpc.Net.Client; using Bookshop; // The port number must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress(""); var client = new Inventory.InventoryClient(channel); var reply = await client.GetBookListAsync(new GetBookListRequest { }); Console.WriteLine("Greeting: " + reply.Books); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); This is based on the example given on the Microsoft docs site btw. What I really like about the above code is how easy it is to read. So here’s what happens. - We first create a gRPC channel with GrpcChannel.ForAddressto the server by giving its URI and port. A client can reuse the same channel object to communicate with a gRPC server. This is an expensive operation compared to invoking a gRPC method on the server. You can also pass in a GrpcChannelOptionsobject as the second parameter to define client options. Here’s a list for that. - Then we use the auto-generated method Inventory.InventoryClientby leveraging the channel we created above. One thing to note here is that, if your server has multiple services, you can still use the same channelobject for all of those. - We call the GetBookListAsyncon our server. By the way, this is a Unary call, we will go through other client-server communication mechanisms in a separate post. - Our GetBookListmethod gets called on the server and returns the list of books. Now that we know how the requests work, let’s see this in action. Communicating with the server Let’s spin up the server that we built in my previous post first. This will be up and running at port 5000. dotnet run --project BookshopServer/BookshopServer.csproj For the client-side, we invoke a similar command. dotnet run --project BookshopClient/BookshopClient.csproj And in the terminal, we will get the following outputs. Nice! as you can see it’s not that hard to get everything working 🎉 One thing to note is that we left out the details about TLS and different ways to communicate with the server (i.e. Unary, streaming etc.). I will cover such topics in-depth in the future. Conclusion In this article, we looked at how to reuse our Protobuf files to create a client to interact with the server we created in the previous post. I hope this article series cleared up a lot of confusion that you had about gRPC. Please feel free to share your questions, thoughts, or feedback in the comments section below. Until next time 👋
https://sahansera.dev/building-grpc-client-dotnet/
CC-MAIN-2022-33
refinedweb
887
69.58
0 Hello everyone. I am trying to work through a programming challenge in my c++ book. I have gotten it to work, but i kind of cheated by looking at the file. I am going to past the entire code so i can be compiled, but the main problem i am having is with reading the last line of a file only. #include <iostream> #include <fstream> using namespace std; void dispJoke ( fstream& ); void dispPunchLine ( fstream& ); int main() { fstream joke ( "joke.txt", ios::in ); fstream punch ( "punchline.txt", ios::in ); if ( !joke ) { cout << "Erorr opening file, joke.txt"; return 0; } else if ( !punch ) { cout << "Erorr opening file, punchline.txt"; return 0; } dispJoke(joke); system("pause"); dispPunchLine(punch); joke.close(); punch.close(); return 0; } void dispJoke ( fstream& joke ) { char data[256]; joke.getline ( data, 256 ); while ( !joke.eof() ) { cout << data << endl; joke.getline ( data, 256 ); } } void dispPunchLine ( fstream& punch ) { char data[256]; punch.seekg(-35L, ios::end ); punch.getline ( data, 256, '.' ); while ( !punch.eof() ) { cout << data << endl; punch.getline ( data, 256, '.' ); } } the contents of file punchline.txt are: asfasdfasdfasdfsdf asdfasdfsadfsadfsadf asdfsadfsdfsdf "I can't work in the dark," he said. I was trying to use the seekg member function. Am i thinking the right way about this? How do i (if i didnt look at the file) determine where to start printing the data if all i want is the last line, not the "garbage" in this test file. Any advice is much appreciated! Thank you Jason
https://www.daniweb.com/programming/software-development/threads/154664/help-reading-data-from-a-file
CC-MAIN-2016-50
refinedweb
245
79.77
Thanks, Mike! We definitely appreciate the feedback. Here are some additional points that I don't think we've yet spelled out clearly. The XMPPService/GTalkService really only has 2 goals: 1) provide a way to efficiently send simple P2P-style messages (in the form of Intents) between handsets, and. This is not a value judgment on XMPP. XMPP supports a broad range of functionality (such as federation) that are outside the scope of what we intend the Service to be used for. The reasons we are using a different protocol are generally to reduce bandwidth and processor overhead, and to improve startup/connection times. So it's not that we don't like XMPP, it's simply that we are trying to solve a different problem. Earlier I suggested that developers who want full standards-compliant XMPP access should use a third-party XMPP library in their applications. However, Davanum Srinivas suggested instead that interested developers create a reusable XMPP Service that has full support for the protocol. I have to agree that that's a much better idea than mine! Hope that clears things up a little, - Dan > More discussion on the subject, and I have to say I agree with the > comments there as well. XMPP inclusion was what excited me most about > Android and this is a major let down... > > Mike > On Feb 15, 12:00 pm, hackbod <hack...@gmail.com> wrote: > > On Feb 15, 10:19 am, fry <bender...@gmail.com> wrote: > > > If I would like to create my own Jabber IM client, it would be weird > > > if I have to build it over API of another IM client (gtalk) - even if > > > "com.google.android.gtalkservice" would contain same classes as > > > "com.google.android.xmppService" did, it would still look weird. > > We are actually fairly careful about what is part of the generic > > platform, and what is not. Specifically, things in the com.google.* > > namespaces are Google-specific APIs that are not part of the core > > platform: that is, you can create a device without any of the Google > > services in those namespaces and still have a working system. This is > > why they are listed in the separate "Google APIs" part of the > > documentation. Correspondingly, given a device that doesn't include > > the APIs, a third party can install on that device a separate .apk > > that provides the same features and works just like the one we are > > shipping with our platform. > > I can't address the specific situation of XMPP or GTalk, but I wanted > > to give an overview of where these fit in to the larger platform > > picture. In general, I don't think these are APIs that we can provide > > as a standard part of the platform, since they rely on an external > > service that may not be available. In this sense they are very > > different than SMS, which is a standard feature available to every > > phone.
http://groups.google.com/group/android-developers/msg/26ae3bf24372c2d4
crawl-001
refinedweb
485
62.07
Well, I couldn't resist... as I mentioned in the last post - where we looked at creating a simple graph inside AutoCAD as an example of modifying objects inside nested transactions - the idea of graphing inside AutoCAD is a good fit for F#. This is for a number of reasons: F# is very mathematical in nature and excels at processing lists of data. I also spiced it up a bit by adding some code to parallelise some of the mathematical operations, but that didn't turn out to be especially compelling with my dual-core laptop. More on that later. Here's the F# code: // Use lightweight F# syntax #light // Declare a specific namespace and module name module Grapher.Commands // Import managed assemblies open Autodesk.AutoCAD.Runtime open Autodesk.AutoCAD.ApplicationServices open Autodesk.AutoCAD.DatabaseServices open Autodesk.AutoCAD.Geometry // Define a common normalization function which makes sure // our graph gets mapped to our grid let normalize fn normFn x minInp maxInp maxOut = let res = fn ((maxInp - minInp) * x / maxOut) let normRes = normFn res if normRes >= 0.0 && normRes <= 1.0 then normRes * (maxOut - 1.0) else -1.0 // Define some shortcuts to the .NET Math library // trigonometry functions let sin x = System.Math.Sin x let cos x = System.Math.Cos x let tan x = System.Math.Tan x // Implement our own normalized trig functions // which each map to the size of the grid passed in let normSin max x = let nf a = (a + 1.0) / 2.0 // Normalise to 0-1 let res = normalize sin nf (Int32.to_float x) 0.0 (2.0 * System.Math.PI) (Int32.to_float max) Int32.of_float res let normCos max x = let nf a = (a + 1.0) / 2.0 // Normalise to 0-1 let res = normalize cos nf (Int32.to_float x) 0.0 (2.0 * System.Math.PI) (Int32.to_float max) Int32.of_float res let normTan max x = let nf a = (a + 3.0) / 6.0 // Normalise differently for tan let res = normalize tan nf (Int32.to_float x) 0.0 (2.0 * System.Math.PI) (Int32.to_float max) Int32.of_float res // Now we declare our command [<CommandMethod("graph")>] let gridCommand() = // We'll time the command, so we can check the // sync vs. async efficiency let starttime = System.DateTime.Now // size rad offset = let ids = new ObjectIdCollection() for i = 0 to size - 1 do for j = 0 to size - 1 do let pt = new Point3d (offset * (Int32.to_float i), offset * (Int32.to_float j), 0.0) let id = createCircle pt rad ids.Add(id) |> ignore ids // Function to change the colour of an entity let changeColour col (id : ObjectId) = if id.IsValid then let ent = tr.GetObject(id, OpenMode.ForWrite) :?> Entity ent.ColorIndex <- col // Shortcuts to make objects red and yellow let makeRed = changeColour 1 let makeYellow = changeColour 2 // Function to retrieve the contents of our // array of object IDs - this just calculates // the index based on the x & y values let getIndex fn size i = let res = fn size i if res >= 0 then (i * size) + res else -1 // Apply our function synchronously for each value of x let applySyncBelowMax size fn = [| for i in [0..size-1] -> getIndex fn size i |] // Apply our function asynchronously for each value of x let applyAsyncBelowMax size fn = Async.Run (Async.Parallel [ for i in [0..size-1] -> async { return getIndex fn size i } ]) // Hardcode the size of the grid and create it let size = 50 let ids = createGrid size 0.5 1.2 // Make the circles all red to start with Seq.iter makeRed (Seq.cast ids) // From a certain index in the list, get an object ID let getId i = if i >= 0 then ids.[i] else ObjectId.Null // Apply one of our trig functions, synchronously or // otherwise, to our grid applySyncBelowMax size normSin |> Array.map getId |> Array.iter makeYellow // Commit the transaction tr.Commit() // Check how long it took let elapsed = System.DateTime.op_Subtraction (System.DateTime.Now, starttime) ed.WriteMessage ("\nElapsed time: " + elapsed.ToString()) Here's what you see on AutoCAD's drawing canvas when you run the GRAPH command as it stands: If you want to play around with other functions, you can edit the call to applySyncBelowMax to pass normCos or normTan instead of normSin. As I mentioned earlier, if you swap the call to be applyAsyncBelowMax instead of applySyncBelowMax you will actually run the mathematics piece as asynchronous tasks. These are CPU-bound operations - they don't call across the network or write to a hard-drive, which might have increased the benefit of calling them asynchronously - so right now the async version actually runs more slowly than the sync version. If I were to have more processing cores available to me, it might also give us more benefit, but right now with my dual-core machine there's more effort spent coordinating the tasks than you gain from the parallelism. But I'll let you play around with that yourselves... you may get better results. One other note on that piece of the code: at some point I'd like to make use of the Parallel Extensions for .NET (in particular the Task Parallel Library (TPL)), but for now I've continued with what I know, the asynchronous worklows capability which is now standard in F#. I'm travelling in India this week (and working from our Bangalore office next week), so this is likely to be my last post of the week. Recent Comments Archives More...
http://through-the-interface.typepad.com/through_the_interface/2009/01/index.html
CC-MAIN-2013-20
refinedweb
906
66.74
GET_PHYS_PAGES(3) Linux Programmer's Manual GET_PHYS_PAGES(3) get_phys_pages, get_avphys_pages - get total and available physical page counts #include <sys/sysinfo.h> long get_phys_pages(void); long error. ENOSYS The system could not provide the required information (possibly because the /proc filesystem was not mounted). These functions are GNU extensions. Before glibc 2.23, these functions obtained the required information by scanning the MemTotal and MemFree fields of /proc/meminfo. Since glibc 2.23, these functions obtain the required information by calling sysinfo(2).); } sysconf(3) This page is part of release 5.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. GNU 2021-03-22 GET_PHYS_PAGES(3) Pages that refer to this page: undocumented(3)
https://man7.org/linux/man-pages/man3/get_avphys_pages.3.html
CC-MAIN-2022-33
refinedweb
132
53.27
DataTempletes are visual representation of data .Consider a case you are supposed to show all the Client list in a combo box along with their Phone Number and Email Address , how will you achieve it?? This was practically impossible with previous technology until unless bit extra work around.So here do Microsoft offers richness in User experience with DataTemplete concept.I am not going to cover basics of DataTemplete but if you are a newbie to Silverlight and just started on Silverlight then read some basics of DataTemplete and continue with rest of article. DataTemplete Evolved , Implicit DataTempleteAs we know until now Silverlight Supported applying datatemplete to the controls not Databut in Silverlight 5 enables the template to attach itself to data object type rather than control only.How ever the same feature is there in WPF since long but Microsoft introduced this concept to web RIA with silverlight 5 Beta ,naming Implicit DataTemplete.Considering that you have a basic idea about datatemplete i am going to put forward a practical example with implementation.Let me know if you have any other ideas or suggestions. Implicit DataTemplete , the Key Points Implicit Datatemplete means template for Data Type not control. No or Zero dependency on Control type Useful for Composite collection , Collection with Different Data Objects The Case StudyLets consider a case study for a HR of a company , for whom you are planning for LOB application ,I am the HR executive of a organisation and my job demands employees information on my finger tip.I have a application that shows up the list of my employee with their respective information.And based on our policy the employees can be of two type Regular Employee Hourly Employee(Contractual)The Regular Employees have salary option on monthly basis however the contractual employees have remuneration on hourly basis.Also the regular employee are going to have company domain mail ids.Based on above requirement the class diagram comes up with somehow as bellow Now the one of your page requires to show all employees (With in a collection of Employee) with their information .And the problem here with earlier approach is that your DataTemplete for the list box must vary based on the data and also the visual representation for employees must be same irrespective of controls ,either in List or Combo box.Here Implicit DataTemplete comes to our rescue. Implementing DataTempleteAs mentioned above , i am going to load all employees both Regular and Hourly to the list box .The List box has no idea how the data is going to display.In first step i am going to define a DataTemplete in App.Xaml Resource.As earlier we used to do, the DataTemplete usually carries a key and the key used to be assigned to control .But ..Here in implicit method instead of Key we are going to add DataType attribute to the datatemplete. Make sure that you have imported the namespace of the types you are going to use.Here my emp indicated my namespace for EmployeeClasses. So as you can see i have two datatempletes defined for 2 different type such as HourlyEmplyee and RegularEmployee.Each of the template defined in such a way that the employees can be identified easily with in a collection. A typical piece of DataTemplete Xaml wrapped inside a stackPanel and Grid ,can be found as bellow Well if you have covered till here then the concept of Implicit DataTemplete is over , assigning the data type to the datatemplete will do the rest of job.Now lets check with the main page of project . As you can check with the code bellow the main page with 2 controls doesnot have any logic or whatsoever in the xaml In this sample the data has been assigned to the both controls on user control load event .The same can be achieved with declarative databinding too.The _employees are getting generated on pageload event with some dummy value.I hope readers will not bother about the source of data . private void UserControl_Loaded(object sender, RoutedEventArgs e) { lstEmployees.ItemsSource = _employees; cmbEmployees.ItemsSource = _employees; } Lets Run.Well the the application is ready to run with no efforts any where else. private void UserControl_Loaded(object sender, RoutedEventArgs e) { lstEmployees.ItemsSource = _employees; cmbEmployees.ItemsSource = _employees; } ConclusionThe feature gives us a immense flexibility for data presentation ,I don't know how we managed so long with out it.Your suggestion and comments are always welcome .Let us know how it is going to help you in your application context. Source Code and LinkLive Link -: HereDownload Source Code-: ImplicitDataTemplate.zipMake sure that you have downloaded latest Silverlight SDK , if not visit this post for more information on Silverlight 5 Beta Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/kb/3937-implicit-datatemplates-silverlight-5-with.aspx
CC-MAIN-2017-17
refinedweb
801
53.31
Details Description Analysis shows that ---------------------------------------------------------------------- The problem is occurring starting at offset 2007 in method e23. There is an invokeinterface to method setWidth(int, int, boolean) of class VariableSizeDataValue. This invoke returns a value of class DataValueDescriptor. That value is in turn stored in field e142 at offset 2015 in method e23. The problem is that field e142 is a NumberDataValue, and DataValueDescriptor is not a valid subclass of NumberDataValue. Thus the store is not allowed. ---------------------------------------------------------------------- Looking at the generated setWidth() calls I see one in BinaryOperatorNode where the return (DataValueDescriptor) is not cast to the type of the field it is stored in.
https://issues.apache.org/jira/browse/DERBY-488?attachmentSortBy=fileName
CC-MAIN-2019-22
refinedweb
104
65.01
package Win32::EnvProcess; use 5.006001; use strict; use warnings; use Carp; require Exporter; use AutoLoader; our @ISA = qw(Exporter); # Items to export into callers namespace by default. # This allows declaration use Win32::EnvProcess ':all'; our %EXPORT_TAGS = ( 'all' => [ qw(SetEnvProcess GetEnvProcess DelEnvProcess GetPids ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} }, 'SetEnvProcess', 'GetEnvProcess', 'DelEnvProcess', 'GetPids' ); our @EXPORT = qw( ); our $VERSION = '0.06'; sub AUTOLOAD { # This AUTOLOAD is used to 'autoload' constants from the constant() # XS function. my $constname; our $AUTOLOAD; ($constname = $AUTOLOAD) =~ s/.*:://; croak "&Win32::EnvProcess::constant not defined" if $constname eq 'constant'; my ($error, $val) = constant($constname); if ($error) { croak $error; } { no strict 'refs'; # Fixed between 5.005_53 and 5.005_61 #XXX if ($] >= 5.00561) { #XXX *$AUTOLOAD = sub () { $val }; #XXX } #XXX else { *$AUTOLOAD = sub { $val }; #XXX } } goto &$AUTOLOAD; } require XSLoader; XSLoader::load('Win32::EnvProcess', $VERSION); # Preloaded methods go here. # Autoload methods go after =cut, and are processed by the autosplit program. 1; __END__ =head1 NAME Win32::EnvProcess - Perl extension to set or get environment variables from other processes =head1 SYNOPSIS use Win32::EnvProcess qw(:all); use Win32::EnvProcess qw(SetEnvProcess); my $result = SetEnvProcess($pid, env_var_name, [value], [...]); use Win32::EnvProcess qw(GetEnvProcess); my @values = GetEnvProcess($pid, [env_var_name, [...]]); use Win32::EnvProcess qw(DelEnvProcess); my $result = DelEnvProcess($pid, env_var_name, [...]); use Win32::EnvProcess qw(GetPids); my @pids = GetPids([exe_name]); =head1 DESCRIPTION This module enables the user to alter or query an unrelated process's environment variables. Windows allows a process with sufficient privilege to run code in another process by attaching a DLL. This is known as "DLL injection", and is used here. =head1 NON-STANDARD INSTALLATION STEP The DLL used for injection is named EnvProcessDll.dll, and does not contain any perl components. It must be copied to a directory (folder) that is on the load path OF THE TARGET PROCESS. If you are not sure where that is, try C:\Perl\bin (we presumably have perl installed, and it is probably in everyone's path). This is done by the tests by default. Failing that, WINDOWS\system32 should work. copy .\blib\arch\auto\Win32\EnvProcess\EnvProcessDll.dll some-directory You do not have to use the command-line for the copy, drag-and-drop with Windows Explorer is probably easier. =head1 EXPORT None by default. =head2 SetEnvProcess my $result = SetEnvProcess($pid, env_var_name, [value], ...); $pid: The process identifier (PID) of the target process. If set to 0 (zero) the parent process identifier is used env_var_name: The name of the environment variable to be set value: The value of the preceeding environment variable Set one or more environment variables in another process. The env_var_name/value pairs may be repeated as a list or, more conviently as a hash, with the keys being the environment variable names. You should avoid changing critcal process specific variables such as USERNAME. Also be aware that there is no guarantee that the program will actually use the new value. For example it may have already read the value on start-up and may be holding it internally, the perl interpreter is such a program (see C<Interaction with perl scripts> below). If an odd number of items is supplied in the list, the final variable specified will have no value. Note that this is not the same as deleting a variable. Returns: the number of environment variables changed. Error information will be available in $^E (See below). =head2 GetEnvProcess my @values = GetEnvProcess($pid, [env_var_name, [...]]); $pid: The process identifier (PID) of the target process. If set to 0 (zero) the parent process identifier is used env_var_name: The name[s] of the environment variable[s] to be read. If not supplied then as many environment variables as possible are returned (see C<LIMITATIONS> below). Get one or more environment variable values from another process. Returns undef on error, error information will be available in $^E. If one or more environment variable name are specified, a list of environment variable values is returned. Note that these may be empty strings if no value is set. If a requested variable does not exist then an empty string is returned in it's place in the list, and $^E will be set to 203 (ERROR_ENVVAR_NOT_FOUND). If no environment variable names are specified then the environment block is returned (subject to LIMITATIONS) in the form of a list. Items are of the form variable=value and may be extracted into a hash as follows: @values = GetEnvProcess (0); my %proc_env; for (@values) { my ($key, $value) = split /=/; $proc_env{$key} = $value; } =head2 DelEnvProcess my $result = DelEnvProcess($pid, env_var_name, ...); $pid: The process identifier (PID) of the target process. If set to 0 (zero) the parent process identifier is used env_var_name: The name of the environment variable to be deleted Delete one or more environment variables in another process. The env_var_name may be repeated as a list. You should avoid deleting critcal process specific variables such as USERNAME and PATH. Also be aware that the program may have already read the value on start-up and may be holding it internally, the perl interpreter is such a program (see C<Interaction with perl scripts> below). Returns: the number of environment variables deleted. Error information will be available in $^E (See below). =head2 GetPids my @pids = GetPids([exe_name]); exe_name: The basename of an executable file (including the '.exe') If supplied, a case-insensitive match is done between the exe name and running processes. If not supplied, then the identifier of the parent process is returned. Returns: A list of process-ids of processes running the supplied exe, or zero on error. This function is provided to assist in obtaining the required process id. Security may prevent some processes from being queried. When this is the case it is unlikely that we have the permissions to manipulate the environment block. The .exe files registered with a process may be in 8.3 format, and currently this function makes no attempt to resolve a 'long name' to short. =head1 $^E ($EXTENDED_OS_ERROR) VALUES The most likely causes of certain Win32 errors are given below: =head3 8 Not enough storage is available to process this command. The total data for the environment variables exceeds C<LIMITATIONS>. In this case as much processing as possible will be done. =head3 14 Not enough storage is available to complete this operation. The number of environment variables exceeds C<LIMITATIONS> =head3 87 The parameter is incorrect. The supplied PID does not exist =head3 183 Cannot create a file when that file already exists. Under most circumstances this error may be ignored when correct results are returned. It generally means that more than one process (or thread) is using this module. =head3 186 The flag passed is not correct. Internal corruption of the FMO, please contact the author =head3 203 The system could not find the environment option that was entered The requested environment variable does not exist =head1 LIMITATIONS Total size of variable names and values: 8192 (increased at v.0.05). Total number of environment variables : 254 (increased at v.0.05). These are artificial limits and may be made more flexible in a future release. Locking: the entire sequence is serial because a named FMO is used. Creating the File Mapping Object(FMO), writing to it, and running the DLL in the other process, is protected by a Mutex. It is therefore possible that calls may block. =head2 Interaction with perl scripts If the target process is a perl script, then note that the script will not 'see' the new variable or value through C<%ENV>. This hash is set at process creation time, and not directly updated through these functions. A perl script can however inspect its own environment using C<GetProcessEnv> with the first argument set to C<$$>. =head1 SEE ALSO Win2::Env, Env::C =head1 AUTHOR C. B. Darke, clive.darke@ talk21.com open to suggestions for improvements. =head1 COPYRIGHT AND LICENSE Copyright (C) 2008 by C. B. Darke This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.6.1 or, at your option, any later version of Perl 5 you may have available. =cut
https://metacpan.org/release/Win32-EnvProcess/source/lib/Win32/EnvProcess.pm
CC-MAIN-2021-10
refinedweb
1,353
56.25
Post your Comment String Reverse Using StringUtils String Reverse Using StringUtils In this example we are going to reverse a given string using StringUtils api. In this example we are reversing a string and the reversed Reverse String using Stack Reverse String using Stack You all are aware of Stack, a data structure... the string using these operations. Here is the code: import java.util.... in the reverse order from that in which they are added. The push operation String reverse program String reverse program write a java program for reverse string? if the string is "Hi welcome to hyderabad" the reverse string is "hyderabad... for help. You can split the String into String array using split method of String print reverse string without api print reverse string without api accept a string and print reverse without using api Reverse Reverse How to reverse two digits in javaprogramming String reverse in java "; String reverse=""; //Using String Buffer System.out.println("Using... System.out.println("Using String Builder "); reverse = new...String reverse in java In this section we are going to discuss about how reverse reverse program to read a string and print the reverse string  ... ReverseString{ public static void main(String[]args){ Scanner input=new Scanner(System.in); System.out.print("Enter String: "); String st PHP Array Sort in Reverse Order in reverse order. There are rsort(), arsort(), and krsort()functions in PHP. By using...PHP Array Sort in Reverse Order Hi, I have just started learning... the PHP Array Sort in Reverse Order. Please suggest any online reference or example String Reverse in Java the input string by using the StringBuffer(String string) method, reverse... String Reverse in Java In this example we are going to reverse a given string JavaScript reverse text string ; In this section, we are going to reverse the text string using JavaScript... JavaScript reverse text string..., you will get the reverse string in the same text box. Here is the code A Program To Reverse Words In String in Java A Program To Reverse Words In String in Java A Program To Reverse Words In String in Java for example: Input:- Computer Software Output :- Software Computer without using split() , StringTokenizer function or any extra Java reverse words in a string using only loops Java reverse words in a string using only loops In this tutorial, you will learn how to reverse words in a string without using any inbuilt methods like...;=c.length;i++) { if(i==c.length) { reverse(c,word_start_index,i-1); } else String Reverse In Java Example will demonstrate you about how to reverse a String using StringBuilder's... this String using StringBuilder's reverse() method. Then we will create a method using which we will reverse a String by applying own logic. In this method JavaScript array reverse example by using the method reverse(). Here is the full example code of JavaScript array... JavaScript array reverse example JavaScript Array class have one method reverse() which Java reverse number the user to enter the number and reverse it by using basic programming concepts...Java reverse number In this tutorial, you will learn how to reverse a number...(/) and remainder operator(%) to reverse the number. The division operator returns Java Reverse String Pattern Java Reverse String Pattern In this section, we have displayed a string in reverse pattern. For this,we have specified a string which is first converted into character array and then print it. Then we have reversed the string using C String Reverse C String Reverse In this section, you will study how to reverse a string. You can see... the method, we are calculating the length of a specified string using a library function Java Reverse words of the String Reverse words of the String Java Programming In this section, we are going to reverse the words of the string. For this, we have allowed the user to enter the string. Then we have converted the string into tokens using StringTokenizer Java reverse string without using inbuilt functions Java reverse string without using inbuilt functions In this tutorial, you will learn how to reverse string without using any inbuilt functions. Here, we have created a method to reverse the string and returns a new string with reverse Reverse String Program in Java in String Java reverse string without using inbuilt functions...Reverse String Program in Java We are going to describe about reverse...[]) { String string, reverse = ""; Scanner in = new Scanner reverse the charstring reverse the charstring how to reverse any character of the string reverse string reverse string how to reverse a string without changing its place...=input.nextLine(); String reverse = new StringBuffer(str).reverse().toString...{ public static void main(String[]args){ Scanner input=new Scanner reverse alphabet reverse alphabet e d c b a d c b a c b a b a a code for this pattern in c language reverse indexing reverse indexing how to list out all the pages names that have keyword common in them when pages names and their respective keywords are given as input in text file format reverse albhabet reverse albhabet e d c b a d c b a c b a code for this pattern Here is a code that displays... class Pattern{ public static void main(String[]args){ int i, j, k, m reverse arrays in java reverse arrays in java how do i make a code that can be used to reverse the elements of an array in two dimension such that the last element of an array becomes the first element of the array and the first element of an array Reverse integer array program Reverse integer array program Been tasked with the following... with all the elements in reverse order. For example, if the input array is [2, 4, 6, 8.... I have this so far: public static int [] reverse (int a[]){ for ( int Post your Comment
http://www.roseindia.net/discussion/18901-String-Reverse-Using-StringUtils.html
CC-MAIN-2014-49
refinedweb
982
58.32
SVIPC(7) Linux Programmer's Manual SVIPC(7) sysvipc - System V interprocess communication mechanisms System V IPC is the name given to three interprocess communication mechanisms that are widely available on UNIX systems: message queues, semaphore, and shared memory. Message queues System V message queues allow data to be exchanged in units called messages. Each messages can have an associated priority, POSIX message queues provide an alternative API for achieving the same result; see mq_overview(7). The System V message queue API consists of the following system calls: msgget(2) Create a new message queue or obtain the ID of an existing message queue. This call returns an identifier that is used in the remaining APIs. msgsnd(2) Add a message to a queue. msgrcv(2) Remove a message from a queue. msgctl(2) Perform various control operations on a queue, including deletion. Semaphore sets System V semaphores allow processes to synchronize their actions. System V semaphores are allocated in groups called sets; each semaphore in a set is a counting semaphore. POSIX semaphores provide an alternative API for achieving the same result; see sem_overview(7). The System V semaphore API consists of the following system calls: semget(2) Create a new set or obtain the ID of an existing set. This call returns an identifier that is used in the remaining APIs. semop(2) Perform operations on the semaphores in a set. semctl(2) Perform various control operations on a set, including deletion. Shared memory segments System V shared memory allows processes to share a region a memory (a "segment"). POSIX shared memory is an alternative API for achieving the same result; see shm_overview(7). The System V shared memory API consists of the following system calls: shmget(2) Create a new segment or obtain the ID of an existing segment. This call returns an identifier that is used in the remaining APIs. shmat(2) Attach an existing shared memory object into the calling process's address space. shmdt(2) Detach a segment from the calling process's address space. shmctl(2) Perform various control operations on a segment, including deletion. IPC namespaces For a discussion of the interaction of System V IPC objects and IPC namespaces, see ipc_namespaces(7). ipcmk(1), ipcrm(1), ipcs(1), lsipc(1), ipc(2), msgctl(2), msgget(2), msgrcv(2), msgsnd(2), semctl(2), semget(2), semop(2), shmat(2), shmctl(2), shmdt(2), shmget(2), ftok(3), ipc_namespaces(7) This page is part of release 5.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2020-04-11 SVIPC(7) Pages that refer to this page: ipcmk(1), ipcrm(1), ipcs(1), lsipc(1), intro(2), ipc(2), msgctl(2), msgget(2), msgop(2), semctl(2), semget(2), semop(2), shmctl(2), shmget(2), shmop(2), ftok(3), proc(5), systemd.exec(5), ipc_namespaces(7)
https://man7.org/linux/man-pages/man7/svipc.7.html
CC-MAIN-2021-43
refinedweb
492
55.34
13 January 2012 10:39 [Source: ICIS news] SINGAPORE (ICIS)--Methanex hopes to restart its second 850,000 tonne/year methanol plant in ?xml:namespace> The company’s other unit with the same capacity is currently operating smoothly, the source said. Its existing natural gas contracts only allow the firm to continue operating the first methanol plant at Motunui through 2011 and 2012, the company official said. The firm has a total of 1.38m tonnes/year of idled capacity in Meanwhile, the firm is running at its 1.3m tonne/year EMethanex methanol facility at Methanol can be found in everything from windshield washer fluid to plywood floors to paint and acetic
http://www.icis.com/Articles/2012/01/13/9523458/methanex-eyes-h2-restart-for-second-new-zealand-methanol-plant.html
CC-MAIN-2014-42
refinedweb
113
62.48
remoto 0.0.16 Execute remote commands or processes. remoto A very simplistic remote-command-executor using ssh and Python in the remote end. All the heavy lifting is done by execnet, while this minimal API provides the bare minimum to handle easy logging and connections from the remote end. remoto is a bit opinionated as it was conceived to replace helpers and remote utilities for ceph-deploy a tool to run remote commands to configure and setup the distributed file system Ceph. Example Usage The usage aims to be extremely straightforward, with a very minimal set of helpers and utilities for remote processes and logging output. The most basic example will use the run helper to execute a command on the remote end. It does require a logging object, which needs to be one that, at the very least, has both error and debug. Those are called for stderr and stdout respectively. This is how it would look with a basic logger passed in: >>> logger = logging.getLogger('hostname') >>> conn = remoto.Connection('hostname', logger=logger) >>> run(conn, ['ls', '-a']) 2013-09-07 15:32:06,662 [hostname][DEBUG] . 2013-09-07 15:32:06,662 [hostname][DEBUG] .. 2013-09-07 15:32:06,662 [hostname][DEBUG] .bash_history 2013-09-07 15:32:06,662 [hostname][DEBUG] .bash_logout 2013-09-07 15:32:06,662 [hostname][DEBUG] .bashrc 2013-09-07 15:32:06,662 [hostname][DEBUG] .cache 2013-09-07 15:32:06,664 [hostname][DEBUG] .profile 2013-09-07 15:32:06,664 [hostname][DEBUG] .ssh The run helper will display the stderr and stdout as ERROR and DEBUG respectively. For other types of usage (like checking exit status codes, or raising upon them) remoto does provide them too. Remote Commands process.run Calling remote commands can be done in a few different ways. The most simple one is with process.run: >>> from remoto.process import run >>> from remoto import Connection >>> logger = my_logging_setup('hostname') >>> conn = Connection('hostname') >>> run(conn, ['whoami']) 2013-09-07 15:32:06,664 [hostname][DEBUG] root Note however, that you are not capturing results or information from the remote end. The intention here is only to be able to run a command and log its output. It is a fire and forget call. process.check This callable, allows the caller to deal with the stderr, stdout and exit code. It returns it in a 3 item tuple: >>> from remoto.process import check >>> check(conn, ['ls', '/nonexistent/path']) ([], ['ls: cannot access /nonexistent/path: No such file or directory'], 2) Note that the stdout and stderr items are returned as lists with the \n characters removed. This is useful if you need to process the information back locally, as opposed to just firing and forgetting (while logging, like process.run). Remote Functions To execute remote functions (ideally) you would need to define them in a module and add the following to the end of that module: if __name__ == '__channelexec__': for item in channel: channel.send(eval(item)) If you had a function in a module named foo that looks like this: import os def listdir(path): return os.listdir(path) To be able to execute that listdir function remotely you would need to pass the module to the connection object and then call that function: >>> import foo >>> conn = Connection('hostname') >>> remote_foo = conn.import_module(foo) >>> remote_foo.listdir('.') ['.bash_logout', '.profile', '.veewee_version', '.lesshst', 'python', '.vbox_version', 'ceph', '.cache', '.ssh'] Note that functions to be executed remotely cannot accept objects as arguments, just normal Python data structures, like tuples, lists and dictionaries. Also safe to use are ints and strings. - Author: Alfredo Deza - Keywords: remote,commands,unix,ssh,socket,execute,terminal - License: MIT - Categories - Package Index Owner: alfredodeza - Package Index Maintainer: trhoden - DOAP record: remoto-0.0.16.xml
https://pypi.python.org/pypi/remoto/0.0.16
CC-MAIN-2016-44
refinedweb
627
56.96
C++ <array> - operator< Function The C++ <array> operator< function is used to check whether the first array is less than the second array or not. It returns true if the first array is less than the second array, else returns false. operator< compares elements of arrays sequentially and stops comparison after first mismatch. Syntax template <class T, size_T N> bool operator< (const array<T,N>& lhs, const array<T,N>& rhs); Parameters Return Value Returns true if the contents of lhs are lexicographically less than the contents of rhs, else returns false. Time Complexity Linear i.e, Θ(n). Example: In the example below, the operator< function is used to check whether the first array is less than the second array or not. #include <iostream> #include <array> using namespace std; int main (){ array<int, 3> arr1 {10, 20, 30}; array<int, 3> arr2 {10, 20, 30}; array<int, 3> arr3 {40, 50, 60}; if (arr1 < arr2) cout<<"arr1 is less than arr2.\n"; else cout<<"arr1 is not less than arr2.\n"; if (arr1 < arr3) cout<<"arr1 is less than arr3.\n"; else cout<<"arr1 is not less than arr3.\n"; return 0; } The output of the above code will be: arr1 is not less than arr2. arr1 is less than arr3. ❮ C++ <array> Library
https://www.alphacodingskills.com/cpp/notes/cpp-array-operator-less-than.php
CC-MAIN-2021-43
refinedweb
215
64.51