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 |
|---|---|---|---|---|---|
....
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') xpos = [1,2,3,4,5,6,7,8,9,10] ypos = [2,3,4,5,1,6,2,1,7,2] num_elements = len(xpos) zpos = [0,0,0,0,0,0,0,0,0,0] dx = np.ones(10) dy = np.ones(10) dz = [1,2,3,4,5,6,7,8,9,10] ax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#00ceaa') plt.savefig('test.png')
Asked: 2014-06-21 03:13:52 -0500
Seen: 402 times
Last updated: Jun 21 '14
Error when trying to access MATLAB from Sage
can I create isosurface contours from list data?
Convert a sage.interfaces.matlab.MatlabElement object
Plot Series of 3D Direction Vectors (Not All from Origen)
z-transform and inverse z-transform in SageMath
filling in an area under a function or curve in 3 dimensions
Adding arrows in vector fields
How to install seaborn in sagemath cloud?
plotting a plane section in sage
canvas3d plot does not change. | https://ask.sagemath.org/question/10938/is-there-a-bar3-from-matlab-equivalent-in-sage/?answer=16133 | CC-MAIN-2018-39 | refinedweb | 184 | 68.67 |
Chapter 1. Accessing the Fuse Console
How you access the Fuse Console depends on your Fuse distribution:
- Fuse on OpenShift
Fuse Standalone:
1.1. Accessing the Fuse Console on OpenShift
You can deploy the Fuse Console either from the OpenShift Console or from the command line.
Security and user management for the Fuse Console is handled by OpenShift.
The Fuse Console templates configure end-to-end encryption by default so that your Fuse Console requests are secured end-to-end, from the browser to the in-cluster services.
Role-based access control (for users accessing the Fuse Console after it is deployed) is not yet available for Fuse on OpenShift.
1.1.1. Before you begin (cluster-mode setup)
If you want to deploy the Fuse Console in cluster mode on the OpenShift Container Platform environment, you need the cluster admin role and the cluster mode template. Run the following command:
oc adm policy add-cluster-role-to-user cluster-admin system:serviceaccount:openshift-infra:template-instance-controller
The cluster mode template is only available, by default, on the latest version of the OpenShift Container Platform. It is not provided with the OpenShift Online default catalog.
1.1.2. Deploying the Fuse Console from the OpenShift Console
To deploy the Fuse Console on your OpenShift cluster, follow these steps:
- In the OpenShift console, open an existing project or create a new project.
Add the Fuse Console to your OpenShift project:
Select Add to Project → Browse Catalog.
The Select an item to add to the current project page opens.
In the Search field, type Fuse Console.
The Red Hat Fuse 7.x Console item should appear as the search result.Note
If the Red Hat Fuse Console item does not appear as the search result, or if the item that appears is not the latest version, you can install the Fuse Console templates manually as described in the "Prepare the OpenShift server" section of the Fuse on OpenShift Guide.
Click the Red Hat Fuse Console item.
The Red Hat Fuse Console wizard opens.
Click Next. The Configuration page of the wizard opens.
Optionally, you can change the default values of the configuration parameters.
Click Create.
The Results page of the wizard indicates that the Red Hat Fuse Console has been created.
- Click the Continue to the project overview link to verify that the Fuse Console application is added to the project.
To open the Fuse Console, click the provided URL link and then log in.
An Authorize Access page opens in the browser listing the required permissions.
Click Allow selected permissons.
The Fuse Console opens in the browser and shows the Fuse pods running in the project.
Click Connect for the application that you want to view.
A new browser window opens showing the application in the Fuse Console.
1.1.3. Deploying the Fuse Console from the command line
Table 1.1, “Fuse Console templates” describes the two OpenShift templates that you can use to access the Fuse Console from the command line, depending on the type of Fuse application deployment.
Table 1.1. Fuse Console templates
Optionally, you can view a list of the template parameters by running the following command:
oc process --parameters -f
To deploy the Fuse Console from the command line:
Create a new application based on a Fuse Console template by running one of the following commands (where myproject is the name of your project):
For the Fuse Console cluster template, where
myhostis the hostname to access the Fuse Console:
oc new-app -n myproject -f -p ROUTE_HOSTNAME=myhost
For the Fuse Console namespace template:
oc new-app -n myproject -f
You can omit the route_hostname parameter for the namespace template because OpenShift automatically generates one.
Obtain the status of your deployment by running this command:
oc status
- To access the Fuse Console from a browser, use the provided URL (for example,).
1.2. Accessing the Fuse Console for Spring Boot standalone
To access the Fuse Console for a standalone Fuse Spring Boot distribution:
Add hawtio-springboot to your Fuse application’s
pom.xmlfile dependencies.
<dependency> <groupId>io.hawt</groupId> <artifactId>hawtio-springboot</artifactId> </dependency>
Note that you do not need to specify the version because it is provided by the Maven BOM.
Edit the
src/main/resources/application.propertiesfile:
Set the following properties to false:
endpoints.jolokia.sensitive
endpoints.hawtio.sensitive
hawtio.authenticationEnabled
Set the following properties to true:
endpoints.hawtio.enabled
endpoints.jolokia.enabled
Your application.properties settings should look similar to the following example:
# ports server.port=8080 management.port=10001 # enable management endpoints for healthchecks and hawtio endpoints.enabled = false endpoints.hawtio.enabled = true endpoints.jolokia.enabled = true endpoints.health.enabled = true management.health.defaults.enabled=false camel.health.enabled=false camel.health.indicator.enabled=true endpoints.jolokia.sensitive=false endpoints.hawtio.sensitive=false hawtio.authenticationEnabled=falseNote
By default, authentication for the Fuse Console on Spring Boot is disabled. Optionally, you can enable authentication by writing code specific to your Fuse Console distribution. Here is an example that you can use for guidance:
Run the Fuse application:
mvn spring-boot:run
To determine the port number for the Fuse Console URL, obtain the management.port value by looking at the value set in the
src/main/resources/application.propertiesfile. For example:
management.port = 10001
To open the Fuse Console in a browser, use the following URL syntax where nnnnn is the value of the management.port property:
For example:
1.3. Accessing the Fuse Console for JBoss EAP standalone
Before you can access the Fuse Console for Red Hat JBoss Enterprise Application Platform, you must install Fuse on the JBoss EAP container. For step-by-step instructions, see Installing on JBoss EAP.
To access the Fuse Console for a standalone JBoss EAP distribution:
Start Red Hat Fuse standalone with the following command:
On Linux/Mac OS:
./bin/standalone.sh
On Windows:
./bin/standalone.bat
- In a web browser, enter the URL to connect to the Fuse Console. For example:
- In the login page, enter your user name and password and then click Log In.
By default, the Fuse Console shows the Home page. The left navigation tabs indicate the running plugins.
1.3.1. Resolving delayed Fuse Console loading
If the main Fuse Console page takes a long time to display in the browser, you might need to reduce the number and the size of the log files. You can use the
periodic-size-rotating-file-handler to rotate the file when it reaches a maximum size (rotate-size) and maintains a number of files (max-backup-index). For details on how to use this handler, see the Red Hat JBoss Enterprise Application Platform product documentation.
1.4. Accessing the Fuse Console for Karaf standalone
To access the Fuse Console for Apache Karaf standalone:
- Install Fuse on the Karaf container. For step-by-step instructions, see Installing on Apache Karaf., enter the URL to connect to the Fuse Console. For example:
- In the login page, enter your user name and password and then click Log In.
By default, the Fuse Console shows the Home page. The left navigation tabs indicate the running plugins. | https://access.redhat.com/documentation/en-us/red_hat_fuse/7.2/html/managing_fuse/access-console | CC-MAIN-2020-40 | refinedweb | 1,192 | 55.13 |
Comment on Tutorial - How to use ArrayList in Java By Hong
Comment Added by : Ashok
Comment Added at : 2010-02-28 05:12:31
Comment on Tutorial : How to use ArrayList in Java By Hong
Nice Work... Keep. Each right shift divides number by 2...
View Tutorial By: kunal at 2013-06-18 03:43:54
2. thanks! it helped!
View Tutorial By: shgy at 2015-03-17 07:42:40
3. finally! tnx google for taking me here :) my probl
View Tutorial By: dorinn at 2009-04-02 10:32:40
4. Introduction is very clear I get the answer what I
View Tutorial By: sathya at 2013-02-05 15:57:30
5. Handling several submissions can be a lot simple t
View Tutorial By: Blaze Blankenship at 2012-12-05 13:04:12
6. Why use recursion in Java, even for Strings? The s
View Tutorial By: Kristoffer L at 2012-11-21 01:51:36
7. import java.io.*;
import java.util.Stack;
View Tutorial By: jack&jill at 2011-07-26 06:40:32
8. best site ever.
View Tutorial By: rehan ahmed at 2008-12-10 02:21:32
9. How do i get tht GSM Connection .Can any one give
View Tutorial By: srinivas raju at 2008-08-08 02:50:02
10. nice code.....
View Tutorial By: ♥♠darryl♠♥ at 2009-02-19 06:24:12 | http://java-samples.com/showcomment.php?commentid=34694 | CC-MAIN-2019-04 | refinedweb | 233 | 75.91 |
Back to: LINQ Tutorial For Beginners and Professionals
LINQ Extension Methods in C# with Examples
In this article, I am going to discuss the LINQ Extension Methods in C# with examples. Please read our previous article before proceeding to this article where we discussed the Differences between IEnumerable and IQueryable in C#. At the end of this article, you will understand the following three concepts in C#.
- What are Extension Methods in C#?
- When to use Extension Methods in C#?
- How to implement extension methods in C#?
- Understanding the LINQ Extension Method.
The LINQ’s standard query operators such as select, where, etc. are implemented in Enumerable class. These methods are implemented as extension methods of the type IEnumerable<T> interface. Let us understand this with an example. We have the following code in our Main method.
The above Where() method is not belonging to List<T> class, but still, we are able to call it as it belongs to List<T> class. Why it is possible to call it using List<T> object, let’s find out. If you go to the definition of where method, then you will find the following definition.
As you can see in the signature, the where Where() method is implemented as an extension method on IEnumerable<T> interface and we know List<T> implements IEnumerable<T> interface. This is the reason why we are able to call the Where() method using the List<T> object.
With this keep in mind, let us understand what extension methods are and how they are implemented in C#.
What are Extension Methods?
According to MSDN, Extension methods allow us to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
In simple words, we can say that the Extension methods can be used as an approach of extending the functionality of a class by adding new methods in the future if the source code of the class is not available or if we don’t have any permission in making changes to the class.
The most important point that you need to keep in mind is, extension methods are the special kind of static methods of a static class, but they are going to be called as if they were instance methods on the extended type.
When to use Extension Methods in C#?
You need to use an extension method if any of the following conditions are true:
- You need a method on an existing type and you are not the owner of the source code of that type.
- You need a method on an existing type, you do own the source code of that type but that type is an interface.
- You need a method on an existing type, you do own the source code and that type is not an interface but adding the method creates undesired coupling.
Otherwise, you should go with the normal method of the actual type itself.
How to implement extension methods in C#?
Let us understand this with an example. Our requirement is, we want to add a method in the built-in string class, let’s call this method as GetWordCount() which will count the word present in a string separated by a space.
For example, if the string is “Welcome to Dotnet Tutorials”, then it should return the word count as 4. The most important point is, we need to call this method on the String object as shown below.
int wordCount = sentence.GetWordCount();
Note: We cannot define the GetWordCount() method directly in the string class as we are not the owner of the string class. The string class belongs to System namespace which is own by the .NET framework. So, the alternative solution to achieve this is to write a wrapper class as shown below.
public class ExtensionHelper { public static int GetWordCount(string str) { if (!String.IsNullOrEmpty(str)) return str.Split(' ').Length; return 0; } }
The above ExtensionHelper Wrapper class works fine, but the problem is, here we cannot call the GetWordCount() method using the string object as shown below.
int wordCount = sentence.GetWordCount();
Instead, we need to call the GetWordCount() method as shown below.
int wordCount = ExtensionHelper.GetWordCount(sentence);
How to convert the above GetWordCount() method to an Extension Method of string class?
Now let’s convert the GetWordCount() method to an extension method on the String class. So that we can able to call the GetWordCount() method using the following syntax.
int wordCount = sentence.GetWordCount();
In order to make the above GetWordCount() method as an extension method, we need to make two changes which are as follows.
- First, we need to make the ExtensionHelper class as a static class.
- Second, the type the method extends (i.e. string) should be passed as the first parameter preceding with the “this” keyword to the GetWordCount() method.
With the above two changes in place, now the GetWordCount() method becomes an extension method and hence we can call the GetWordCount() method in the same way as we call an instance method of a class.
The complete code is given below.
using System; namespace LINQDemo { class Program { static void Main(string[] args) { string sentence = "Welcome to Dotnet Tutorials"; int wordCount = sentence.GetWordCount(); Console.WriteLine($"Count : {wordCount}"); Console.ReadKey(); } } public static class ExtensionHelper { public static int GetWordCount(this string str) { if (!String.IsNullOrEmpty(str)) return str.Split(' ').Length; return 0; } } }
Now run the application and you will see the word count as expected in the console window. Here we are still able to call the GetWordCount() extension method using the wrapper class style syntax and also get the output as expected as shown below.
So, the point that I need to keep focus is, behind the scene this is how the extension methods are called internally.
That means, it is also possible to call the LINQ extension methods such as select, where, etc. using the wrapper class style syntax. As all the LINQ extension methods are implemented in the Enumerable class, So, the syntax to call those methods should looks as shown below.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { List<int> intList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; IEnumerable<int> EvenNumbers = Enumerable.Where(intList, n => n % 2 == 0); Console.ReadKey(); } } }
In the next article, I am going to discuss the LINQ Operators in C#. Here, in this article, I try to explain the Linq Extension Methods in C# with Examples. I hope you enjoy this LINQ Extension Methods in C# article. | https://dotnettutorials.net/lesson/linq-extension-methods/ | CC-MAIN-2022-21 | refinedweb | 1,096 | 64.41 |
Each Answer to this Q is separated by one/two green lines.
I want to install OpenCV for python3 in ubuntu 16.04. Fist I tried running
sudo apt-get install python3-opencv which is how I pretty much install all of my python software. This could not find a repository. The install does work however if I do
sudo apt-get install python-opencv this issue with this is that by not adding the three to python it installs for python 2 which I do not use. I would really perfer not to have to build and install from source so is there a way I can get a repository? I also tried installing it with pip3 and it could not find it either.
Well this will be a lengthy answer, so let’s start :
Step 1: Install prerequisites :
Upgrade any pre-installed packages:
$ sudo apt-get update $ sudo apt-get upgrade
Install developer tools used to compile OpenCV 3.0:
$ sudo apt-get install build-essential cmake git pkg-config
Install libraries and packages used to read various image and videos formats from disk:
$ sudo apt-get install libjpeg8-dev libtiff5-dev libpng-dev libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
Install GTK so we can use OpenCV’s GUI features:
$ sudo apt-get install libgtk2.0-dev
Install packages that are used to optimize various functions inside OpenCV, such as matrix operations:
$ sudo apt-get install libatlas-base-dev gfortran
Step 2: Setup Python (Part 1)
Let’s download pip , a Python package manager, installed for Python 3:
$ wget $ sudo python3 get-pip.py
Let’s use our fresh pip3 install to setup virtualenv and virtualenvwrapper :
$ sudo pip3 install virtualenv virtualenvwrapper
Now we can update our ~/.bashrc file (place at the bottom of the file):
# virtualenv and virtualenvwrapper export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh $ source ~/.bashrc $ mkvirtualenv cv
Step 2: Setup Python (Part 2)
we’ll need to install the Python 3.4+ headers and development files:
$ sudo apt-get install python3.4-dev
OpenCV represents images as NumPy arrays, so we need to install NumPy into our cv virtual environment:
$ pip install numpy
Step 3: Build and install OpenCV 3.0 with Python 3.4+ bindings
$ cd ~ $ git clone $ cd opencv $ git checkout 3.0.0 $ cd ~ $ git clone $ cd opencv_contrib $ git checkout 3.0.0
Time to setup the build:
$ cd ~/opencv $ mkdir build $ cd build $ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=ON ..
Let’s start OpenCV compile process :
$ make -j4
Assuming OpenCV 3.0 compiled without error, you can now install it on your system:
$ sudo make install $ sudo ldconfig
Step 4: Sym-link OpenCV 3.0
If you’ve reached this step, OpenCV 3.0 should now be installed in
/usr/local/lib/python3.4/site-packages/.
Here, our OpenCV bindings are stored under the name
cv2.cpython-34m.so
However, in order to use OpenCV 3.0 within our cv virtual environment, we first need to sym-link OpenCV into the site-packages directory of the cv environment, like this: (Be sure to take note of
cv2.cpython-34m.so)
$ cd ~/.virtualenvs/cv/lib/python3.4/site-packages/ $ ln -s /usr/local/lib/python3.4/site-packages/cv2.cpython-34m.so cv2.so
Notice how I am changing the name from cv2.cpython-34m.so to cv2.so — this is so Python can import our OpenCV bindings using the name cv2 .
Step 5: Test out the OpenCV 3.0 and Python 3.4+ install
$ workon cv $ python >>> import cv2 >>> cv2.__version__ '3.0.0'
Hope that helps. Also, credit to Adrian Rosebrock on his post. It worked for me as a charm.
I found this:
OpenCV on wheels
‘Unofficial OpenCV packages for Python.’
Installation was painless for Ubuntu 16.04
pip3 install opencv-python
Check the installation
python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '3.2.0'
Not sure why this wasn’t mentioned. Perhaps it is newly available?
Assuming that you installed Python3.x, I resolved it using the following:
1: Install side packages required for OpenCV with Ubuntu (only validated for: Ubuntu 16.04):
apt-get update apt-get install -y libglib2.0.0 libsm6 apt-get install libxext6 apt-get install -y libxrender-dev
2: Install OpenCV on python3.x:
pip3 install opencv-contrib-python
Using conda inside a python3 environment:
First install conda in a python3 environment and activate it if you haven’t yet:
conda create --name py3k python=3 source activate py3k
Now you can install opencv in the conda environment:
pip install pillow conda install -c menpo opencv3=3.1.0
To import in Python:
import cv2
Ubuntu 18.04 and later
In Ubuntu 18.04 and later Python 3 bindings for the OpenCV (Open Computer Vision) library can be installed from the default Ubuntu repositories with the following command:
sudo apt install python3-opencv
The Open Computer Vision Library is a collection of algorithms and sample code for various computer vision problems. The library is compatible with IPL (Intel’s Image Processing Library) and, if available, can use IPP (Intel’s Integrated Performance Primitives) for better performance.
This is because you have multiple installations of python in your machine.You should make python3 the default, because by default is the python2.7
The popular suggested solution worked miracles for me, where sudo apt install of opencv failed to install properly. Another note on step 4 (which may make life easier for others). It seems simple now but it took me quite a while to troubleshoot (because I am new to this).
Step 4a: Run the following code to find out where the cv2 file is installed. Your filename may also be slightly different. Just because you can’t find it where the OP said it would be, that doesn’t mean the installation did not work.
> $ find /usr/ -iname cv2.* > /usr/lib/python3/dist-packages/cv2.cpython-38-x86_64-linux-gnu.so
Step 4b: SymLink OpenCV 3.0 as above
> $ cd ~/anaconda3/virtualenv/lib/python3.8/site-packages/ > $ ln -s /usr/lib/python3/dist-packages/cv2.cpython-38-x86_64-linux-gnu.so cv2.so
After ubuntu 18.04, use
sudo apt install python3-opencv
Careful, autostart Anaconda enviroment may cover normal apt installation, which took me hours to find. put it down here in case some newbie like me find it not working.
sudo pip3 install opencv-python opencv-contrib-python
| https://techstalking.com/programming/python/ubuntu-how-to-install-opencv-for-python3/ | CC-MAIN-2022-40 | refinedweb | 1,116 | 66.33 |
in reply to
Re: Database normalization the easier way
in thread Database normalization the easier way
My initial idea was to ask for a DBI:: namespace, but yesterday I found out that such namespace is restricted. Then DBIx:: is a good candidate (Or it should be as soon as I get an answer from CPAN. Being in a monastery, I should become used to being patient {grin}).
DBIx::DBSchema was a good hint. I checked it and it seems to provide enough information to replace the direct calls I am using so far.
I would need to rewrite the two subs that are dealing with column information (so many greps and maps wasted!) but this is a good chance to make the module portable across databases.
Thanks.
g | http://www.perlmonks.org/?node_id=132831 | CC-MAIN-2015-48 | refinedweb | 128 | 70.02 |
Untangling a String with a Thread (see what I did there…?) way to manage the messages the Roborio reads from the serial port?
What about an ExecutorService with an ArrayBlockingQueue?
Figured it might be a good opportunity to teach/learn about work queues, threads, etc.
So….
Create an ExecutorService (I’m using a single thread for this example…tune as required)…this is a way for Java to manage the creation of threads:
private ExecutorService executorService = Executors.newFixedThreadPool(1);
And then create a queue to place your String in for processing:
private ArrayBlockingQueue visionReaderQueue= new ArrayBlockingQueue(1000,true);
The (1000,true) constructor means your queue can hold 1,000 messages and your want them to be FIFO (first in, first our…the order is guaranteed)
These two fields would be on your Command. Then create a Runnable class called something like “VisionQueueReader”
import java.util.concurrent.ArrayBlockingQueue;
public class VisionQueueReader implements Runnable {
private ArrayBlockingQueue queue;
public VisionQueueReader(ArrayBlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
String messageFromQueue = queue.take();
//Here is where you do whatever processing on the json you need to…chance are this class might also have a Static reference to the Subsystem waiting for the message
} catch (InterruptedException e) {
break;
//this gets tripped when you shut the ExecutorServiceDown…the loop ends
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}
and finally…in your command that drops the Strings on to the queue, you need to cleanly shut down the Executor service when the system is shutting down
executorService.shutdownNow();
To start the ExecutorService…in either the init or constructor of your command:
executorService.submit(new VisionQueueReader(visionMessageQueue));
so you basically have this ArrayBlockingQueue waiting for strings….when you put a string on, the queue being managed and run by the ExecutorService grabs it and processes it within its run method.
I think this would be a cleaner way to manage that thread resource and guarantee it’ll stick around rather than spend the resources spinning up another…it also guarantees the order in which the messages come off the queue.
Now, this is just another implementation and subject to scrutiny…try it, see if it works. While you do, ask yourself how you might test it vs. your implementation. | https://jamiemcilroy.medium.com/untangling-a-string-with-a-thread-see-what-i-did-there-ee79c5a73afa?responsesOpen=true&source=---------4---------------------------- | CC-MAIN-2021-10 | refinedweb | 374 | 52.09 |
The following useful decorator measures the execution time of a function. It also prints the function's name. However, it would be great if it could also print the class name if the function is a method. What is a concise way to get to the full method name a la
Class.method
import time
def timeit(f):
def timed(*args, **kw):
ts = time.time()
result = f(*args, **kw)
te = time.time()
print('func:%r args:[%r, %r] took: %2.4f sec' % (f.__name__, args, kw, te-ts))
return result
return timed
What about
.__qualname__ ?
In [1]: class MyClass(object): ...: def my_method(self): ...: pass ...: In [2]: MyClass.my_method.__qualname__ Out[2]: 'MyClass.my_method' | https://codedump.io/share/9ZeIg8cVr4tg/1/python-function-decorator-should-print-full-method-name | CC-MAIN-2016-50 | refinedweb | 113 | 80.48 |
If you’re related to web development scene, you’ll most certainly have come across the acronym “MVC” hundreds of time, if not more. MVC is one of the most talked about design patterns in the web programming world today, and rightly so. In this article, we’ll take you through the world of MVC Architecture. We’ll talk about the basics of MVC, its advantages, and finally, a simple code that will help you understand the implementation of MVC in Java in a clearer way.
What exactly is the MVC architecture?
Before we get into the technicalities of it, let’s make some things clear – MVC is NOT a design pattern, it’s a way to structure your applications. In recent years, the web applications are extensively using the MVC architecture, and hence it’s natural to confuse it for a design pattern exclusive for web applications. However, let’s tell you that MVC was first described way back in 1979 – before the WWW era when there was no concept of web applications. The architecture used today for web applications is an adaptation of the original pattern.
In fact, this architecture was initially included in the two major web development frameworks – Struts and Ruby on Rails. These two environments paved the way for a majority of web frameworks that came later – and thus the popularity of this architecture kept rising.
Why Companies are Looking to Hire Full Stack Developers
MVC architectural pattern follows an elementary idea – we must separate the responsibilities in any application on the following basis:
- Model: Handles data and business logic.
- View: Presents the data to the user whenever asked for.
- Controller: Entertains user requests and fetch necessary resources.
Each of the components has a demarcated set of tasks which ensures smooth functioning of the entire application along with complete modularity. Let us have a look at each of these components in further detail.
Controller
The controller is the like the housekeeper of the application – it performs coordination between model and view to entertain a user request. The user requests are received as HTTP get or post request – for example, when the user clicks on any GUI elements to perform any action.
The primary function of a controller is to call and coordinate with the model to fetch any necessary resources required to act. Usually, on receiving a user request, the controller calls the appropriate model for the task at hand.
Model
The model is quite simply the data for our application. The data is “modelled” in a way it’s easy to store, retrieve, and edit. The model is how we apply rules to our data, which eventually represents the concepts our application manages.
For any software application, everything is modelled as data that can be handled easily. What is a user, a book, or a message for an app? Nothing really, only data that must be processed according to specific rules. Like, the date must not be higher than the current date, the email must be in the correct format, the name mustn’t be more than “x” characters long, etc.
Whenever a user makes any request from the controller, it contacts the appropriate model which returns a data representation of whatever the user requested. This model will be the same for a particular work, irrespective of how we wish to display it to the user. That is why we can choose any available view to render the model data.
Additionally, a model also contains the logic to update the relevant controller whenever there is any change in the model’s data.
View
As the name suggests, the view is responsible for rendering the data received from the model. There may be pre-designed templates where you can fit the data, and there may even be several different views per model depending on the requirements.
How to Succeed in Your First Software Development Job
Any web application is structured keeping these three core components in mind. There may be a primary controller that is responsible for receiving all the requests and calling the specific controller for specific actions. Let’s understand the working of a web application under the MVC architecture better using an example.
Let’s See an Example
Let’s take an example of an online stationery shop. The user can view items, buy, add items to cart, add items to current order, or even add/remove items (if he’s the admin).
Now, let’s see what will happen when a user clicks on the title “Pens” to see the list of pens.
Our application will have a particular controller to handle all the queries related to pens. Let’s say it’s called “pens_controller.php”. We’ll also have a model that will store the data regarding the pens we have – let’s call it “pens_model.php”. Finally, we’ll have several views to present the data – a list of pens, a table displaying pens, a page to edit the list, etc.
The following figure shows the complete flow of control right from the moment a user clicks on “pens”, to when the result is rendered in front of him: (2).
Now, the model searches the database for the necessary information (3), applies logics if necessary, and returns the data to the controller(4).
The controller then picks an appropriate view (5) and presents the data (6 and 7). If a request comes from a handheld device, a view suitable for it will be used, or if the user has a particular theme selected, its view will be picked – and so on.
How to Become a Full Stack Developer
The Advantages of the MVC Architecture
A common problem faced by application developers these days is the support for different type of devices. The MVC architecture solves this problem as developers can create different interfaces for different devices, and based on from which device the request is made, the controller will select an appropriate view. The model sends the same data irrespective of the device being used, which ensures a complete consistency across all devices.
The MVC separation beautifully isolates the view from the business logic. It also reduces complexities in designing large application by keeping the code and workflow structured. This makes the overall code much easier to maintain, test, debug, and reuse.
A Simple Implementation of MVC using Java
We will have the following three:
- StudentObject : the model.
- StudentView: view class to print details on the console.
- StudentController: a controller that stores data in studentObject and updates StudentView accordingly
Step 1: Create the Model
public class Student { private String rollNo; private String name; public String getRollNo() { return rollNo; } public void setRollNo(String rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
The code is self-explanatory. It consists of functions to get/set roll number and names of the students. Let’s call it “student.java”.
Step 2: Create the View
public class StudentView { public void printStudentDetails(String studentName, String studentRollNo){ System.out.println("Student: "); System.out.println("Name: " + studentName); System.out.println("Roll No: " + studentRollNo); } }
This is simply to print the values to the console. Let’s call this “studentView.java”.
Step 3: Create the Controller()); } }
Call this “StudentController.java”. A cursory glance will tell you that this controller is just responsible for calling the model to get/set the data, and then updating the view.
Now, let’s have a look at how all of this is tied together.
Step 4: Create the main Java file; } }
This is called “MVCPatternDemo.java”. As you can see, it fetches the student data from the database or a function (in this case we’re using a function to set the values) and pushes it on to the Student model. Then, it initialises the view we had created earlier.
Further, it also initialises our controller and binds it to the model and the view. The updateView() method is a part of the controller which updates the student details on the console.
Step 5: Test the Result
If everything goes right, the result should be:
Student: Name: Robert Roll No: 10 Student: Name: John Roll No: 10
If you get this as the output, congratulations! You’ve successfully implemented the MVC architecture using Java, albeit for a simple application. However simple, this application is enough to demonstrate the powers of the MVC architecture.
15 Must-Know Spring MVC Interview Questions
Wrapping Up…
After so much said and done, it’s hard to emphasise more on the power of the MVC architecture in any web/desktop application these days. It provides an altogether new level of modularity to your code which makes it a lot more readable and maintainable. So, if you want to scale to new heights in your career as an application developer, getting hold of the MVC architecture and its working should be your top priority.
Do drop by a comment and let us know how you like this article!
Latest posts by Arjun Mathur (see all)
- 16 Popular DevOps Use Cases & Real Life Applications [2020] - February 14, 2020
- Solving Real-Time Scenarios With DevOps - February 10, 2020
- 25+Questions For Your Nagios Interview - January 30, 2020 | https://www.upgrad.com/blog/mvc-architecture-in-java/ | CC-MAIN-2020-10 | refinedweb | 1,535 | 52.7 |
Popularity
7.5
Growing
Activity
7.2
Growing
904
20
106
Programming language: Go
License: BSD 3-clause "New" or "Revised" License
Tags: Utility Text Processing
xurls alternatives and similar packages
Based on the "Utility" category.
Alternatively, view xurls alternatives based on common mentions on social networks and blogs.
Koazee6.5 0.0 xurls VS KoazeeA StreamLike, Immutable, Lazy Loading and smart Golang Library to deal with slices.
gotabulate5.8 0.0 xurls VS gotabulateGotabulate - Easily pretty-print your tabular data with Go
radix5.0 0.0 xurls VS radixA fast string sorting algorithm (MSD radix sort)
shell2telegram4.7 3.0 xurls VS shell2telegramTelegram bot constructor from command-line
regroup4.2 0.0 xurls VS regroupMatch regex group into go struct using struct tags and automatic parsing
strutil-go3.9 3.4 xurls VS strutil-goGolang metrics for calculating string similarity and other string utility functions
Goa3.2 0.0 xurls VS GoaThe Go library that will drive you to AOP world!
html2data3.1 4.8 xurls VS html2dataLibrary and cli for extracting data from HTML via CSS selectors
gofuckyourself3.0 1.9 xurls VS gofuckyourselfA sanitization-based swear filter for Go.
parth3.0 0.0 xurls VS parthPath parsing for segment unmarshaling and slicing.
xj2go2.4 2.6 xurls VS xj2goConvert xml and json to go struct
frontmatter2.0 5.3 xurls VS frontmatterGo library for detecting and decoding various content front matter formats
Tagify1.9 6.5 xurls xurls VS kaceCommon case conversions covering common initialisms.
TySug1.3 6.9 xurls VS TySugA project around helping to prevent typing typos. TySug (Typo Suggestions) suggests alternative words with respect to keyboard layouts
parseargs-go1.3 0.0 xurls VS parseargs-goA string argument parser that understands quotes and backslashes
Bookgot1.0 0.0 xurls VS BookgotSimple script for farm free books from PackPub.com
textwrap0.9 0.0 xurls VS textwrapPort of Python's "textwrap" module to Go
godazo0.3 0.0 xurls VS godazoStupid simple slide presenter or static site creator. xurls or a related project?
Popular Comparisons
README
xurls
Extract urls from text using regular expressions. Requires Go 1.16 or later.
import "mvdan.cc/xurls/v2" func main() { rxRelaxed := xurls.Relaxed() rxRelaxed.FindString("Do gophers live in golang.org?") // "golang.org" rxRelaxed.FindString("This string does not have a URL") // "" rxStrict := xurls.Strict() rxStrict.FindAllString("must have scheme: -1) // []string{" rxStrict.FindAllString("no scheme, no match: foo.com", -1) // []string{} }
Since API is centered around regexp.Regexp, many other methods are available, such as finding the byte indexes for all matches.
The regular expressions are compiled when the API is first called. Any subsequent calls will use the same regular expression pointers.
cmd/xurls
To install the tool globally:
go install mvdan.cc/xurls/v2/cmd/[email protected]
$ echo "Do gophers live in | xurls | https://go.libhunt.com/xurls-alternatives | CC-MAIN-2022-21 | refinedweb | 468 | 52.15 |
ScratchExt is set of JavaScript Extensions for Scratch, a programming environment and community for people of all ages. It is a project developed by GrannyCookies, Yoda3D and thistleeverfreen.
This project is currently still in development, so features are still being added, removed, and/or changed. Please keep this in mind while working with ScratchExt. This Instructable will be updated accordingly when significant changes are made.
System Requirements:
- Pretty much any OS: Windows, Mac, or Linux
- Adobe Flash Player
- A JavaScript Enabled browser. I'd recommend Google Chrome, though Firefox or Safari should also work.
The Official website of ScratchExt.
Watch and/or download the code on floobits!
Warnings:
Though JavaScript is relatively safe as it cannot directly access your computer, unapproved external libraries can run scripts that can harm your privacy. We personally strive to safely extend the possibilities of Scratch by closely adhering to the Scratch Terms of Use and Community Guidelines, as well as warning the user before preforming potentially undesired operations. However, other imported Scratch extensions may not necessarily follow these guidelines. As expressed in the GNU General Public License v3, it is the end user who must assume full responsibility for any damages that may arise from the use of our software unless otherwise required by law or agreed upon in writing. Please see the official license for more details.
Step 1: Installing the Installer
Yes, you will need to install something to install something else.
However, this is the one and only complicated step, so don't let that scare you.
- Go to
- Click and drag the link to your bookmarks bar.
- Thats it!
This bookmarklet will run a bit of javascript to install the "– Import –" extension.
However the beauty of this extension is that it will allow you to install other extensions!
Everything else is self updating, so you shouldn't need to do much more once you have the bookmark.
If you use google Chrome, you can also install this Chrome extension
This will directly insert the installer into the Scratch webpages when you use Scratch.
Please note that these changes are not persistent. For each time you view a project that implements ScratchExt, you will need to click the bookmarklet AFTER a project is fully loaded, followed by the green flag. Consider using TamperMonkey or other browser plugin to run scripts automatically.
Step 2: Using the 'Import' Blocks
To run a project that implements ScratchExt, click the bookmark after the project is loaded, then click the green flag again. A prompt should appear to confirm if you want to install additional extensions.
To create a project using ScratchExt, first make sure that your project is shared, otherwise Scratch will not let you share the project once you include new blocks. Then, click the bookmark while you are in the Scratch editor. The new blocks will be added to the "More Blocks" section. Use the "import library" and the "install library" blocks to get even more blocks!
Documentation for these essential blocks is provided below.
Please see the official reference (which is also still a work in progress) for more info.
– Import – (The important blocks):
import library [menu]
Prepares an official extension for installation with the name selected from the menu.
This block will only "mark" a library for installation and will not do anything until an "install libraries" block is used.
import library [string]
–A work in progress–
Prepares an unofficial extension from a link for installation.
This block will only "mark" a library for installation and will not do anything until an "install libraries" block is used.
WARNING: Unofficial extensions can do anything from forced ponification to completely hijacking your web browser. It is not recommended to use this block unless you are fully aware of an extension's capabilities; i.e. you developed an extension for yourself.
install libraries
Installs all libraries specified by previous "import library" blocks. Should be called after all desired libraries are marked for installation.
install all libraries
Installs all official libraries in a single block. Useful to quickly install everything, but will clutter the block selection and/or possibly slow down your project
Step 3: Writing Your Own Extensions
For those who want to take this a step further, you can create your own blocks.
This will require an understanding of JavaScript, as well a a way to publish JS code on the internet, such as a greasyfork. For testing purposes, you may also run your code inside your browser's JavaScript console or create your own bookmarklet.
Please see the official Scratch Extensions Document for more information.
Example Code:
Hello World:
function installHelloWorld() { (function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Installed'}; }; var descriptor = { blocks: [ [' ', 'hello world', 'helloWorld'] ] }; //The Hello world function ext.helloWorld = function(){ alert('Hello World!') }; ScratchExtensions.register('Hello World', descriptor, ext); })({}); }<br>installHelloWorld();
Basic block types:
function installBasicBlocks() { (function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Installed'}; }; var descriptor = { blocks: [ [' ', 'a basic method', 'foo'], ['h', 'a hat block', 'hatMethod'], ['r', 'a reporter', 'reporterMethod'], ['b', 'a boolean reporter', 'bReporterMethod'], ['-'], //Separator [' ', 'string %s number %n color %c', 'bar', 'petrichor', '42', '16775399'] ] }; //Alert method ext.foo = function(){ alert('Foo'); }; //The Hat method (runs code when this returns true) ext.hatMethod = function(){ return true; }; //Reporter ext.reporterMethod = function(){ return 42; }; //Boolean Reporter ext.bReporterMethod = function(){ return true; }; //Method with arguments ext.bar = function(arg1, arg2, arg3){ alert('Received: ' + arg1 + ' ' + arg2 + ' ' + arg3); }; ScratchExtensions.register('Basic Blocks', descriptor, ext); })({}); } installBasicBlocks();
Discussions | https://www.instructables.com/id/How-to-Install-and-Use-ScratchExt-Javascript-Scrat/ | CC-MAIN-2019-30 | refinedweb | 952 | 55.64 |
A Machine for Keeping Secrets?
[I can't begin to describe all the things Vinay Gupta does. Fortunately, he does, at. There his leadership in many involvements are on display, where you can treat yourself to many hours of productive reading, listening and viewing—many involving breeds of Linux. After getting a little hang time with Vinay in London recently, I invited him to treat us to a guest EOF on any topic of his choice. He took the bait, and here it is.—Doc Searls]
The Lesson of Ultra and Mincemeat.
Like any modern zero-day sold on the black market, the Enigma compromise had value only if it remained secret. The stakes were higher, but the basic template of the game—secret compromise, secret exploitation, doom on discovery—continues to be one basic form of the computer security game to this day. The allies went to extraordinary lengths to conceal their compromise of the Enigma, including traps like Operation Mincemeat (planting false papers on a corpse masquerading as a drowned British military officer). The Snowden revelations and other work has revealed the degree to which this game continues, with many millions of taxpayer dollars being spent keeping illicit access to software compromises available to the NSA, GCHQ and all the rest. The first rule is not to reveal success in breaking your enemy's security by careless action; the compromise efforts that Snowden revealed had, after all, been running for many years before the public became aware of them.
Who Does Software Serve?
I would like to posit a fundamental problem in our attitude toward computer security. For a long time we basically have assumed that computers are tools much like any other. Pocket calculators and supercomputer clusters all share the same von Neumann architecture (another artifact of WWII). But the truth is that the computer also has been, from its very first real implementation, a machine for keeping and seeking secrets. This history applies not just to the Enigma machines that the British subverted to help defeat the Nazis, but also to IBM's Hollerith tabulators, used by the Nazis to identify Jews from census databases.
This is why the general utility model of computing we now use is notoriously difficult to secure. At a conceptual level, all programs are assumed to be direct representatives of the user (or superuser). This is fundamentally a mistake, a conceptual error that cannot be repaired by any number of additional layers piled on top of the fundamental error: software serves its authors, not its users. Richard M. Stallman, of course, understands this clearly but focuses mainly on freeing the source code, giving technical users control of their software. But beyond the now-rusty saw of "with enough eyes, all bugs are shallow", the security community as a whole has not gone back to basics and assigned the intentionality of software correctly: to its authors, rather than to its users. Once we admit that software works for those who wrote it, rather than the hapless ones running it, many of the problems of managing computer security get much clearer, if not easier! Furthermore, there is always the gremlin: discordia manifested as bugs. Software behaviors that no human intended are not only common, but ubiquitous. In these cases, software serves neither the user nor the author, but silently adds to the entropy of the universe all by itself.
Imagine if all the people that wrote the software you use every day were made visible. If you run a fully-free computer, right down to the BIOS, you would generally expect to see a group of people who are fully on your side. But then there is the router, and the firmware in your mouse and your telephone's baseband processor, and indeed the epic maze of software that powers the electrical grid to which your devices must connect, and so on. In truth, we do not like or trust many of the people writing the software on which our lives depend in so many ways. The fact that in the 21st century we still download and run programs that have arbitrary access to all of our personal files, data and often deep access to our operating systems is frankly madness. I'm not discussing sandboxing or virtual environments—these may be answers, but let us first clearly state the question: who does this machine serve?
The machine serves the authors of the software, not the person choosing to run it. If you have recently handed over permissions you were not entirely happy with while installing software on an Android phone, you have felt a sense of "No, I do not want you to do that—that's your desire, not mine!" Often we do not entirely trust those authors, their software or the hardware on which it runs. We literally cannot trust our possessions. Nobody wants to carry a snitch in their pocket, and yet we all do.
In an ideal world, all of our systems (and perhaps not only technological ones) would obey the Principle of Least Privilege. Rather than granting large, abstract powers to code (or other systems) and trusting there to be no bugs, we could grant powers in a more narrow way. Consider the all-too-typical "programs can see the entire filesystem" permission we grant to nearly all software dæmons: when something goes wrong, it results in disasters like Squid deleting your root filesystem when restarting. Why does Squid need the power to do that? Why even hold those keys?
So What Happens If We Choose Not to Trust Everybody?
There was a path not taken: capability-based operating systems. Capability-based operating systems really are machines for keeping secrets. They assume that all code is written by people we do not trust, and that the code may contain damaging bugs, if not outright assaults. "All code is untrusted code" creates a completely different role for the operating system in protecting users from the tools they themselves have downloaded. This is a realistic model of what software is like, an explicit model of distrust, unlike the vague trust we feel when installing software many other people are using, thinking "with enough eyes all bugs are shallow, so I'm sure this will be fine." That's not a great model of trust! Capability-based systems assume that all code may be evil, even code the user writes (bugs!), so it is, by default, untrusted in the most profound way.
A bare program can do nothing—no network, no filesystem access, nothing until it is granted permissions, and the operating system provides a smooth interface for an extremely granular approach to granting and managing these permissions. This is not like the Android model, where the application has access to high-level constructs like "your address book"; rather, this extends all the way from that level down to a low-level file-by-file access control model.
In an object capability model, a program cannot open a directory or search for files without a go-ahead from a user, although usually that go-ahead is implicit. For example, passing an open file handle as a command-line argument would grant the relevant program access to that file. A shell could manage those open file handles seamlessly for the user, opening files and passing their handles in a way that is seamless and transparent to the user. Without that permission, all attempts to access a file simply will be met by failure; as far as the software is concerned, that resource simply does not exist.
To get to this security position, one has to be very clear about the politics of software. Why was this code written? Who does it serve? Toward whose advantage does it work? Cui bono? Even if the only illicit advantage is a bug or two serving only the increase of entropy in the universe, we must admit that, when we get right down to it, if you did not write the software yourself, it's pretty much like giving somebody the keys to your house. But, it does not have to be this way.
This line of argument gives me an uneasy feeling every time I write it down
using a modern Linux machine, knowing full well that every single thing I've
used
apt-get install to put on my computer could relaying my key
presses, because once I install it, it acts as if it were me, whether I want that
behavior or not, moment by moment.
The computer is a machine for keeping and seeking secrets.
Is There an Evolutionary Upgrade Path?
I'm not suggesting that we throw out everything that has been done and start again. My suspicion is that to a very substantial degree, with a concerted effort, ideas from the capability-based systems could be comprehensively re-integrated into Linux. Security-Enhanced Linux uses these terms, but without having the full object capability model available. Post-Snowden, now fully aware of how pervasive advanced persistent threat type attacks are on our machines, it seems like it should be possible to start reconsidering what we think we know about software and security for the new operating environment in which we find ourselves. But, can we work out from the long-established SELinux project to those goals?
This is not a straightforward proposition for two reasons: the current limitations of SELinux and the problem of who wrote SELinux.
SELinux currently builds on top of Linux's POSIX capabilities, which are a way of dividing up the power of root into a set of compartments, avoiding the use of setuid. This is important because, in the event of a privilege escalation bug, the illicitly gained privileges aren't the full power of root, but a constrained subset of those powers: notionally, under SELinux, breaking "sudo tail /log/stuff" won't give you access to install new software in the network stack or any other unrelated thing. You might be able to read what you should not, but you can't write to a damn thing. However, the POSIX capability model in SELinux is (confusingly) not the fully blown object capabilities model, because it does not allow for delegation and (as far as I can tell from the docs!) applies only to superuser privileges. It comes from a different theoretical base.
In a full-blown object capability system with delegation, like the research operating systems lineage of GNOSIS, KeyKos (used in production systems), EROS, CapROS and Coyotos, a program (let's say a ported version of GIMP) is run and is blind. It can't see the filesystem, the network stack or anything else; it exists in the void. A user opens a filesystem browser and passes a file to the program, and along for the ride go a necessary set of access keys that are passed invisibly by the operating system. These can be implemented as cryptographic tokens, a little like Kerberos, or as an operating-system-level grant of permissions. Now GIMP can see that file. It can pass the token to the operating system like a filename or handle, which then will open/close the file, and so on. Furthermore, however, when permitted, it can pass that token to another program. Want to run an external filter that only exists as a command-line utility? GIMP can pass that token over to an external utility; the authority to see the file is a transferable asset. And, this model extends across computers. A token for, say, Wi-Fi access can be passed from one machine to another as a delegated authority, and authorities can be chained and combined. Something can act on your behalf (it has the token) without being you as far as the software is concerned.
Say a printer requires network access from one user, and a file to print from another. Normally this is a little tricky. You usually wind up with one user e-mailing the file to another, because the printer expects to work for a single individual: authentication is authorization. In an object capabilities system, the printer (or device, or program) simply assembles capabilities until it has what it needs to do the job. This completely breaks the model in which people are (all too commonly) passing passwords, which have infinite power, to people that they actually want to do one specific job on a remote machine. The granularity of control is so much finer, and delegation fits our real-world security use cases so much better, than the password identity model. You may still use a password to log in, but after that, it's delegated capabilities to manage untrusted software (and untrusted people) all the way down. Doesn't that sound like a better way of doing business in our unsafe times?
Now for the second problem: who wrote SELinux?. It includes a set of sample security policy configuration files designed to meet common, general-purpose security goals.
The NSA team behind SELinux released it under a FOSS license at year end 2000. Now we need to ask ourselves, what is it? We have strong reason to suspect from the Snowden documents that long-term attempts to compromise open and academic security work are part of the NSA's mandate—for example, subverting the National Institute for Standards and Technology cryptography credentialing process by introducing flawed algorithms and getting NIST to sign off on them as credible standards. And, as bitter experience with OpenSSL has shown us (Heartbleed) "with enough eyes, all bugs are shallow" in fact buys us very little security. OpenSSL was extremely under-funded ($2,000 per year!) until the Heartbleed bug brought the world's focus to the plight of OpenSSL's underpaid development team. GPG's development team has been similarly underfunded. This is not working.
So now we have to look at SELinux in much the same light as (sadly) the Tor project—FOSS security tools funded by deeply untrusted sources with a long history of coercive undermining of security, privacy and user control of their own computers. Do we have enough eyes to be able to trust the code under these circumstances? SELinux is one of only four systems that can provide this kind of control under Linux (the others being AppArmor, Smack and Tomoyo) using the same underlying POSIX capabilities. Are eyeballs the right metric? Is that enough eyeballs?
These ongoing questions cut to the heart of our security development processes. I hope in the next few years we find a good way of funding the necessary security work that we, and increasingly the entire world, depend on day-in, day out.
Enter Capsicum. Capsicum is a fairly serious push to integrate deeply a full implementation of capability-based security into FreeBSD. There is an ongoing effort to create Capsicum for Linux, and work is continuing. This seems like a sensible and obvious approach to providing users with an appropriate level of security for the post-Snowden environment we now know we operate in. Because any flawed piece of software assumes full permissions as the user or as the superuser, depending on whether it was a user agent like a browser or a dæmon that got compromised (roughly speaking), we have a challenge. Either perfectly tighten every bolt on an entire starship and miss not a single one, or install bulkheads and partition the space into safe areas, so that, if there is a compromise, it is not systemic.
Bolt-tightening approaches to security are certainly necessary, but I cannot see any way to offer users comprehensive privacy and security on devices that act as secure end points without capability-based operating system concepts coming to Linux in a big way, and right now, that appears to mean Capsicum is the only game in town. This is a matter of some urgency. End-point security weaknesses are really starting to have systemic effects. Let me explain.
I would be much more comfortable if I did not have to trust the thousands of apps on my laptop as much as I do today, and I have very specific reasons for my unease: private key management. Right now I work for Ethereum, a FOSS project producing software to build a global-distributed metacomputer that includes a blockchain database. It's a bit like bitcoin, but it uses the database to store executable software in the form of "contracts" (little scripts you trust to manage your assets).
I think Ethereum is pretty cool. We expect to see an awful lot of very interesting use cases for the platform. Many people may wind up deeply relying on services using that software. For example, comprehensive solutions to the increasing mess that is DNS and issuing SSL certificates could come out of a global-distributed database with scripting: register a domain on the blockchain and self-publish your certificates using the same keys you used to pay for the domain name registration. Simple. Namecoin already has given some sense of what is possible, and I have no doubt there is far more to come..
Huge disruption to everyday life could result from an error like this if blockchain technology winds up being the solution to DNS and SSL namespace issues (a conclusion I consider likely and that I may write up in future for this journal). We could lose basic connectivity to a large part of the Internet in the event that the consensus protocols are attacked by compromised machines. If a zero-day was used to construct malware that abused or just published private keys, that also could have disastrous effects not only for individual users, but also for the decentralized databases as a whole. If blockchains turn out to be vital to the Internet of Things (IBM has an Ethereum-based project, ADEPT, looking at blockchains and the IoT), then even if the blockchain itself and our software are secure, we have hostages to fortune in the form of the PCs being used to manage the keys and the code on which all of this value and utility is stored.
There is an urgent problem that users are starting to store very real value on their machines, not simply in the form of indirect access to value via banking Web sites, but as direct access to their own private keys and a political role in the consensus algorithms on which the entire blockchain is formed. This is all getting a lot more systemic and potentially serious than having somebody read one's e-mail or private journal.
Right now the weakest link in the ongoing adoption of blockchain technology is operating system security. The fear that one will get hacked discourages many users from using software on their own machines to do their computation (to use the Stallman model). Instead, third-party Web sites operating theoretically more secure wallets are common—essentially people are storing their bitcoin and similar "in the cloud" because they do not trust their own PCs enough to store value in a decentralized fashion. This negates many of the decentralization benefits of blockchain-based approaches. This is clearly a massive problem when viewed from Stallman's usual mode of analysis.
Surely at this point in history it's time for us to return computing to its roots. The computer is a machine for keeping my secrets: my banking details, my cryptocurrency holdings, my private keys controlling software acting on my behalf on the blockchain, or in the Internet of things, or in virtual reality, or in any other setting. It's becoming increasingly necessary that users can actually store value on their own machines, and right now, playing whackamole with zero-day exploits is not a good enough security model for this revolution to continue. We have to return to the hard question of how do I stop other people from telling my computer what to do without first asking me?
Encryption without secure endpoints isn't going to help very much, and right now, operating system security is the weakest link. I look forward to your ideas about how we might address these issues in an ongoing fashion—both as a question of awareness raising and funding models, and for the long, hard quest for genuine security for average users. Ordinary people should be able to store value on their home computers without feeling that they have automatically left the front door open with the keys in the lock. How can we provide people with an equivalent level of protection for their bank accounts or their bitcoin holdings? This is the real challenge meeting cryptocurrencies, blockchains and even the Internet of Things. If we cannot trust the users' devices, how can we give them all this access to and power over users' lives?
The revolution is stalling for ordinary users because they cannot trust their operating systems to protect their private keys and thereby their accounts. What now?: | https://www.linuxjournal.com/content/machine-keeping-secrets | CC-MAIN-2019-13 | refinedweb | 3,495 | 57.61 |
I looked and there are offtheshelfe solution, but they are rather expensive and not as fun to build as a RPi setup
So I have the newest RPi and bought the PiCam.
I found this project : and had a go with the code.
Except for a small problem with the Print statement, I got it working.
The RPi setup will be left unattended for 1-2 weeks in a box.
The change I want to make is so it only takes pictures if its within a certain timeframe (to save space on the memory card)
The problem I cant see to figure out how to solve (Im am new at this) is how to set it up so the loop in the code will only run if its between 8:00AM and 4:00PM
This is the code now :
What would you suggest?
Code: Select all
import os import time import RPi.GPIO as GPIO import logging) # Define the location where you wish to save files. Set to HOME as default. # If you run a local web server on Apache you could set this to /var/www/ to make them # accessible via web browser. folderToSave = "/home/timelapse/timelapse_" + str(initYear) + str(initMonth) + str(initDate) + str(initHour) + str(initMins) os.mkdir(folderToSave) # Set up a log file to store activities for any checks. logging.basicConfig(filename=str(folderToSave) + ".log",level=logging.DEBUG) logging.debug(" R A S P I L A P S E C A M -- Started Log for " + str(folderToSave)) logging.debug(" Support at") # Set the initial serial for saved images to 1 fileSerial = 1 # Run a WHILE Loop of infinitely while True: d = datetime.now() if d.hour < 99: # = 800 # Max = 2592 imgHeight = 600 #) + "_" + str(hour) + str(mins) + ".jpg -sh 40 -awb auto -mm average -v") # Write out to log file logging.debug(' Image saved: ' + str(folderToSave) + "/" + str(fileSerialNumber) + "_" + str(hour) + str(mins) + ".jpg") # Increment the fileSerial fileSerial += 1 # Wait 60 seconds (1 minute) before next capture time.sleep(60) else: # Just trapping out the WHILE Statement print " ====================================== Doing nothing at this time" | https://www.raspberrypi.org/forums/viewtopic.php?f=91&t=160412&p=1040356 | CC-MAIN-2020-29 | refinedweb | 347 | 71.75 |
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
Re: [PATCH]Â Fix =thread-created not showing up when detaching
Re: [1/3] [PATCH] value_optimized_out and value_fetch_lazy
Re: [2/3] [PATCH] value_optimized_out and value_fetch_lazy
Re: [3/3] [PATCH] value_optimized_out and value_fetch_lazy
Re: [COMMIT PATCH] Move pagination_enabled declaration to a proper place.
[COMMIT PATCH] Use allocate_optimized_out_value instead of set_value_optimized_out.
[COMMIT PATCH] value_bits_valid: Fix latent bug.
[commit/obv] Remove trailing space in gdb.ada/small_reg_param.exp
[commit/obvious] Fix call to get_raw_print_options on mt-tdep.c (was: Re: [patch] Rename "prettyprint" to "prettyformat")
[commit] [patch] testsuite build regression on CentOS-5 [Re: [PATCH 1/7] test suite update - gdb.base/[ab]]
[commit] change missing DWO complaint to a warning
[commit] delete togglelist
[commit] delete unnecessary init of *list variables
[commit] dwarf2read.c (process_queue): Add type signature to debug output.
[commit] Fix FAIL: gdb.ada/small_reg_param.exp: continue to call_me
Re: [commit] Improved linker-debugger interface
[commit] linux-fork.h: delete detach_fork
[commit] main.c (captured_command_loop): Tweak comment.
[commit] native-stdio-gdbserver.exp: pass "--" to switch
[commit] Re: Runtime regression for gdb.base/reread.exp & co. [Re: [RFA] Remove target_section.bfd]
[commit] symtab.c (iterate_over_some_symtabs): Add comment.
[commit] symtab.c (iterate_over_some_symtabs): Fix indentation.
[commit] target.c (target_async_permitted_1): Fix comment.
[committed] micromips_deal_with_atomic_sequence formatting fix
[PATCH 0/2] Minor dwarf2read cleanups
[PATCH 0/2] New option --skip-unavailable to -stack-list-XXX commands
[PATCH 0/3 V3] Test mingw32 GDB in cygwin
Re: [PATCH 0/3] a few more fixes from the cleanup checker
Re: [PATCH 0/3] add a few new warning options
[PATCH 0/3] Fixes for mingw testing in remote host
Re: [PATCH 0/3] more simple test suite fixes
Re: [PATCH 0/3] Select the current frame in command tdump.
[PATCH 0/3] Test mingw32 GDB in cygwin
[PATCH 0/4] introduce test suite "parallel" mode
[PATCH 0/4] Remove deprecated_throw_reason
[PATCH 0/5] AndesTech nds32 port
[PATCH 0/7] Implement gdbarch_gdb_signal_{to,from}_target
[PATCH 0/8] enable target-async by default
Re: [PATCH 00/09] Import unistd and pathmax gnulib modules.
Re: [PATCH 00/16] clean up remote.c state
[PATCH 00/17] Implement gdbarch_gdb_signal_to_target
[PATCH 01/17] Implement the gdbarch.{sh,c,h} bits.
[PATCH 02/17] Linux kernel generic support
Re: [PATCH 03/16] Add new_remote_state
[PATCH 03/17] Alpha support
[PATCH 04/17] x86_64 support
[PATCH 05/17] ARM support
[PATCH 06/17] AVR support
[PATCH 07/17] Cris support
[PATCH 08/17] h8300 support
[PATCH 09/17] i386 support
[PATCH 1/2] cleanup: rename is_ref_attr to attr_form_is_ref
Re: [patch 1/2] Code cleanup: remote.c *->{async,sync}*
[PATCH 1/2] Use mi_getopt in mi_cmd_stack_list_locals and mi_cmd_stack_list_variables
[PATCH 1/3] Copy set_unbuffered_mode_saved.o on remote host
[PATCH 1/3] Detect GDB is in cygwin
[PATCH 1/3] Fix ppc64 single step over atomic sequence testcase
[PATCH 1/3] New option --cygwin-tty.
Re: [PATCH 1/3] New test case for PR12929.
Re: [PATCH 1/3] Tweak gdb.trace/backtrace.exp
[PATCH 1/4] more uses of standard_output_file
[PATCH 1/4] Remove deprecated_throw_reason from internal_verror.
[PATCH 1/5] Code for nds32 target
[PATCH 1/5] config support for powerpc64-aix
Re: [PATCH 1/5] powerpc64-aix- Processing XLC generated line tables
Re: [PATCH 1/5] powerpc64-aix- Processing XLC generated line tables + CHANGELOG
Re: [PATCH 1/5] Share 'enum target_hw_bp_type' in GDB and GDBserver.
Re: [PATCH 1/7] gdbserver, common: conditionally include the unistd.h
[PATCH 1/7] Implement the gdbarch.{sh,c,h} bits.
[PATCH 1/8] fix latent bugs in ui-out.c
[PATCH 10/17] IA-64 support
Re: [PATCH 11/16] move some statics from remote_read_qxfer into struct remote_state
[PATCH 11/17] m32r support
[PATCH 12/17] m68klinux support
[PATCH 13/17] mn10300 support
Re: [PATCH 14/16] move async_client_callback and async_client_context into remote_state
[PATCH 14/17] s390 support
[PATCH 15/17] SPARC support
[PATCH 16/17] Xtensa support
[PATCH 17/17] MIPS support
[PATCH 18/18] AArch64 support
[PATCH 2/2] Add options to skip unavailable locals
[PATCH 2/2] cleanup: constify argument passed to dwarf form predicates
Re: [PATCH 2/3] add -Wold-style-declaration
Re: [PATCH 2/3] Don't force interpreter sync mode in execute_gdb_command.
Re: [PATCH 2/3] Make test result of gdb.trace/backtrace.exp unique
[PATCH 2/3] Remove the directory of DEST in proc gdb_compile_shlib
[PATCH 2/3] Support up to 3 conditional branches in an atomic sequence
[PATCH 2/3] Unbuffer stdout and stderr in cygwin
[PATCH 2/3] Unbuffer stdout and stderr on windows
[PATCH 2/4] introduce parallel mode
[PATCH 2/4] Remove deprecated_throw_reason from mips_error.
[PATCH 2/5] gdbserver for nds32
Re: [PATCH 2/5] Include asm/ptrace.h in mips-linux-nat.c
[PATCH 2/5] powerpc64-aix processing xlC generated line table
[PATCH 2/5] powerpc64-aix- xcoffread patch
[PATCH 2/7] Linux kernel generic support
[PATCH 2/8] add target method delegation
[PATCH 3/3] Add multiple branches to single step through atomic sequence testcase
Re: [PATCH 3/3] Match output in async mode.
[PATCH 3/3] native mingw32 gdb, eol format
Re: [PATCH 3/3] Select the current frame in command tdump.
[PATCH 3/3] Set stdin/stdout/stderr to binary mode in cygwin.
[PATCH 3/3] Use the tail name as the output name of compile.
[PATCH 3/4] add standard_temp_file
[PATCH 3/4] Remove remaining uses of deprecated_throw_reason.
[PATCH 3/5] powerpc64-aix config patch
[PATCH 3/5] powerpc64-aix inf-ptrace patch
Re: [PATCH 3/5] Refactor in mips-linux-nat.c
[PATCH 3/5] testsuite for nds32
[PATCH 3/7] Alpha support
[PATCH 3/8] PR gdb/13860: make -interpreter-exec console "list" behave more like "list".
[PATCH 4/4] add caching procs to test suite
[PATCH 4/4] Remove deprecated_throw_reason.
Re: [PATCH 4/5] CHANGELOG
Re: [PATCH 4/5] Move mips hardware watchpoint stuff to common/
[PATCH 4/5] powerpc64-aix inf-ptrace patch [wrongly sent as PATCH 3/5 earlier]
[PATCH 4/5] powerpc64-aix ptrace64 when defined.
[PATCH 4/5] Simulator for nds32
[PATCH 4/7] AVR support
Re: [PATCH 4/7] gdbserver: conditionally include sys/param.h and sys/time.h
[PATCH 4/8] PR gdb/13860: make "-exec-foo"'s MI output equal to "foo"'s MI output.
[PATCH 5/5] make calls to ptrace64 in aix-thread.c when defined
Re: [PATCH 5/5] MIPS GDBserver watchpoint
[PATCH 5/5] powerpc64-aix aix-thread patch
[PATCH 5/5] testsuite for nds32 simulator
[PATCH 5/7] SPARC support
[PATCH 5/8] PR gdb/13860: don't lose '-interpreter-exec console EXECUTION_COMMAND''s output in async mode.
Re: [PATCH 6/7] common: add an alternative implementation for xstrvprintf
[PATCH 6/7] Xtensa support
[PATCH 6/8] make dprintf.exp pass in always-async mode
[PATCH 7/7] MIPS support
[PATCH 7/8] fix py-finish-breakpoint.exp with always-async
[PATCH 8/8] enable target-async
[PATCH OB] Remove obsolete comments in board files.
[PATCH OB] Remove unused parameter in i386_linux_core_read_xcr0 and i386_in_stack_tramp_p
[PATCH PR gdb/15715] 'set history filename' to by immediately converted to absolute path.
FW: [PATCH v11 0/5] remove-symbol-file & add-symbol-file
Re: [PATCH v11 2/5] Test adding and removing a symbol file at runtime.
[PATCH v12 0/5] remove-symbol-file & add-symbol-file
[PATCH v12 1/5] New remove-symbol-file command.
[PATCH v12 2/5] Documentation for the remove-symbol-file command.
[PATCH v12 3/5] 'add-symbol-file' should update the current target sections.
[PATCH v12 4/5] Function is_elf_target.
[PATCH v12 5/5] Test adding and removing a symbol file at runtime.
[PATCH v14 0/5] remove-symbol-file & add-symbol-file
[PATCH v14 1/5] New remove-symbol-file command.
[PATCH v14 2/5] Documentation for the remove-symbol-file command.
[PATCH v14 3/5] 'add-symbol-file' should update the current target sections.
[PATCH v14 4/5] Function is_known_elf_target.
[PATCH v14 5/5] Test adding and removing a symbol file at runtime.
[PATCH v2 0/4] increase the portability of the gdbserver code
Re: [PATCH v2 0/5] mips hardware watchpoint support in gdbserver
[PATCH v2 0/9] enable target-async by default
Re: [PATCH v2 00/16]
[PATCH v2 1/4] gdbserver, common: convert some variadic macros to C99
[PATCH v2 1/9] fix latent bugs in ui-out.c
[PATCH v2 2/4] gdbserver: avoid empty structs
[PATCH v2 2/9] add "this" pointers to more target APIs
[PATCH v2 3/4] gdbserver, win32: fix some function typedefs
[PATCH v2 3/9] add target method delegation
[PATCH v2 4/9] PR gdb/13860: make -interpreter-exec console "list" behave more like "list".
[PATCH v2 5/9] PR gdb/13860: make "-exec-foo"'s MI output equal to "foo"'s MI output.
[PATCH v2 6/9] PR gdb/13860: don't lose '-interpreter-exec console EXECUTION_COMMAND''s output in async mode.
[PATCH v2 7/9] make dprintf.exp pass in always-async mode
[PATCH v2 8/9] fix py-finish-breakpoint.exp with always-async
[PATCH v2 9/9] enable target-async
Re: [PATCH v2] Add convenience variable $_exitsignal
Re: [PATCH v3] gdbserver: fix the standalone build
[patch v4 00/24] record-btrace: reverse
[patch v4 01/24] gdbarch: add instruction predicate methods
[patch v4 02/24] record: upcase record_print_flag enumeration constants
[patch v4 03/24] btrace: change branch trace data structure
[patch v4 04/24] record-btrace: fix insn range in function call history
[patch v4 05/24] record-btrace: start counting at one
[patch v4 06/24] btrace: increase buffer size
[patch v4 07/24] record-btrace: optionally indent function call history
[patch v4 08/24] record-btrace: make ranges include begin and end
[patch v4 09/24] btrace: add replay position to btrace thread info
[patch v4 10/24] target: add ops parameter to to_prepare_to_store method
[patch v4 11/24] record-btrace: supply register target methods
[patch v4 12/24] frame, backtrace: allow targets to supply a frame unwinder
[patch v4 13/24] record-btrace, frame: supply target-specific unwinder
[patch v4 14/24] record-btrace: provide xfer_partial target method
[patch v4 15/24] record-btrace: add to_wait and to_resume target methods.
[patch v4 16/24] record-btrace: provide target_find_new_threads method
[patch v4 17/24] record-btrace: add record goto target methods
[patch v4 18/24] record-btrace: extend unwinder
[patch v4 19/24] btrace, linux: fix memory leak when reading branch trace
[patch v4 20/24] btrace, gdbserver: read branch trace incrementally
[patch v4 21/24] record-btrace: show trace from enable location
[patch v4 22/24] infrun: reverse stepping from unknown functions
[patch v4 23/24] record-btrace: add (reverse-)stepping support
[patch v4 24/24] record-btrace: skip tail calls in back trace
[PATCH with testcase] Bug 11568 - delete thread-specific breakpoint on the thread exit
Re: [PATCH, e500] Fix store.exp failures
[patch, sim, mips] Implement unlink, lseek, and stat for MIPS
[PATCH, testsuite] Don't run SREC, IHEX and TEKHEX tests for MIPS N64.
Re: [PATCH, testsuite] Fix failures in gdb.mi/gdb2549.exp when register 0 doesn't have a name
[PATCH/AARCH64] Fix hardware break points
Re: [PATCH/v2] fix Bug 15180 Agent style dprintf does not respect conditions
[PATCH3/5] 64 bit support in xcoffread + reading auxillary entries correctly
[PATCH] [1/2] Add new 'z' format for print command
[PATCH] [1/2] value_fetch_lazy - ensure parent is not lazy before accessing.
[PATCH] [2/2] Don't raise an error for optimized out sub-fields.
[PATCH] [2/2] Resue 'z' formatter from mi register display code
[PATCH] [OBV] Look for gdb_prompt in py-explore.exp
[patch] [python] Add two different initialization checks for frame filters
[PATCH] ada-lang.c:coerce_unspec_val_to_type: Preserve laziness.
[PATCH] Catch up with OpenBSD/hppa ptrace(2) changes
Re: [PATCH] change gdb to use BFD's "dwz" functions
[PATCH] cleanup: constify "struct attribute" function parameter
[PATCH] Copy file to host if it is remote
[PATCH] Don't call strchr with the NULL character.
[PATCH] Enable hw watchpoint with longer ranges using DAWR on Power
[PATCH] fix Bug 11568 - delete thread-specific breakpoint on the thread exit
Re: [PATCH] Fix bug 15433 - GDB crashes when using agent dprintf, %s format, and an in-line string
RE: [patch] Fix cleanup in finish_command
[PATCH] Fix for PR15117
[PATCH] Fix PR 12702 - gdb can hang waiting for thread group leader (gdbserver)
Re: [PATCH] fix PR 15180 "May only run agent-printf on the target"
[PATCH] Fix PR 15692 -dprintf-insert does not accept double quotes
[PATCH] Fix PR 15693 - Extra *running event when call-style dprintf hits
[PATCH] fix PR symtab/15719
Re: [PATCH] fix remote host test failures in testsuite
[patch] Fix SIGTERM signal safety (PR gdb/15358)
Re: [PATCH] Fix up msymbol type of dll trampoline to mst_solib_trampoline
Re: [PATCH] gdb/testsuite/gdb.base/gnu-ifunc-lib.c: Use %function syntax.
Re: [PATCH] gdb/testsuite/gdb.dwarf2: Replaces @ with % sign to allow tests stay compatible with both arm and x86 assembly
[PATCH] gdb/testsuite/gdb.threads: Ensure TLS tests link against pthreads.
Re: [PATCH] gdb/testsuite/gdb.threads: Make sure TLS tests link against pthreads.
[PATCH] Implement way of checking if probe interface can evaluate arguments
[PATCH] Improve performance of large restore commands
Re: [PATCH] Link GDBserver with -lmcheck on mainline/development too.
[PATCH] make default_print_one_register_info print_hex_chars
Re: [PATCH] Make file transfer commands work with all (native) targets.
[PATCH] MIPS: Define descriptive names for GNU attribute values
[PATCH] native mingw32 gdb, eol format
Re: [PATCH] NULL dwarf2_per_objfile in dwarf2_per_objfile_free
[PATCH] optimized out registers in mi
[PATCH] Pass address around within ada-valprint.c
[patch] PR 15695, add missing check_typedef's
Re: [PATCH] print '--with{,out}-babeltrace' in 'gdb --configuration'
Re: [PATCH] Rely on beneath to do partial xfer from tfile target
[PATCH] Remove error_pre_print and quit_pre_print
[PATCH] remove msymbol_objfile
[PATCH] Remove parameter lsal from 'create_breakpoints_sal' in 'struct breakpoint_ops'
[patch] Rename "prettyprint" to "prettyformat"
Re: [PATCH] Rename 'booke' ptrace interface in ppc-linux-nat.c
Re: [PATCH] Revised display-linkage-name
[PATCH] Share gdbservre setting for board files native-*gdbserver.exp
[PATCH] Share more common target structures between gdb and gdbserver
[PATCH] Share ptrace options discovery/linux native code between GDB and gdbserver
[patch] testsuite build regression on CentOS-5 [Re: [PATCH 1/7] test suite update - gdb.base/[ab]]
[PATCH] testsuite/gdb.base: Enable disp-step-syscall.exp tests for arm targets
[PATCH] testsuite/gdb.dwarf2: Enable dw2-error.exp tests for arm targets
[PATCH] testsuite/gdb.dwarf2: Fix for dw2-dos-drive failure on ARM
[PATCH] testsuite/gdb.dwarf2: Fix for dw2-ifort-parameter failure on ARM
[PATCH] Unbuffer stdout and stderr on windows
[PATCH] Update pattern to match when value is missing
[PATCH] Use DWARF2 CFI unwinder on OpenBSD/hppa
[PATCH] wp-replication: Fix test case loop
Re: [patch][python] 0 of 5 - Frame filters and Wrappers
RE: [patchv2 1/11] Remove xfullpath (use gdb_realpath instead)
Re: [patchv2 2/2] Fix CTRL-C for remote.c (PR remote/15297)
[PING (docs)] Re: [PATCH] [1/2] Add new 'z' format for print command
[ping 2] [RFA][PATCH v4 0/5] Add TDB regset support
[ping 2]: [PATCH 0/3] Select the current frame in command tdump.
[ping] [RFA][PATCH v4 0/5] Add TDB regset support
[PING] Re: [PATCH] [1/2] value_fetch_lazy - ensure parent is not lazy before accessing.
[ping]: [PATCH 0/2] New option --skip-unavailable to -stack-list-XXX commands
Re: [ping][PATCH 00/17] Implement gdbarch_gdb_signal_to_target
[RFA 0/14] Remove quadratic behaviour from probes linker interface
[RFA 1/14] Changes to solib.c
[RFA 10/14] Changes to solib-som.c
[RFA 11/14] Changes to solib-spu.c
[RFA 12/14] Changes to solib-sunos.c
[RFA 13/14] Changes to solib-target.c
[RFA 14/14] Changes to solib-svr4.c
[RFA 2/14] Changes to solib-aix.c
[RFA 3/14] Changes to solib-darwin.c
[RFA 4/14] Changes to solib-dsbt.c
[RFA 5/14] Changes to solib-frv.c
[RFA 6/14] Changes to solib-ia64-hpux.c
[RFA 7/14] Changes to solib-irix.c
[RFA 8/14] Changes to solib-osf.c
[RFA 9/14] Changes to solib-pa64.c
Re: [RFA, doc RFA] set print frame-arguments-raw on|off
Re: [RFA, doc RFA] work around gold/15646
[RFA] bad VER in src-release causes snapshot failure
Re: [RFA] buildsym.c cleanup
Re: [RFA] dwarf2read.c: fix computing list of included symtabs
[RFA] Fix mi-var-child-f.exp failures
[RFA] Fix namespace aliases (c++/7539, c++/10541)
[RFA] Fix varobj/15166
[RFA] nto_find_and_open_solib: Fix setting temp_pathname on failure.
Re: [RFA] remove duplicates in search_symbols
[RFA] Remove target_section.bfd
[RFA] Windows x64 SEH unwinder (v2)
[RFA][PATCH v4 0/5] Add TDB regset support
[RFA][PATCH v4 1/5] S/390 regmap rework
[RFA][PATCH v4 2/5] S/390: Add TDB regset
[RFA][PATCH v4 3/5] Dynamic core regset sections support
[RFA][PATCH v4 4/5] S/390: Exploit dynamic core regset sections
[RFA][PATCH v4 5/5] PowerPC: Exploit dynamic core regset sections
Re: [RFC/PATCH] Add new internal variable $_signo
Re: [RFC/PATCH] New convenience variable $_exitsignal
Re: [rfc] Add help text to start-up text
Re: [RFC] Catch exception after stepped over watchpoint.
Re: [RFC] Debug Methods in GDB Python
[RFC] Support for dynamic core file register notes
Re: [RFC][PATCH] GDB kills itself instead of interrupting inferior
[RFC][PATCH] Preliminary `catch syscall' support for ARM Linux.
[v13 0/5] remove-symbol-file & add-symbol-file
[v13 1/5] New remove-symbol-file command.
[v13 2/5] Documentation for the remove-symbol-file command.
[v13 3/5] 'add-symbol-file' should update the current target sections.
[v13 4/5] Function is_known_elf_target.
[v13 5/5] Test adding and removing a symbol file at runtime.
Build regression on CentOS-5 [Re: [PATCH 3/3] add -Wold-style-definition]
Build regression with --enable-targets=all [Re: [RFA] Remove target_section.bfd]
Re: Events when inferior is modified
RE: fix ARI for version.in change
FYI: [testsuite/Ada] Add testing of access to packed arrays.
FYI: GDB nightly snapshots still down
FYI: minor comment fixes in ptid.h
Fw: gdb-7.6 patches for powerpc64-aix
gdb-patches Library cleaner Book sterilizer for soleagent each countries
Patch contribution
Regression for fission-reread.exp and pr13961.exp [Re: [PATCH 2/3] fix init_cutu_and_read_dies]
Regression for implptr.exp and pieces.exp [Re: [COMMIT PATCH] value_bits_valid: Fix latent bug.]
Re: Regression for implptr.exp and pieces.exp [Re: [COMMIT PATCH] value_bits_valid: Fix latent bug.]
Re: regroup --help text in --help)
Relocation test fix for target=i686-mingw32 and host=i686-pc-linux
RFA: remove mention of "target nrom"
RFC: don't call add_target for thread_db_ops
RFC: fix ARI for version.in change
Re: RFC: fix src-release for version.in move
Re: RFC: introduce common.m4
Re: RFC: introduce scoped cleanups
RFC: remove pop_target
Runtime regression for gdb.base/reread.exp & co. [Re: [RFA] Remove target_section.bfd]
Re: Runtime regression for gdb.base/reread.exp & co. [Re: [RFA] Remove target_section.bfd]
Setting parity for remote serial
Re: Updated patch for Bug 13217 - thread apply all detach throws a SEGFAULT | https://sourceware.org/ml/gdb-patches/2013-07/subjects.html | CC-MAIN-2017-04 | refinedweb | 3,193 | 54.12 |
The program is pretty much done. It's a program to split an input such as 20110102 into 01/02/2011. I already have the loop in place, but for some reason when I output the program it gives me huge numbers. Please tell me what's wrong in my void function. Thank you.
Code:#include <iostream> #include <iomanip> using namespace std; void date (int fulldate, int month, int day, int year) { year = (fulldate/100/100); month = (fulldate0); day = ((fulldate/100)0); } int main() { rerun: int fulldate, month, day, year; char a; cout << "Enter a long integer of the form yyymmdd: "<< endl; cin >> fulldate; cout << "The date is " << month << "/" << day << "/" << year <<endl; cout << "Would you like to try again? [y/n]" << endl; cin >> a; if (a == 'y' || a == 'Y') goto rerun; else return 0; } | http://cboard.cprogramming.com/cplusplus-programming/142105-need-little-bit-help.html | CC-MAIN-2014-15 | refinedweb | 134 | 84.3 |
I'm trying to write a method to generate Pascal's triangles as a 2D array. For example:
pascal(3) # => [[1],[1,1],[1,2,1]]
def pascal n
pascal = []
row = [1]
(1...n).each do |i|
#first iteration set pascal equal to [[1]] and row to [1,1]
if i.zero?
pascal << row
#sets new value for row for next iteration
row = [1,1]
else
#row generator sets new value for row
row = ([0] + row).zip(row + [0]).collect { |a, b| a + b }
#push row's new value into pascal array
pascal << row
end
end
end
1...5
Return value of ruby method is the last thing evaluated. In your case, it's
each.
each returns a thing it iterated (the range). You should explicitly return
pascal array from your method as this seems to be the result you need. Add this line to the end of your method.
pascal << row end # end if end # end each pascal # < this line end # end method
This will make
pascal the last thing evaluated and, therefore, return value of the method.
JFYI, it seems that your code has broken logic. If we do the abovementioned correction, we get this (which does not match your expectation).
pascal(3) # => [[1, 1], [1, 2, 1]]
I leave it up to you to debug this. :) | https://codedump.io/share/wwhdtHFkZ0pj/1/pascal-triangle-in-ruby | CC-MAIN-2018-09 | refinedweb | 219 | 82.44 |
Obtaining a RealNumber in Python
I have a python module imported by a SageMath notbook and in this module, I import and use Sage functionality via
from sage.all import *.
Most functions work fine, however when I try to obtain a
RealNumber such as in the following code:
from sage.rings.real_mpfr import RealNumber # ... test = RealNumber(1.2)
I get this error:
TypeError: Cannot convert float to sage.rings.real_mpfr.RealField_class
I've tried using strings as well and that didn't work either.
Note that to use <- This was an incorrect assumption on my part. After @slelievre's answer, I looked if
RealNumber I need to import it explicitly (it's not included in
sage.all).
create_RealNumber was imported by
sage.all and it indeed is. Ultimately, to get
RealNumber to work, only the
sage.all import is needed.
Question:
How can I use
RealNumber in my Python module? | https://ask.sagemath.org/question/56426/obtaining-a-realnumber-in-python/?sort=votes | CC-MAIN-2021-49 | refinedweb | 150 | 60.01 |
rcsfile - format of RCS file
An RCS file's contents are described by the grammar below.
The text is free format: space, backspace, tab, newline,
vertical tab, form feed, and carriage return (collec-
tively, white space) have no significance except in
strings. However, white space cannot appear within an id,
num, or sym, and an RCS file must end with a newline.
Strings are enclosed by @. If a string contains a @, it
must be doubled; otherwise, strings can contain arbitrary
binary data.
The meta syntax uses the following conventions: `|' (bar)
separates alternatives; `{' and `}' enclose optional
phrases; `{' and `}*' enclose phrases that can be repeated
zero or more times; `{' and '}+' enclose phrases that must
appear at least once and can be repeated; Terminal symbols
are in boldface; nonterminal symbols are in italics.
rcstext ::= admin {delta}* desc {deltatext}*
admin ::= head {num};
{ branch {num}; }
access {id}*;
symbols {sym : num}*;
locks {id : num}*; {strict ;}
{ over-
lap. In most environments RCS uses the ISO 8859/1 encod-
ing:-
phrase will begin with any keyword already in use.
The delta nodes form a tree. All nodes whose numbers con-
sist of a single indi-
cates the default branch (or revision) for most RCS opera-
tions. If empty, the default branch is the highest branch
on the trunk.
All delta nodes whose numbers consist of 2n fields (n>=2)
(e.g., 3.1.1.1, 2.1.2.2, etc.) are linked as follows.
All nodes whose first 2n-1 number fields are identical are
linked through the next field in order of increasing num-
bers.-
point. This list is ordered in increasing numbers. /
\ /
\ /
\ /
Author: Walter F. Tichy, Purdue University, West
Lafayette, IN, 47907.
Manual Page Revision: 5.6; Release Date: 1995/06/05.
Eggert.
rcsintro(1), ci(1), co(1), ident(1), rcs(1), rcsclean(1),
rcsdiff(1), rcsmerge(1), rlog(1)
Walter F. Tichy, RCS--A System for Version Control,
Software--Practice & Experience 15, 7 (July 1985),
637-654. | http://www.linuxonlinehelp.com/man/rcsfile.html | crawl-001 | refinedweb | 323 | 65.62 |
Objects
Introduction
Chuck implements an object system that borrows from both C++ and Java conventions. In our case this means:
- You can define custom classes as new types and instantiate objects
- ChucK supports polymorphic inheritance (this is the same model used in Java, and also known as virtual inheritance in C++)
- All object variables are references (like Java), but instantiation resembles C++. We will discuss this in detail below.
- There is a default class library.
- All objects inherit from the Object class (as in Java)
For the sake of clarity we will define these terms:
- A class is an abstraction of data (members) and behavior (methods)
- A class is a type.
- An object is an instantiation of that class
- A reference variable refers indirectly to an object - it is not the object itself. All ChucK object variables are reference variables (like in Java).
- Similarly, reference assignment duplicates a reference to an object and assigns the reference to a reference variable. The object itself is not duplicated. All ChucK object assignments are reference assignments.
Built-in Classes
ChucK has a number of classes defined within the language.
- Object : base class to all ChucK objects.
- Event : ChucK’s basic synchronization mechanism; may be extended to create custom Event functionality (discussed here).
- Shred : basic abstraction for a non-premptive ChucK process.
- UGen : base unit generator class (discussed here).
These are some of the more commonly used classes in ChucK.
Working With Objects
Let’s begin with some examples. For these examples, let’s assume Foo is a defined class.
// create a Foo object; stored in reference variable bar Foo bar;
The above code does two things:
- A reference variable bar is declared; its type is Foo
- A new instance of Foo is created, and its reference is assigned to bar
Note that in contrast to Java, this statement both declares a reference variable and instantiates a instance of that class and assigns the reference to the variable. Also note that in contrast to C++, bar is a reference, and does not represent the object itself.
To declare a reference variable that refers to nothing (also called a null reference):
// create a null reference to a Foo object Foo @ bar;
The above code only declare a reference and initializes it to null. (random note: the above statement may be read as ”Foo at bar”).
We can assign a new instance to the reference variable:
// assign new instance of Foo to bar new Foo @=> Foo @ bar; // (this statement is equivalent to ’Foo bar’, above)
The code above is exactly equivalent to Foo bar; as shown above. The new operator creates an instance of a class, in this case Foo. The @=> operator performs the reference assignment. (see Operators chapter for more information on @=>)
It is possible to make many references to same object:
// make a Foo Foo bar; // reference assign to duh bar @=> Foo @ duh; // (now both bar and duh points to the same object)
ChucK objects are reference counted and garbage collection takes place automatically. (note: this is still being implemented!)
As stated above, a classes may contain data and behavior, in the form of member variables and mem- ber functions, respectively. Members are accessed by using ’dot notation’ - reference.memberdata and reference.memberfunc(). To invoke a member function of an object (assuming class Foo has a member function called compute that takes two integers and returns an integer):
// make a Foo Foo bar; // call compute(), store result in boo bar.compute( 1, 2 ) => int boo;
Writing a Class
If a class has already been defined in the ChucK virtual machine (either in the same file or as a public class in a different file) then it can be instantiated similar to primitive types.
Unless declared public, class definitions are scoped to the shred and will not conflict with identically named classes in other running shreds.
Classes encapsulate a set of behaviors and data. To define a new object type, the keyword class is used followed by the name of that class.
// define class X class X { // insert code here }
If a class is defined as public, it is integrated into the central namespace (instead of the local one), and can be instantiated from other programs that are subsequently compiled. There can be at most one public class per file.
// define public class MissPopular public class MissPopular { // ... } // define non-public class Flarg class Flarg { // ... } // both MissPopular and Flarg can be used in this file // only MissPopular can be used from another file
We define member data and methods to specify the data types and functionality required of the class. Members, or instance data and instance functions are associated with individual instances of a class, whereas static data and functions are only associated with the class (and shared by the instances).
Members (Instance Data + Functions)
Instance data and methods are associated with an object.
// define class X class X { // declare instance variable ’m_foo’ int m_foo; // another instance variable ’m_bar’ float m_bar; // yet another, this time an object Event m_event; // function that returns value of m_foo fun int getFoo() { return m_foo; } // function to set the value of m_foo fun void setFoo( int value ) { value => m_foo; } // calculate something fun float calculate( float x, float y ) { // insert code } // print some stuff fun void print() { <<< m_foo, m_bar, m_event >>>; } } // instantiate an X X x; // set the Foo x.setFoo( 5 ); // print the Foo <<< x.getFoo() >>>; // call print x.print();
Class Constructors
In the initial release, we do not support constructors yet. However, we have a single pre-constructor. The code immediately inside a class definiton (and not inside any functions) is run every time an instance of that class is created.
// define class X class X { // we can put any ChucK statements here as pre-constructor // initialize an instance data 109 => int m_foo; // loop over stuff for( 0 => int i; i < 5; i++ ) { // print out message how silly <<< "part of class pre-constructor...", this, i >>>; } // function fun void doit() { // ... } } // when we instantiate X, the pre-constructor is run X x; // print out m_foo <<< x.m_foo >>>;
Static (Data + Functions)
Static data and functions are associated with a class, and are shared by all instances of that class – in fact, static elements can be accessed without an instance, by using the name of the class: Classname.element.
// define class X class X { // static data static int our_data; // static function fun static int doThatThing() { // return the data return our_data; } } // do not need an instance to access our_data 2 => X.our_data; // print out <<< X.our_data >>>; // print <<< X.doThatThing() >>>; // create instances of X X x1; X x2; // print out their static data - should be same <<< x1.our_data, x2.our_data >>>; // change use one 5 => x1.our_data; // the other should be changed as well <<< x1.our_data, x2.our_data >>>;
Inheritance
Inheritance in ob ject-oriented code allows the programmer to take an existing class and extend or alter its functionality. In doing so we can create a taxonomy of classes that all share a specific set of behaviors, while implementing those behaviors in different, yet well-defined, ways. We indicate that a new class inherits from another class using the extends keyword. The class from which we inherit is referred to as the parent class, and the inheriting class is the child class. The Child class receives all of the member data and functions from the parent class, although functions from the parent class may be overridden ( below ). Because the children contain the functionality of the parent class, references to instances of a child class may be assigned to a parent class reference type.
For now, access modifiers (public, protected, private) are included but not fully implemented. Everything is public by default.
// define class X class X { // define member function fun void doThatThing() { <<<"Hallo">>>; } // define another fun void hey() { <<<"Hey!!!">>>; } // data int the_data; } // define child class Y class Y extends X { // override doThatThing() fun void doThatThing() { <<<"No! Get away from me!">>>; } } // instantiate a Y Y y; // call doThatThing y.doThatThing(); // call hey() - should use X’s hey(), since we didn’t override y.hey(); // data is also inherited from X <<< y.the_data >>>;
Inheritance provides us a way of efficiently sharing code between classes which perform similar roles. We can define a particular complex pattern of behavior, while changing the way that certain aspects of the behavior operate.
// parent class defines some basic data and methods class Xfunc { int x; fun int doSomething( int a, int b ) { return 0; } } // child class // which overrides the doSomething function with an addition operation class Xadds extends Xfunc { fun int doSomething ( int a, int b ) { return a + b ; } } // child class, which overrides the doSomething function with a multiply operation class Xmuls extends Xfunc { fun int doSomething ( int a, int b ) { return a * b; } } // array of references to Xfunc Xfunc @ operators[2]; // instantiate two children and assign reference to the array new Xadds @=> operators[0]; new Xmuls @=> operators[1]; // loop over the Xfunc for( 0 => int i; i < operators.cap(); i++ ) { // doSomething, potentially different for each Xfunc <<< operators[i].doSomething( 4, 5 ) >>>; }
Because Xmuls and Xadds each redefine doSomething( int a, int b ) with their own code, we say that they have overridden the behavior of the parent class. They observe the same interface, but have potentially different implementation. This is known as polymorphism.
Overloading
Function overloading in classes is similar to that of regular functions. see functions. | http://archive.flossmanuals.net/chuck/ch026_objects.html | CC-MAIN-2020-40 | refinedweb | 1,553 | 52.29 |
These docs are in progress!
Themes are handled through contexts in the latest Reapp UI. While it's a small change in code to support, it's a huge enhancement in flexibility.
A theme consists of constants, styles and animations. It looks like this:
let theme = { constants: { borderWidth: 1 }, styles: { List: { self: { background: '#eee' }, } }, animations: { fadeToLeft({ index, step }) { return { translate: { x: index - step }, opacity: index - step } } } }
If you're using reapp-kit, loading a custom theme that extends the iOS one is as easy as:
import ../{ theme } from .css'reapp-kit'; import iOS from 'reapp-kit/themes/ios'; theme({ constants: [ iOS.constants.base, iOS.constants.components, require('./constants/components') ], styles: [ iOS.styles, require('./styles') ], animations: [ iOS.animations ] });
When you import reapp-ui, you are given a helper that lets you construct these objects more easily.
Here's an example of manually loading the iOS theme with reapp-ui:
import UI from 'reapp-ui'; import iOS from 'reapp-ui/themes/ios'; // import base css styles import '../reapp-ui/themes/ios/stylesheets.css'; UI.addConstants( iOS.constants.base, iOS.constants.components ); UI.addStyles( iOS.styles ); UI.addAnimations( iOS.animations ); export default UI.makeTheme();
One thing to note is that when using the reapp-ui helpers, your styles will have access to constants if you export a function for each one. So you can use them like so:
UI.addConstants({ baseColor: '#fff' }); UI.addStyles({ List: constants => ({ self: { border: `1px solid ${constants.baseColor}` } }) });
In general:
A final note: notice the
UI.makeTheme(). This exports a plain JS object like the one we started
out with. Since themes use context, let's learn how to load them into our app.
With reapp-kit, you already have your theme loaded. When you build your top-level component, you just need to wrap it like so:
import { React, Reapp } from 'reapp-kit' class MyComponent extends React.Component { render() { // your stuff } } export default Reapp(MyComponent);
Reapp-kit will take care of loading the theme into context.
Without the kit, you can load a theme using our
Theme helper. After you've made your theme
using
UI.makeTheme from above, you could load it like so:
import theme from './mytheme'; import Theme from 'reapp-ui/helpers/Theme'; import ../Button from .css'reapp-ui/components/Button'; export default React.createClass({ render() { return ( <Theme {...theme}> <Button>Hello world!</Button> </Theme> ) } })
The
Theme helper is a simple component that sets the
this.context.theme variable
to be the theme object you created.
We'll be expanding documentation on this as we go, but in the future the power of the
themes in contexts will be that you can swap them out. That very same Button could
change the
theme variable to be an Android theme, and your entire app would change
on the fly! | http://www.reapp.io/docs-themes/ | CC-MAIN-2018-39 | refinedweb | 462 | 67.45 |
The QCommServiceManager class provides a method to discover the active communications services and interfaces. More...
#include <QCommServiceManager>
Inherits QAbstractIpcInterfaceGroupManager.
The QCommServiceManager class provides a method to discover the active communications services and interfaces.
Each service has a unique name, such as GSM, VoIP, etc. Within each service is a list of interfaces for functionality areas, which have names such as QNetworkRegistration, QSMSSender, etc.
Interface names correspond to class names elsewhere in the Qtopia Communications and Telephony API's. To use an interface, the caller creates an instance of the corresponding class. The caller can specify an explicit service name, if more than one service implements the same interface, or leave the service name empty to use the default service for that interface.
See the documentation for QAbstractIpcInterface for more information on writing and using interface classes.
See also QCommInterface.
Construct a new communications service manager and attach it to parent.
Destroy this communications service manager.
Signal that is emitted when service is added. A service is considered to have been added when its first interface is constructed.
See also services().
Signal that is emitted when service is removed. A service is considered to have been removed when its last interface is deleted.
See also services().
Get the list of all services that are currently active within the system.
See also servicesChanged(), serviceAdded(), and serviceRemoved().
Signal that is emitted when the list of services changes, if the interfaces on a service has changed, or if the priority assignments have changed.
See also services(). | https://doc.qt.io/archives/qtopia4.3/qcommservicemanager.html | CC-MAIN-2021-25 | refinedweb | 252 | 51.44 |
.\" REF 1" .TH PERLREF 1 "2004-11-05" "perl v5.8.6" "Perl Programmers Reference Guide" .SH "NAME" perlref \- Perl references and nested data structures .SH "NOTE" .IX Header "NOTE" This is complete documentation about all aspects of references. For a shorter, tutorial introduction to just the essential features, see perlreftut. .SH "DESCRIPTION" .IX Header variables, but also lets you have \*(L"hard\*(R" references to any piece of data or code. Any scalar may hold a hard reference. Because arrays and hashes contain scalars, you can now easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on. .PP Hard references are smart\*(--they keep track of reference counts for you, automatically freeing the thing referred to when its reference count goes to zero. (Reference counts for values in self-referential or cyclic data structures may not go to zero without a little help; see \&\*(L"Two\-Phased Garbage Collection\*(R" \*(L"blessed\*(R" into a class package.) .PP Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The \f(CW*glob\fR notation is something of a symbolic reference. (Symbolic references are sometimes called \*(L"soft references\*(R", but please don't call them that; references are confusing enough without useless synonyms.) .PP In contrast, hard references are more like hard links in a Unix file system: They are used to access an underlying object without concern for what its (other) name is. When the word \*(L"reference\*(R" is used without an adjective, as in the following paragraph, it is usually talking about a hard reference. .PP. .Sh "Making References" .IX Subsection "Making References" References can be created in several ways. .IP "1." 4 By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address\-of) operator in C.) This typically creates \fIanother\fR reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples: .Sp .Vb 5 \& $scalarref = \e$foo; \& $arrayref = \e@ARGV; \& $hashref = \e%ENV; \& $coderef = \e&handler; \& $globref = \e*foo; .Ve .Sp It isn't possible to create a true reference to an \s-1IO\s0 handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the \f(CW*foo{THING}\fR syntax below. However, you can still use type globs and globrefs as though they were \s-1IO\s0 handles. .IP "2." 4 A reference to an anonymous array can be created using square brackets: .Sp .Vb 1 \& $arrayref = [1, 2, ['a', 'b', 'c']]; .Ve .Sp Here we've created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, \f(CW\*(C`$arrayref\->[2][1]\*(C'\fR would have the value \*(L"b\*(R".) .Sp Taking a reference to an enumerated list is not the same as using square brackets\*(--instead it's the same as creating a list of references! .Sp .Vb 2 \& @list = (\e$a, \e@b, \e%c); \& @list = \e($a, @b, %c); # same thing! .Ve .Sp As a special case, \f(CW\*(C`\e(@foo)\*(C'\fR returns a list of references to the contents of \f(CW@foo\fR, not a reference to \f(CW@foo\fR itself. Likewise for \f(CW%foo\fR, except that the key references are to copies (since the keys are just strings rather than full-fledged scalars). .IP "3." 4 A reference to an anonymous hash can be created using curly brackets: .Sp .Vb 4 \& $hashref = { \& 'Adam' => 'Eve', \& 'Clyde' => 'Bonnie', \& }; .Ve .Sp \fIlocal()\fR or \fImy()\fR) are executable statements, not compile-time declarations. .Sp Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a \f(CW\*(C`+\*(C'\fR or a \f(CW\*(C`return\*(C'\fR in front so that Perl realizes the opening brace isn't starting a \s-1BLOCK\s0. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle. .Sp For example, if you wanted a function to make a new hash and return a reference to it, you have these options: .Sp .Vb 3 \& sub hashem { { @_ } } # silently wrong \& sub hashem { +{ @_ } } # ok \& sub hashem { return { @_ } } # ok .Ve .Sp On the other hand, if you want the other meaning, you can do this: .Sp .Vb 3 \& sub showem { { @_ } } # ambiguous (currently ok, but may change) \& sub showem { {; @_ } } # ok \& sub showem { { return @_ } } # ok .Ve .Sp The leading \f(CW\*(C`+{\*(C'\fR and \f(CW\*(C`{;\*(C'\fR always serve to disambiguate the expression to mean either the \s-1HASH\s0 reference, or the \s-1BLOCK\s0. .IP "4." 4 A reference to an anonymous subroutine can be created by using \&\f(CW\*(C`sub\*(C'\fR without a subname: .Sp .Vb 1 \& $coderef = sub { print "Boink!\en" }; .Ve .Sp Note the semicolon. Except for the code inside not being immediately executed, a \f(CW\*(C`sub {}\*(C'\fR is not so much a declaration as it is an operator, like \f(CW\*(C`do{}\*(C'\fR or \f(CW\*(C`eval{}\*(C'\fR. (However, no matter how many times you execute that particular line (unless you're in an \&\f(CW\*(C`eval("...")\*(C'\fR), \f(CW$coderef\fR will still have a reference to the \fIsame\fR anonymous subroutine.) .Sp Anonymous subroutines act as closures with respect to \fImy()\fR. .Sp. .Sp You might also think of closure as a way to write a subroutine template without using \fIeval()\fR. Here's a small example of how closures work: .Sp .Vb 6 \& sub newprint { \& my $x = shift; \& return sub { my $y = shift; print "$x, $y!\en"; }; \& } \& $h = newprint("Howdy"); \& $g = newprint("Greetings"); .Ve .Sp .Vb 1 \& # Time passes... .Ve .Sp .Vb 2 \& &$h("world"); \& &$g("earthlings"); .Ve .Sp This prints .Sp .Vb 2 \& Howdy, world! \& Greetings, earthlings! .Ve .Sp Note particularly that \f(CW$x\fR continues to refer to the value passed into \fInewprint()\fR \fIdespite\fR \*(L"my \f(CW$x\fR\*(R" having gone out of scope by the time the anonymous subroutine runs. That's what a closure is all about. .Sp This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with. .IP "5." 4 References are often returned by special subroutines called constructors. Perl objects are just references to a special type often named \fInew()\fR and called indirectly: .Sp .Vb 1 \& $objref = new Doggie (Tail => 'short', Ears => 'long'); .Ve .Sp But don't have to be: .Sp .Vb 1 \& $objref = Doggie->new(Tail => 'short', Ears => 'long'); .Ve .Sp .Vb 2 \& use Term::Cap; \& $terminal = Term::Cap->Tgetent( { OSPEED => 9600 }); .Ve .Sp .Vb 4 \& use Tk; \& $main = MainWindow->new(); \& $menubar = $main->Frame(-relief => "raised", \& -borderwidth => 2) .Ve .IP "6." 4 References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven't talked about dereferencing yet, we can't show you any examples yet. .IP "7." 4 A reference can be created by using a special syntax, lovingly known as the *foo{\s-1THING\s0} syntax. *foo{\s-1THING\s0} returns a reference to the \s-1THING\s0 slot in *foo (which is the symbol table entry which holds everything known as foo). .Sp .Vb 6 \& $scalarref = *foo{SCALAR}; \& $arrayref = *ARGV{ARRAY}; \& $hashref = *ENV{HASH}; \& $coderef = *handler{CODE}; \& $ioref = *STDIN{IO}; \& $globref = *foo{GLOB}; .Ve .Sp All of these are self-explanatory except for \f(CW*foo{IO}\fR. It returns the \s-1IO\s0 handle, used for file handles (\*(L"open\*(R" in perlfunc), sockets (\*(L"socket\*(R" in perlfunc and \*(L"socketpair\*(R" in perlfunc), and directory handles (\*(L"opendir\*(R" in perlfunc). For compatibility with previous versions of Perl, \f(CW*foo{FILEHANDLE}\fR is a synonym for \f(CW*foo{IO}\fR, though it is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn of its use. .Sp \&\f(CW*foo{THING}\fR returns undef if that particular \s-1THING\s0 hasn't been used yet, except in the case of scalars. \f(CW*foo{SCALAR}\fR returns a reference to an anonymous scalar if \f(CW$foo\fR hasn't been used yet. This might change in a future release. .Sp \&\f(CW*foo{IO}\fR is an alternative to the \f(CW*HANDLE\fR mechanism given in \&\*(L"Typeglobs and Filehandles\*(R" in perldata for passing filehandles into or out of subroutines, or storing. .Sp .Vb 2 \& splutter(*STDOUT); # pass the whole glob \& splutter(*STDOUT{IO}); # pass both file and dir handles .Ve .Sp .Vb 4 \& sub splutter { \& my $fh = shift; \& print $fh "her um well a hmmm\en"; \& } .Ve .Sp .Vb 2 \& $rec = get_rec(*STDIN); # pass the whole glob \& $rec = get_rec(*STDIN{IO}); # pass both file and dir handles .Ve .Sp .Vb 4 \& sub get_rec { \& my $fh = shift; \& return scalar <$fh>; \& } .Ve .Sh "Using References" .IX Subsection "Using References" That's it for creating references. By now you're probably dying to know how to use references to get back to your long-lost data. There are several basic methods. .IP "1." 4 Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type: .Sp .Vb 6 \& $bar = $$scalarref; \& push(@$arrayref, $filename); \& $$arrayref[0] = "January"; \& $$hashref{"KEY"} = "VALUE"; \& &$coderef(1,2,3); \& print $globref "output\en"; .Ve .Sp It's important to understand that we are specifically \fInot\fR dereferencing \&\f(CW$arrayref[0]\fR or \f(CW$hashref{"KEY"}\fR there. The dereference of the scalar variable happens \fIbefore\fR it does any key lookups. Anything more complicated than a simple scalar variable must use methods 2 or 3 below. However, a \*(L"simple scalar\*(R" includes an identifier that itself uses method 1 recursively. Therefore, the following prints \*(L"howdy\*(R". .Sp .Vb 2 \& $refrefref = \e\e\e"howdy"; \& print $$$$refrefref; .Ve .IP "2." 4 Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a \&\s-1BLOCK\s0 returning a reference of the correct type. In other words, the previous examples could be written like this: .Sp .Vb 6 \& $bar = ${$scalarref}; \& push(@{$arrayref}, $filename); \& ${$arrayref}[0] = "January"; \& ${$hashref}{"KEY"} = "VALUE"; \& &{$coderef}(1,2,3); \& $globref->print("output\en"); # iff IO::Handle is loaded .Ve .Sp Admittedly, it's a little silly to use the curlies in this case, but the \s-1BLOCK\s0 can contain any arbitrary expression, in particular, subscripted expressions: .Sp .Vb 1 \& &{ $dispatch{$index} }(1,2,3); # call correct routine .Ve .Sp Because of being able to omit the curlies for the simple case of \f(CW$$x\fR,, \&\fInot\fR case 2: .Sp .Vb 4 \& $$hashref{"KEY"} = "VALUE"; # CASE 0 \& ${$hashref}{"KEY"} = "VALUE"; # CASE 1 \& ${$hashref{"KEY"}} = "VALUE"; # CASE 2 \& ${$hashref->{"KEY"}} = "VALUE"; # CASE 3 .Ve .Sp Case 2 is also deceptive in that you're accessing a variable called \f(CW%hashref\fR, not dereferencing through \f(CW$hashref\fR to the hash it's presumably referencing. That would be case 3. .IP "3." 4 Subroutine calls and lookups of individual array elements arise often enough that it gets cumbersome to use method 2. As a form of syntactic sugar, the examples for method 2 may be written: .Sp .Vb 3 \& $arrayref->[0] = "January"; # Array element \& $hashref->{"KEY"} = "VALUE"; # Hash element \& $coderef->(1,2,3); # Subroutine call .Ve .Sp The left side of the arrow can be any expression returning a reference, including a previous dereference. Note that \f(CW$array[$x]\fR is \fInot\fR the same thing as \f(CW\*(C`$array\->[$x]\*(C'\fR here: .Sp .Vb 1 \& $array[$x]->{"foo"}->[0] = "January"; .Ve .Sp This is one of the cases we mentioned earlier in which references could spring into existence when in an lvalue context. Before this statement, \f(CW$array[$x]\fR may have been undefined. If so, it's automatically defined with a hash reference so that we can look up \&\f(CW\*(C`{"foo"}\*(C'\fR in it. Likewise \f(CW\*(C`$array[$x]\->{"foo"}\*(C'\fR will automatically get defined with an array reference so that we can look up \f(CW\*(C`[0]\*(C'\fR in it. This process is called \fIautovivification\fR. .Sp One more thing here. The arrow is optional \fIbetween\fR brackets subscripts, so you can shrink the above down to .Sp .Vb 1 \& $array[$x]{"foo"}[0] = "January"; .Ve .Sp Which, in the degenerate case of using only ordinary arrays, gives you multidimensional arrays just like C's: .Sp .Vb 1 \& $score[$x][$y][$z] += 42; .Ve .Sp Well, okay, not entirely like C's arrays, actually. C doesn't know how to grow its arrays on demand. Perl does. .IP "4.". .PP. .PP .Vb 3 \& if ($ref1 == $ref2) { # cheap numeric compare of references \& print "refs 1 and 2 refer to the same thing\en"; \& } .Ve .PP Using a reference as a string produces both its referent's type, including any package blessing as described in perlobj, as well as the numeric address expressed in hex. The \fIref()\fR operator returns just the type of thing the reference is pointing to, without the address. See \*(L"ref\*(R" in perlfunc for details and examples of its use. .PP The \fIbless()\fR operator may be used to associate the object a reference points to with a package functioning as an object class. See perlobj. .PP A typeglob may be dereferenced the same way a reference can, because the dereference syntax always indicates the type of reference desired. So \f(CW\*(C`${*foo}\*(C'\fR and \f(CW\*(C`${\e$foo}\*(C'\fR both indicate the same scalar variable. .PP Here's a trick for interpolating a subroutine call into a string: .PP .Vb 1 \& print "My sub returned @{[mysub(1,2,3)]} that time.\en"; .Ve .PP The way it works is that when the \f(CW\*(C`@{...}\*(C'\fR is seen in the double-quoted string, it's evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to \f(CW\*(C`mysub(1,2,3)\*(C'\fR. So the whole block returns a reference to an array, which is then dereferenced by \f(CW\*(C`@{...}\*(C'\fR and stuck into the double-quoted string. This chicanery is also useful for arbitrary expressions: .PP .Vb 1 \& print "That yields @{[$n + 5]} widgets\en"; .Ve .Sh "Symbolic references" .IX Subsection "Symbolic references" We said that references spring into existence as necessary if they are undefined, but we didn't say what happens if a value used as a reference is already defined, but \fIisn't\fR a hard reference. If you use it as a reference, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the \fIname\fR of a variable, rather than a direct link to a (possibly) anonymous value. .PP People frequently expect it to work like this. So it does. .PP .Vb 9 \& $name = "foo"; \& $$name = 1; # Sets $foo \& ${$name} = 2; # Sets $foo \& ${$name x 2} = 3; # Sets $foofoo \& $name->[0] = 4; # Sets $foo[0] \& @$name = (); # Clears @foo \& &$name(); # Calls &foo() (as in Perl 4) \& $pack = "THAT"; \& ${"${pack}::$name"} = 5; # Sets $THAT::foo without eval .Ve .PP This is powerful, and slightly dangerous, in that it's possible to intend (with the utmost sincerity) to use a hard reference, and accidentally use a symbolic reference instead. To protect against that, you can say .PP .Vb 1 \& use strict 'refs'; .Ve .PP and then only hard references will be allowed for the rest of the enclosing block. An inner block may countermand that with .PP .Vb 1 \& no strict 'refs'; .Ve .PP Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with \fImy()\fR) aren't in a symbol table, and thus are invisible to this mechanism. For example: .PP .Vb 6 \& local $value = 10; \& $ref = "value"; \& { \& my $value = 20; \& print $$ref; \& } .Ve .PP This will still print 10, not 20. Remember that \fIlocal()\fR affects package variables, which are all \*(L"global\*(R" to the package. .Sh "Not-so-symbolic references" .IX Subsection "Not-so-symbolic references" A new feature contributing to readability in perl version 5.001 is that the brackets around a symbolic reference behave more like quotes, just as they always have within a string. That is, .PP .Vb 2 \& $push = "pop on "; \& print "${push}over"; .Ve .PP has always meant to print \*(L"pop on over\*(R", even though push is a reserved word. This has been generalized to work the same outside of quotes, so that .PP .Vb 1 \& print ${push} . "over"; .Ve .PP and even .PP .Vb 1 \& print ${ push } . "over"; .Ve .PP will have the same effect. (This would have been a syntax error in Perl 5.000, though Perl 4 allowed it in the spaceless form.) This construct is \fInot\fR considered to be a symbolic reference when you're using strict refs: .PP .Vb 3 \& use strict 'refs'; \& ${ bareword }; # Okay, means $bareword. \& ${ "bareword" }; # Error, symbolic reference. .Ve .PP Similarly, because of all the subscripting that is done using single words, we've applied the same rule to any bareword that is used for subscripting a hash. So now, instead of writing .PP .Vb 1 \& $array{ "aaa" }{ "bbb" }{ "ccc" } .Ve .PP you can write just .PP .Vb 1 \& $array{ aaa }{ bbb }{ ccc } .Ve .PP and not worry about whether the subscripts are reserved words. In the rare event that you do wish to do something like .PP .Vb 1 \& $array{ shift } .Ve .PP you can force interpretation as a reserved word by adding anything that makes it more than a bareword: .PP .Vb 3 \& $array{ shift() } \& $array{ +shift } \& $array{ shift @_ } .Ve .PP The \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR switch will warn you if it interprets a reserved word as a string. But it will no longer warn you about using lowercase words, because the string is effectively quoted. .Sh "Pseudo\-hashes: Using an array as a hash" .IX Subsection "Pseudo-hashes: Using an array as a hash" \&\fB\s-1WARNING\s0\fR: This section describes an experimental feature. Details may change without notice in future versions. .PP \&\fB\s-1NOTE\s0. .PP Beginning with release 5.005 of Perl, you may use an array reference in some contexts that would normally require a hash reference. This allows you to access array elements using symbolic names, as if they were fields in a structure. .PP For this to work, the array must contain extra information. The first element of the array has to be a hash reference that maps field names to array indices. Here is an example: .PP .Vb 1 \& $struct = [{foo => 1, bar => 2}, "FOO", "BAR"]; .Ve .PP .Vb 2 \& $struct->{foo}; # same as $struct->[1], i.e. "FOO" \& $struct->{bar}; # same as $struct->[2], i.e. "BAR" .Ve .PP .Vb 2 \& keys %$struct; # will return ("foo", "bar") in some order \& values %$struct; # will return ("FOO", "BAR") in same some order .Ve .PP .Vb 3 \& while (my($k,$v) = each %$struct) { \& print "$k => $v\en"; \& } .Ve .PP Perl will raise an exception if you try to access nonexistent fields. To avoid inconsistencies, always use the \fIfields::phash()\fR function provided by the \f(CW\*(C`fields\*(C'\fR pragma. .PP .Vb 2 \& use fields; \& $pseudohash = fields::phash(foo => "FOO", bar => "BAR"); .Ve .PP For better performance, Perl can also do the translation from field names to array indices at compile time for typed object references. See fields. .PP There are two ways to check for the existence of a key in a pseudo\-hash. The first is to use \fIexists()\fR. This checks to see if the given field has ever been set. It acts this way to match the behavior of a regular hash. For instance: .PP .Vb 3 \& use fields; \& $phash = fields::phash([qw(foo bar pants)], ['FOO']); \& $phash->{pants} = undef; .Ve .PP .Vb 3 \& print exists $phash->{foo}; # true, 'foo' was set in the declaration \& print exists $phash->{bar}; # false, 'bar' has not been used. \& print exists $phash->{pants}; # true, your 'pants' have been touched .Ve .PP The second is to use \fIexists()\fR on the hash reference sitting in the first array element. This checks to see if the given key is a valid field in the pseudo\-hash. .PP .Vb 2 \& print exists $phash->[0]{bar}; # true, 'bar' is a valid field \& print exists $phash->[0]{shoes};# false, 'shoes' can't be used .Ve .PP \&\fIdelete()\fR on a pseudo-hash element only deletes the value corresponding to the key, not the key itself. To delete the key, you'll have to explicitly delete it from the first hash element. .PP .Vb 5 \& print delete $phash->{foo}; # prints $phash->[1], "FOO" \& print exists $phash->{foo}; # false \& print exists $phash->[0]{foo}; # true, key still exists \& print delete $phash->[0]{foo}; # now key is gone \& print $phash->{foo}; # runtime exception .Ve .Sh "Function Templates" .IX Subsection "Function Templates" As explained above, a closure is an anonymous function with access to the lexical variables visible when that function was compiled. It retains access to those variables even though it doesn't get run until later, such as in a signal handler or a Tk callback. .PP Using a closure as a function template allows us to generate many functions that act similarly. Suppose you wanted functions named after the colors that generated \s-1HTML\s0 font changes for the various colors: .PP .Vb 1 \& print "Be ", red("careful"), "with that ", green("light"); .Ve .PP The \fIred()\fR and \fIgreen()\fR functions would be similar. To create these, we'll assign a closure to a typeglob of the name of the function we're trying to build. .PP .Vb 5 \& @colors = qw(red blue green yellow orange purple violet); \& for my $name (@colors) { \& no strict 'refs'; # allow symbol table manipulation \& *$name = *{uc $name} = sub { "@_" }; \& } .Ve .PP Now all those different functions appear to exist independently. You can call \fIred()\fR, \s-1\fIRED\s0()\fR, \fIblue()\fR, \s-1\fIBLUE\s0()\fR, \fIgreen()\fR, \f(CW\*(C`my\*(C'\fR on the loop iteration variable. .PP This is one of the only places where giving a prototype to a closure makes much sense. If you wanted to impose scalar context on the arguments of these functions (probably not a wise idea for this particular example), you could have written it this way instead: .PP .Vb 1 \& *$name = sub ($) { "$_[0]" }; .Ve .PP However, since prototype checking happens at compile time, the assignment above happens too late to be of much use. You could address this by putting the whole loop of assignments within a \s-1BEGIN\s0 block, forcing it to occur during compilation. .PP Access to lexicals that change over type\*(--like those in the \f(CW\*(C`for\*(C'\fR loop above\*(--only works with closures, not general subroutines. In the general case, then, named subroutines do not nest properly, although anonymous ones do. If you are accustomed to using nested subroutines in other programming languages with their own private variables, you'll have to work at it a bit in Perl. The intuitive coding of this type of thing incurs mysterious warnings about ``will not stay shared''. For example, this won't work: .PP .Vb 5 \& sub outer { \& my $x = $_[0] + 35; \& sub inner { return $x * 19 } # WRONG \& return $x + inner(); \& } .Ve .PP A work-around is the following: .PP .Vb 5 \& sub outer { \& my $x = $_[0] + 35; \& local *inner = sub { return $x * 19 }; \& return $x + inner(); \& } .Ve .PP Now \fIinner()\fR can only be called from within \fIouter()\fR, because of the temporary assignments of the closure (anonymous subroutine). But when it does, it has normal access to the lexical variable \f(CW$x\fR from the scope of \fIouter()\fR. .PP This has the interesting effect of creating a function local to another function, something not normally supported in Perl. .SH "WARNING" .IX Header "WARNING" You may not (usefully) use a reference as the key to a hash. It will be converted into a string: .PP .Vb 1 \& $x{ \e$a } = $a; .Ve .PP If you try to dereference the key, it won't do a hard dereference, and you won't accomplish what you're attempting. You might want to do something more like .PP .Vb 2 \& $r = \e@a; \& $x{ $r } = $r; .Ve .PP And then at least you can use the \fIvalues()\fR, which will be real refs, instead of the \fIkeys()\fR, which won't. .PP The standard Tie::RefHash module provides a convenient workaround to this. .SH "SEE ALSO" .IX Header "SEE ALSO" Besides the obvious documents, source code can be instructive. Some pathological examples of the use of references can be found in the \fIt/op/ref.t\fR regression test in the Perl source directory. .PP See also perldsc and perllol for how to use references to create complex data structures, and perltoot, perlobj, and perlbot for how to use them to create objects. | http://www.fiveanddime.net/ss/man-unformatted/man1/perlref.1 | crawl-003 | refinedweb | 4,341 | 65.12 |
NAME | SYNOPSIS | INTERFACE LEVEL | PARAMETERS | DESCRIPTION | RETURN VALUES | CONTEXT | SEE ALSO | NOTES
#include <sys/ddi.h> #include <sys/sunddi.h);
Solaris DDI specific (Solaris DDI).
The DMA handle previously allocated by a call to ddi_dma_alloc_handle(9F).
A pointer to an address space structure. This parameter should be set to NULL, which implies kernel address space.
Virtual address of the memory object.
Length of the memory object in bytes.., callback, if such a function is specified.
A pointer to the first ddi_dma_cookie(9S) structure.
Upon a successful return, ccountp points to a value representing the number of cookies for this DMA object.. The alignment and padding constraints specified by the minxfer and burstsizes fields in the DMA attribute structure, ddi_dma_attr(9S) (see ddi_dma_alloc_handle(9F)) is used to allocate the most effective hardware support for large transfers. by returning status DDI_DMA_PARTIAL_MAP. At a later point, the caller can use ddi_dma_getwin(9F) to change the valid portion of the object for which resources are allocated. If resources were allocated for only part of the object, ddi_dma_addr_bind_handle() returns resources for the first DMAwindow. Even when DDI_DMA_PARTIAL is set, the system may decide to allocate resources for the entire object (less overhead) in which case DDI_DMA_MAPPED is returned.
The callback function callback indicates how a caller wants to handle the possibility of resources not being available. If callback is set to DDI_DMA_DONTWAIT, the caller does not care if the allocation fails, and can handle an allocation failure appropriately. If callback is set to DDI_DMA_SLEEP, the caller wishes to have the allocation routines wait for resources to become available. If any other value is set and a DMA resource allocation fails, this value is assumed to be the address of a function to be available. The callback function must take whatever steps are necessary to protect its critical resources, data structures, queues, and so on.
ddi_dma_addr_addr_bind_handle() can be called from user, kernel, or interrupt context, except when callback is set to DDI_DMA_SLEEP, in which case it can only be called from user or kernel context.)
If the driver permits partial mapping with the DDI_DMA_PARTIAL flag, the number of cookies in each window may exceed the size of the device's scatter/gather list as specified in the dma_attr_sgllen field in the ddi_dma_attr(9S) structure. In this case, each set of cookies comprising a DMA window will satisfy the DMA attributes as described in the ddi_dma_attr(9S) structure in all aspects. The driver should set up its DMA engine and perform one transfer for each set of cookies sufficient for its scatter/gather list, up to the number of cookies for this window, before advancing to the next window using ddi_dma_getwin(9F).
NAME | SYNOPSIS | INTERFACE LEVEL | PARAMETERS | DESCRIPTION | RETURN VALUES | CONTEXT | SEE ALSO | NOTES | http://docs.oracle.com/cd/E19683-01/817-0720/6mggibe60/index.html | CC-MAIN-2016-50 | refinedweb | 457 | 54.22 |
Created on 2008-05-30 07:47 by rhettinger, last changed 2008-07-15 19:09 by mark.dickinson. This issue is now closed.
Let bin() show floating point values. This would contribute quite a
bit to people's understanding of floating point arithmetic. It has a
nice education value and it makes it easier to diagnose floating point
mysteries.
def vis(f):
""" Show binary representation of a floating point number:
>>> vis(math.pi)
'0b11.001001000011111101101010100010001000010110100011'
>>> vis(-0.375)
'-0b0.011'
"""
f, sign = (f, '') if f >= 0 else (-f, '-')
n, d = f.as_integer_ratio() if isinstance(f, float) else (f, 1)
n, d = map(lambda x: bin(x)[2:], (n, d))
n = n.rjust(len(d), '0')
s = list(n)
s.insert(len(n) - len(d) + 1, '.')
return sign + '0b' + ''.join(s)
I'm not sure about the educational value of letting obscure bugs
creeping in when someone passes a float where an int is expected :-)
Your vis() function looks appropriate for the task of educating people,
why should its behaviour be folded into bin()?
Or, if you want to educate people at all cost, the TypeError raised by
bin() when trying it on a float object could include in its message the
binary representation of the float object "for edification". :-)
I like the idea in general. It is way too common for people to be
confused by decimal representation of floats, so an obvious mechanism to
display the true value will be helpful.
I don't think a promiscuous bin() will lead to obscure bugs. Antoine
will have to give a specific example to convince me otherwise. I can
see, that extending :b format to floats may be a problem, but this is
not being proposed.
As far as the proposed implementation goes, I don't like the fact that
it always returns a fixed rather than floating point notation. (Try
vis(1e100)). I think it should behave somewhat like "%g" format.
If bin() is extended to floats, it may become confusing that hex() and
oct() are not similarly extended.
Well it's quite simple. Imagine you have a function f() which takes an
integer parameter named x, and somewhere applies bin() to this parameters.
Right now, if you call f(1.0) instead of f(1), you will get a TypeError,
which is easy to detect: you then fix the call to f(1), and bin()
produces the expected result ('0b1').
With Raymond's suggestion, if you call f(1.0) instead of f(1), no
exception will tell you your mistake, and bin() will produce a
completely bogus result compared to the expected one. If you notice the
bogus function output and find out that it contains a strange-looking
string (something like
'0b11.001001000011111101101010100010001000010110100011'), it is still
not obvious from it that the problem stems from passing a float instead
of an int. Especially if f() is a library function which you didn't
write yourself.
There is a reason Python recently introduced a stronger distinction
between ints and floats (for instance the __index__ method, which bin()
seems to use currently), I don't see the logic behind trying to undo it.
And it's not like printing the bin() representation of a float has any
actually use (besides education, but education can use its own tools
rather than builtin functions).
On Fri, May 30, 2008 at 10:52 AM, Antoine Pitrou <report@bugs.python.org> wrote:
>
> Antoine Pitrou <pitrou@free.fr> added the comment:
>
> Well it's quite simple. Imagine you have a function f() which takes an
> integer parameter named x, and somewhere applies bin() to this parameters.
This is too abstract. Depending on what f() is designed to do,
accepting floats may or may not be the right thing. For example, if
bin is used inside f() only to produce some log output, but
otherwise f() works on any number, promiscuous bin() will actually
make an application using f() more robust.
>
>
> Right now, if you call f(1.0) instead of f(1), you will get a TypeError,
> which is easy to detect: you then fix the call to f(1), and bin()
> produces the expected result ('0b1').
There is no "right now". Builtin bin is new in 2.6.
>
> ..
>
> There is a reason Python recently introduced a stronger distinction
> between ints and floats (for instance the __index__ method, which bin()
> seems to use currently), I don't see the logic behind trying to undo it.
I think you are mistaken. Python always distinguished between floats
and integers
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list indices must be integers
>>> int.__index__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'int' has no attribute '__index__'
__index__ was introduced in order to allow user-defined class
instances to be used as indices without affecting the way floats are
treated.
>
>
> And it's not like printing the bin() representation of a float has any
> actually use (besides education, but education can use its own tools
> rather than builtin functions).
That's exactly my point. Builtin bin being new, I cannot comment on
its actual use, but I've only used hex() in interactive sessions as an
easy to type alternative to the finger-twisting "0x%x" % incantation.
(IMO, "{0:b}".format(..) is even worse.) In the scripts, however, you
would rarely need to create a string representation of single number.
More often you will need to embed a number in a larger message and
thus you will use % or str.format instead of bin/hex/oct anyways.
BTW, google code search quickly revealed the following antipattern:
log.msg("real checksum: %s"%hex(hdr[19]))
(twisted-Zope-3.2.2/twisted/words/protocols/toc.py)
Surely "real checksum: %x" % hdr[19] would be a better choice. (The
0x prefix generated by hex is just noise in the log output.)
While writing my previous comments I did not realize that '%x' % accepts
floats:
>>> "%x" % 3.1415
'3'
Float support has been even improved somewhat since 2.5:
Python 2.5 (r25:51908, Nov 24 2006, 11:03:50)
>>> '%x' % 1e10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int argument required
The new stile formatting, however does not allow floats with either :x
or :b formats:
>>> "{0:x}".format(1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown conversion type x
>>> "{0:b}".format(1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown conversion type b
I don't think anything needs to be done about it given that % formatting
is being deprecated while new style format is doing the right thing IMO.
> I think you are mistaken. Python always distinguished between floats
> and integers
Sorry, my bad.
> For example, if
> bin is used inside f() only to produce some log output, but
> otherwise f() works on any number, promiscuous bin() will actually
> make an application using f() more robust.
First I'm not sure bizarre log output should be considered "more
robust". Second if you are outputting the bin() of an integer as part of
a log output, it probably means the integer should be understood as a
kind of bitfield, and then I don't see how accepting float values is
"more robust" (again). Anyway Python doesn't accept floats for bit-wise
operators (e.g. "1.0&128" raises TypeError).
I still find this proposal undesirable, for several reasons:
1. while taking the binary representation of an integer has a real
meaning, taking the binary representation of a float only exposes an
implementation detail, that is the internal layout of float numbers.
2. if two numbers (one integer and one float) are equal, it sounds
expectable that calling a function on them will produce similar output
(or fail). Of course, this is not always the case, str(1) and str(1.0)
are different. But they are not wildly different and the difference is
still easily understood. While getting something like
'0b11.001001000011111101101010100010001000010110100011' while you were
waiting for '0b11' is disturbing.
3. I'm skeptical about the educational value. People who don't know
about the internal layout of float numbers won't very likely feel
enlightened by a string of 1s and 0s. Showing a bunch of bits does not
really explain a structure.
One related feature, though, would be to know whether a string
representation of a float is exact or not.
If we allowed repr() to lose its round-trippability, this could be
implemented by making repr(0.5) return "0.5 (exact)" and repr(0.1)
return "0.10000000000000001 (inexact)".
Or this could be a dedicated method.
> While writing my previous comments I did not realize that '%x' %
> accepts floats:
And witness how it does something rather intuitive (convert the argument
to int) rather than show the internal layout of the float number in
hexadecimal form :-)
On Fri, May 30, 2008 at 1:47 PM, Antoine Pitrou <report@bugs.python.org> wrote:
..
> 2. if two numbers (one integer and one float) are equal, it sounds
> expectable that calling a function on them will produce similar output
> (or fail). .. While getting something like
> '0b11.001001000011111101101010100010001000010110100011' while you were
> waiting for '0b11' is disturbing.
I fail to see how the proposed bin(..) can produce '0b11.00100..' from
a float that compares equal to 3.
On Fri, May 30, 2008 at 1:47 PM, Antoine Pitrou <report@bugs.python.org> wrote:
..
> 1. while taking the binary representation of an integer has a real
> meaning, taking the binary representation of a float only exposes an
> implementation detail, that is the internal layout of float numbers.
>
You may have misunderstood the proposal. I read the proposal as
producing the true mathematical radix 2 representation of a float
rather than its 64-bit memory layout.
What would you say to adding float-capable bin/oct/hex (+ maybe tobase)
to the math module?
> I read the proposal as
> producing the true mathematical radix 2 representation of a float
> rather than its 64-bit memory layout.
The term "layout" was probably badly chosen.
Still, the explicit motivation for producing that representation is that
it it supposed to educate people about the actual implementation of
floats. Other than that, a radix 2 representation is quite an obscure
(and almost never used) way of representing float objects. Binary
representation of integers in comparison is more widely understood and
more frequently used, which -- I suppose -- justifies the existence of a
builtin function to obtain it.
> I fail to see how the proposed bin(..) can produce '0b11.00100..' from
> a float that compares equal to 3.
Oops, you are right. bin(3.0) would produce '0b11.', which is indeed
more readable.
> What would you say to adding float-capable bin/oct/hex (+ maybe tobase)
> to the math module?
Why not indeed.
However, as I said, if the intent is float-specific (and it is, unless
there is another inexact numeric type which warrants a specific bin()
output), then why not make it a method of float?
Better to just build-out bin() and be done with it.
FWIW, the action on ints and floats is similar to how str() handles
numeric inputs:
str(3) --> '3'
str(3.0) --> '3.0'
bin(3) --> '0b11'
bin(3.0) --> '0b11.0'
> Better to just build-out bin() and be done with it.
Ok, someone has to take a decision anyway.
However, if you do that, it should be probably decided first what
happens for hex() and oct(). Do they still disallow floats (which is
semantically reasonable but makes things slightly inconsistent)? Or are
they also changed in order to return the same kind of things as bin()
does (which would probably give awful results)?
AFAICT, there is no good use case for showing floats in in hex or oct,
so those should not chance. Also, since bin() is new, no existing code
is affected. Thanks for the comments.
Another problem with bin() on floats is that it will be a one-way street
because as far as I know, there is no function to convert a binary
string back to a float.
My last thought on this issue is that it will be helpful to add
tobase(f, n) and frombase(s,n) functions to math module (and I withdraw
my suggestion of using %g-like notation due to the conflict between E
for exponent and E for 0xE). On the other hand, there is no need to
mess up with builtin bin/oct/hex because with math.tobase float-capable
extensions will be trivially implementable.
On Fri, May 30, 2008 at 2:32 PM, Antoine Pitrou <report@bugs.python.org> wrote:
> then why not make it a method of float?
.. because you rarely want to make your functions accept 1.0, but
reject 1 and using f.bin() in your function will give it this
property.
> AFAICT, there is no good use case for showing floats in in hex
It is my impression that hexadecimal is more common than binary, in the
numerical analysis community, for exact representation of floats.
For example:
"Hexadecimal floating-point representations are especially important
when values must be represented exactly, for reproducible results — for
instance, for testing “borderline cases” in algorithms."
Or course, without hex float literals or an equivalent function for
input, hex float output is not much use.
No need to conquer the whole world. Start with bin(1.1). If requests
pour-in for hex(1.1) or for a reverse routine, we can deal with those
when we get them (in the context of their use cases).?
Saving this for after the first beta goes out.
To address the ideas brought-up so far, here's a new version that can
work with eval. The same appoach extends to oct and hex as well:
def newbin(f):
"""
>>> newbin(3.125)
'0b11001 * 2.0 ** -3'
"""
n, d = f.as_integer_ratio()
s = '%s * 2.0 ** %d' % (bin(n), -math.log(d, 2.0))
return s
The other reviewers asked for:
* same treatment for oct() and hex()
* platform independent exact representation of floats
* fixed-size exponential style output instead of tons of leading zeros
* output that round-trips through eval()
* use Py2.6 octal format in 2.6, and 3.0 format in 3.0
Attaching a patch with tests.
I don't like this modification of a PyString object:
+ n = PyString_GET_SIZE(conv);
+ conv_str = PyString_AS_STRING(conv);
+ /* Remove the trailing 'L' if present */
+ if (n && conv_str[n-1] == 'L')
+ conv_str[n-1] = '\0';
+ result = PyString_FromFormat("%s * 2.0 ** %d", conv_str, exp);
The string may have other references (ex: all single-char strings are
shared) and it seems unwise to directly modify the memory.
Also, tests should check if negative numbers have the same
representation as their absolute value (with the sign). It is not
obvious from the implementation, which uses floor().
The patch looks good to me.
It's a bit unfortunate that -0.0 doesn't round-trip correctly (the sign
of the zero gets lost):
>>> eval(bin(-0.0))
0.0
I don't know whether it's worth special-casing this; the output would
have to be in a different format: '-0b0 * 2.0 ** 0' isn't good enough,
since unary minus has higher precedence than multiplication.
Hmm, I don't see a way to preserve -0.0 without varying from the
standard format.
Attaching an updated patch for Amaury's comments.
Mark, I added tests for Inf/Nan. Will this work on all platforms?
> Mark, I added tests for Inf/Nan. Will this work on all platforms?
I think the tests should work on all common to semicommon platforms,
including on all the buildbots. They won't work on non IEEE 754 platforms
(float('nan') will throw an exception). Then again, neither will all the
Inf/NaN tests in test_math.py. Sigh.
Applied in r64438
Re-opening for further discussion.
-1 on Nick's suggestion to normalize hex output so that nearby floats
have nearby reprs. This unnecessarily complicates a simple, straight-
forward presentation. In the paper referenced by Terry Reedy,
normalized presentations were not used and I've never seen that done
anywhere else.
IMO, the patch is fine as-is.
Updating patch so that the global symbol starts with _Py.
> -1 on Nick's suggestion to normalize hex output so that nearby floats
> have nearby reprs. This unnecessarily complicates a simple, straight-
> forward presentation. In the paper referenced by Terry Reedy,
> normalized presentations were not used
As far as I can tell, that paper *does* use normalized presentations:
with the exception of subnormals and zeros, all hex floats have a leading
digit of 1. This is the same normalization that Java's toHexString uses,
and that C's printf %a format modifier uses on all machines that I've
tested (though the C standards don't seem to lay down the law on this).
I think this is helpful. For example, on the first page of section 4.1 of
the paper Terry Reedy references, the author gives two different results
produced by running the same sin() computation on different systems. The
results are:
-0x1.95b011554d4b5p-1
and
-0x1.95b0115490ca6p-1.
Looking at these results, it's readily apparent that the error is somewhat
less than 1000 ulps. But the current hex() output for these two numbers
is:
'-0x195b011554d4b5 * 2.0 ** -53'
and
'-0xcad808aa48653 * 2.0 ** -52'
It's much less clear that these numbers are close, or how close they are.
I guess I just have a feeling that changes to the least significant bits
of a number shouldn't produce big changes in its representation.
> and I've never seen that done anywhere else.
I'm not sure I've ever seen this *not* done anywhere else.
P.S. You should blame me for the normalization comment, not Nick. :)
How would the algorithm need to change to support leading-1
normalization?
Well, here's some Python code to output C99-style hexadecimal
representations of floats. It's not quite the same as Java's output,
which also special cases IEEE 754 subnormals (writing them with a fixed
exponent of -1022 and a '0' before the point). But then Python doesn't
have the luxury of knowing that its floats are IEEE 754 format.
The big downside is that the output format has a decimal point in it, so
won't be eval-able.
Attaching a patch that includes normalization to a leading 1.
Add support for non-float floats.
Here's some Python code to translate floats to hex strings and back, in
case it's useful.
Here's an updated Python version of toHex and fromHex; fixes a bug in the
previous version of fromHex for hex floats starting with an upper case hex
digit. I'm not sure how useful this is, but I thought I might as well
post the code.
I also have tests for these; to follow.
I'd be happy to help out with the C version once the API is decided on; I
have far too much time on my hands right now. Though I'm assuming Raymond
will beat me to it.
...and the tests for hex_float.py
I'm looking forward to your C implementation.
Raymond, Mark? Is a new patch with tests and docs forthcoming? Have
you decided on the API yet? I'm willing to approve this for beta 2,
which will be around July 15.
Mark, I'm tied-up with EuroPython until the 14th. Do you have time to
take a crack at this?
I'm working on it. I expect to have something ready by the end of this
weekend.
BTW couldn't you use the %a feature built into C99 to implement this?
(Both input and output?)
Sure. What about non-C99 machines? I thought Python code was only
allowed to assume ANSI C.
On Fri, Jul 4, 2008 at 7:12 AM, Mark Dickinson <report@bugs.python.org> wrote:
>
> Mark Dickinson <dickinsm@gmail.com> added the comment:
>
> Sure. What about non-C99 machines? I thought Python code was only
> allowed to assume ANSI C.
I'm pretty sure that's a thing of the past. Ask MvL.
Microsoft compilers implement %a since VS8.0.
VS7.1 does not have it.
In the interests of getting early feedback, here's half a patch,
containing an implementation of from.fromhex and tests.
Still to come: float.hex and documentation.
I'll ask on python-dev about C99 and %a.
> containing an implementation of from.fromhex and tests.
That should be 'float.fromhex', not 'from.fromhex'.
I should also have said that this patch is against the trunk; only minor
changes should be required for py3k.
Here's an updated patch, complete with both float methods and
documentation.
Add updated patch with expanded documentation.
Here's a slightly more polished version of the previous patch; no
behaviour changes.
Let me know if there's anything I can do to help get this in before next
week's beta. Anybody want to trade patch reviews?
Minor modifications to the previous patch, mostly to the docs.
Setting priority to critical, since this really needs to go in before the
next beta if it's going to get into 2.6/3.0.
Here's an updated patch that makes the trailing 'p123' exponent optional
in fromhex. (This matches the behaviour of C99's strtod and sscanf; in
contrast, Java always requires the exponent.)
I'm beginning to wonder whether the '0x' shouldn't also be optional on
input as well, in the same way that it's optional in int():
>>> int('0x45', 16)
69
>>> int('45', 16)
69
This would then allow, e.g.,
>>> float.fromhex('45')
69.0
In the spirit of being "liberal in what you accept, but strict in what you
emit", here's a version that makes both the leading '0x' and the trailing
'p...' exponent optional on input. Both of these are still produced on
output.
Note that this version is still perfectly interoperable with C99 and Java
1.5+: fromhex accepts anything produced by C and Java (e.g. via C's '%a',
or Java's toHexString), and the output of hex can be read by C99's
strtod/sscanf and Java's Double constructor, and/or used as hex literals
in C or Java source.
Some final tinkering:
- docstrings and docs expanded slightly; docs mention interoperability
with C and Java.
- in float.hex(), there's always a sign included in the exponent (e.g.
"0x1p+0" instead of "0x1p0"). This just makes for a little bit more
consistency with repr(float), with C99 and with the way the Decimal module
behaves (but not with Java, which omits the + sign).
So far this looks good. Will complete the review on the next leg of my
flight (about 12 hrs).).
Question: are the ("0x0p+0") and ("-0x0p+0") special cases standard?
The docs need a "new in py2.6"
Coding style: move the inner si++ to a separate line so there are no
side-effects and the order of execution is obvious.
Question: should the "inf" string checks be made case sensitive on
insensitive? Is there a standard?
Here's an updated patch that addresses Raymond's concerns.
>).
Done.
> Question: are the ("0x0p+0") and ("-0x0p+0") special cases standard?
Not entirely. Java outputs "0x0.0p0" and "-0x0.0p0". The C99 standard
doesn't specify exactly how the output should look, except to say that
the exponent should be 0. The '+' is there for consistency.
I can change '0x0p+0' to '0x0.0p+0' if people think this looks prettier.
On consideration, this does look better to me. Changed.
> The docs need a "new in py2.6"
Fixed.
> Coding style: move the inner si++ to a separate line so there are no
> side-effects and the order of execution is obvious.
Done. (And the same with s++ in float_fromhex.)
> Question: should the "inf" string checks be made case sensitive on
> insensitive? Is there a standard?
Everything I've seen, except Java, seems to like case-insensitivity.
The C99 standard says case should be ignored, as does the IBM Decimal
standard. Python's float('nan') and float('inf') also currently ignore
case. So I think these checks should be case insensitive.
(Java insists on infinity being spelt "Infinity", and nan being spelt
"NaN".)
Thank you for reviewing this, Raymond!
I aim to check this in when (if?) I get approval from Barry.
If you two can agree that this code is good, I'm ok with the API.
I would emphasize in the docs and NEWS entry though that .hex() is an
*instance* method while .fromhex() is a *class* method.
Mark, please go ahead and apply so the buildbots will have time to give
it a run on all the platforms before beta 2 is cut. Be sure to make
Guido's edits to the Misc/NEWS entry.
Committed, r64974 | http://bugs.python.org/issue3008 | CC-MAIN-2015-06 | refinedweb | 4,165 | 66.84 |
When)
-
- FS) or other platforms that provide this service.
AD FS FS infrastructure so that AD is responsible for authenticating the request.
AD FS FS implementation. The availability of AD FS is a key discussion point when discussing federation. For whatever reason if the AD FS FS is a hard requirement to get SSO. That is soooooooooooo Q1 2013!
Anyway, I digress let’s get back to AD FS…..
We shall look at installing AD FS 2012 R2 since there are numerous compelling features in this release!
What’s New And Improved In AD FS 2012 R2
The quick answer is a lot! Some examples include:
- IIS dependency removed
- Single server installation option removed and now have single farm install (recommended to install a farm always in prior release anyway)
- Separate AD FS proxy role removed. AD FS proxy now based off Web Application Proxy (WAP), and is used to publish the AD FS server to the Internet. WAP can publish many other applications, not just AD FS.
- AD FS extranet lockout – AD DS account lockout protection via the AD FS proxy
- Access control based on network location to control user authentication to AD FS
There are many others, but check here for them since we are focussing on Office 365 usage for AD FS.
Note that you will not see me call this release AD FS 3.0. Its full and proper name is AD FS 2012 R2. for reference here are the older versions and what some folks call them:
Update 5-5-2014: Please also see this post on exploring AD FS 2012 R2 Extranet Lockout protection.
Update 29-5-2014: Please also review update 2948086 Update that improves AD FS proxy and STS reliability in Windows Server 2012 R2 when multiple clients sign in.
Update 9-9-2014: For the other posts on ADF S, please view this tag cloud.
Planning And Prerequisites, And Other Fun Details
Prerequisites
The prerequisites are listed on TechNet and now also on docs.microsoft.com. Of course before jumping into the install the installation needs to be planned.
AD FS Role Planning
The AD FS role should be deployed within the corporate network, and not in the DMZ. The AD FS proxy role (WAP in Windows Server 2012 R2) is intended to be installed into the DMZ.
The default topology for Active Directory Federation Services (AD FS) is a federation server farm, using the Windows Internal Database (WID), which may contain FS when the domain is federated there is a strong recommendation to have at least two AD FS servers with a redundant AD FS proxy infrastructure.
Please review the design guidance on TechNet.
AD FS Service Account
We can now use a standard service account or a Group Managed Service Account in AD FS 2012 R2.
In this case since the KDS root key was not configured, lets leverage a standard service account.
The installation process should set the required Service Principal Names (SPN) on the account.
AD FS Namespace
Select what name you are to use to access AD FS. Typically this is along the lines of:
sts.wingtiptoys.ca
adfs.tailspintoys.ca
Note that this is the namespace for the AD FS service. Since we will be using Kerberos to access AD FS internally, there must be a Service Principle Name (SPN) registered for this name. This will be associated to the service account, and since SPNs operate in the “Highlander – there can be only one!” mode you do not want to duplicate the SPN on the AD FS server by naming the computer the same as the AD FS namespace.
You also want to discuss what display name should be chosen, as this will be visible to users.
Additionally you may also wish to plan to also enable Device Registration Service (DRS) as well, this is a separate namespace. For more details please see Configuring Device Registration.>
This would be enterpriseregistration.tailspintoys.ca in this environment.
Internet Access
The AD FS server will require access to the Internet in order to complete the configuration of the solution. This may be an issue if your servers are behind a proxy solution.
Certificates
Since AD FS FS FS server, and in the future add another AD FS server for redundancy.
If you wish to use the Device Registration Service (DRS), then add the additional name onto the certificate. Even if you are not using DRS now you may want to save the time updating certificates later on.
Installing AD FS On Windows Server 2012 R2
After starting up server manager’s add roles and features wizard, select Active Directory Federation Services, then click next.
We don’t need to add any additional features. Remember that the IIS dependency was removed in AD FS 2012 R2.
Clicking next takes us to the AD FS splash screen. Note that it helpfully tells us that the specific AD FS proxy role has been removed in Windows 2012 R2 and how to go about installing it. Shame I missed that the very first time I ran this, and could not find the old school AD FS Proxy role…
Clicking next will then install the necessary bits.
Bits are being shuffled around…
Shuffling has been completed, and the installation is complete. You can launch the AD FS configuration wizard from here, or alternatively if this window is closed it can be launched from server manager.
Before starting the AD FS FS farm or add this box to an existing farm. This saves the painful issue from older AD FS builds, where AD FS was not installed into a farm you were then unable to add the second AD FS server for redundancy. In that case you had to build a net new farm.
Provide your domain admin credentials.
We need to select the SSL certificate that we will use and also provide the AD FS name we selected in the design process.
In this case the name is adfs.tailspintoys.ca -- note that there is no concept of an InternalURL or ExternalURL for the AD FS namespace. Clients will use the same name on the intranet and internet to locate AD FS. Thus split DNS will make life simple!
Provide your chosen display name, and click next.
As mentioned earlier it is possible to use a GMSA as the AD FS service account. GMSA will automatically update the service account’s credentials and administrators will also be oblivious as to its password. Note that if you do want to use a GMSA, please review the required setup for this, noting the DC version requirements and the steps you must manually perform. Add-KdsRootKey FS pre-requisite checks are done, and we can proceed to the configuration:
One coffee later, we have a shiny new AD FS server – whoo!!
We are not quite done yet, and there a couple of additional things to do!
Next Steps
AD FS Update(s)
Update 29-5-2014: Please also review update 2948086 Update that improves AD FS proxy and STS reliability in Windows Server 2012 R2 when multiple clients sign in.
When multiple clients (over 200 clients) try to sign in by using an Active Directory Federation Services (AD FS) proxy, the AD FS proxy consumes 100% usage of the CPU. In this situation, the AD FS proxy performance is slow, and causes a delay that exceeds 10seconds. This also causes STS to work under minimal load. Therefore, STS rejects the requests or serves only 5 to 10 requests per second.
Update 11-12-2014: The above update 2948086 is now bundled in this rollup: May 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2
Update 16-7-2014: Other updates you may want to review are at the bottom of this post.
Update 4-11-2016 And you will also want to review this list of updates and fixes: Updates for AD FS and WAP in Windows Server 2012 R2
DNS A Record
We must create the DNS record for the AD FS instance. This maps to the AD FS namespace that we previously planned. Create this A record in your internal DNS infrastructure.
Ideally you will have two AD FS servers for resiliency, in which case you will need to create a load balanced VIP for this service. Please follow the steps for your specific LB device. The DNS A record should resolve to the VIP. For testing purposes, use a hosts file on a client to check out individual AD FS servers – do not try and just use the IP address of the box.
Once the DNS record has been created and propagated, ensure that it resolves correctly.
One thing to mention here, if you create a CNAME and point that to the server hosting AD FS chances are that you will run into a never ending authentication prompt situation.
In the below example the AD FS namespace is called adfs.tailspintoys.ca and a CNAME was used to direct traffic to the AD FS FS server’s federation metadata URL.
This will be something like the below, just change the FQ DN to match your environment.
The result should show this:
Verify AD FS Sign-In Page
Browse to the AD FS FS instance is functioning appropriately we can then move onto installing the AD FS proxy role (WAP).
This will be covered in the second post in this series, to prevent this one getting too long!
Cheers,
Rhoderick
In part one we installed the ADFS server on our corporate network, and tested that it was working. Now
Well then, here we are in part three already! Previously we: Installed ADFS 2012 R2 For Office 365 in
Excellent
Thanks
Security is an integral aspect of running modern IT operations. There is a clear understanding that we
Nice work
Excellent just what I was looking for.
The blog post on how to integrate Office 365 with Windows 2012 R2 ADFS raised an interesting question
My configuration fails every time during the WID install and gives an error that the service cannot be started. I’ve even tried granting the service accounts log on as rights. Still no go.
Excellent, worked a treat
Jason, I had the same issue.
This fixed it for me.
Good write-up but the word "leverage" is overused.
@Adam – it’s in there 4 times to annoy one of my ex-colleagues. Bit of a history 🙂
Rhoderick this is a great post. We just decided to to look into ADFS. A curious question… Does ADFS 3.0 in 2012R2 allow for a single server setup? Meaning we wouldn’t have to deploy a server in the DMZ? We only have 100 users and don’t require a very
complicated setup. Thanks for you time! 🙂
Hey Rhoderick, your post helped me to just confirm a few differences between the ADSF 2.0 I have done in the past and the 3.0 I need to do now; very succinct thanks! Was a bit surprised when I scrolled down and thought to myself "Hey, I know that guy!"
You came in for a review of our environment while I was working in Toronto once.
Hi Hayden – it’s a small world innit 🙂 ?? Thanks for the shout out – much appreciated.
Steven – not something I have ever done or thought of doing.
On
The following AD FS requirements are for the server functionality that is built into the Windows Server® 2012 R2 operating system:
• For extranet access, you must deploy the Web Application Proxy role service – part of the Windows Server® 2012 R2 Remote Access server role. Prior versions of a federation server proxy are not supported with AD FS in Windows Server® 2012 R2.
• A federation server and the Web Application Proxy role service cannot be installed on the same computer.
I’ll see if I can find some other references.
Cheers
Rhoderick
Does O365 support ADFS 2.1 ?
thanks
Mark – Yes, we are using ADFS 2.0 on Windows 2008 R2 servers with o365 and are looking into upgrading to ADFS 3.0 in the near future. The way I understand it, all versions of ADFS are supported by O365. Someone else can correct me if I am wrong on this.
Hi Rhoderick,
do I understood right, that if we need implement Office365 (Exchange Online) with SSO, we need 2 additional servers on-premise for ADFS Server and ADFS Proxy roles?
Thank You.
This is really a great post and things went swimmingly for the installation. My only problem is verifying the ADFS using IE, I can’t get a web page to display. My question is, how can the server display a web page if IIS is not installed?
Brian & Mark G. – Yes you can use that, but all of the shiny new features are in ADFS 2012 R2.
Older ones are still listed in here, for example:
Cheers,
Rhoderick
Mindaugas – that would be the minimum recommended number of ADFS servers.
If you wanted HA, then double that. If that is overkill for a small organisation, please look at the works with Office 365 programme as there are providers that will do this for you at a small fee per user per month.
Cheers,
Rhoderick
Hi Rhoderick,
Deploying for a customer currently, I get the error "Unable to configure the private key store", but am unable to find any clues on the internet. Do you have any idea what can cause this?
thanks
Sorted it, misconfigured firewall rule – LDAP wasn’t open from the network zone where the ADFS servers are located to the PDC Emulator. Added it to the rule and it’s installed.
Ok that was easy enough – when I followed your guide…
Thanks!!!!
Thanks for the comment Mick – glad it helped!
Andy – good you are up and running. After seeing a customer today with a 2008 R2 DC called "PDC" and the other DC called "BDC" it reminded me of the importance of the PDC emulator role even nowadays!
Cheers,
Rhoderick
Hi Rhoderick,
Thanks for the write up. I currently have an on-premise ADFS 2.0 farm working with O365 and want to add an ADFS 3 server on Azure as a secondary server and then make it the primary. Besides setting up a VPN tunnel to Azure and the normal install and join ADFS
farm steps are there any other configuration that I need to do or consider?
Thanks
Thanks mate
STILL NO DOCUMENTATION FROM MICROSOFT FOR HIGH AVAILABILITY ADFS 3.0 implementation ?????
Rhoderick,
Can you tell me if it’s possible to setup O365 with ADFS to allow a hierarchical login option? Meaning, the default option is to use certificate based authentication but if the end user does not have a smart card they have the option to use their LDAP user
name and password as a secondary option?
Perfect!!
Rhoderick, kb/2948086 states "not applicable to your computer" when launched from a 2012r2 farm server. Has this been superseded by another update? Maybe I’m not awake yet?
Tim – let me see what I can find on this.
Cheers,
Rhoderick
Mr Update (for lack of a better name, could be MRs but I’m guessing…. 🙂 )
That will probably be the case, I suspect you just built a 2012 R2 server, have it fully patched and went to install that update?
Cheers,
Rhoderick
Looks like it is in here:
May 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2
Cheers,
Rhoderick
1 Úvod
V tomto článku se budeme zabývat povýšením ADFS serverů
Excellent blog
SInce SSO is now supported without the ADFS, what are the advantages of keep using ADFS?
En la transición de una organización hacía Office 365, un escenario muy habitual
This is a link throw-down for the items that we discussed during a recent Office 365 workshop that I
can we use self-signed certificate
Please see the Certificates section in this post.
Cheers,
Rhoderick
Nuno – that is a good question. Have something in draft for you! Will publish it shortly.
Cheers,
Rhoderick
Great Blog. This helped me so much planning and finding the necessary requirements, and then finally implementing this in 10 minutes or less. Very much appreciated.
I can browse to the federation metadata OK –
For both adfs and sts, I’m using an A record and have my spn registered "host /sts.contoso.co.uk" for service.adfs
But displays a 404 every time!
Please advise
Never mind, with ADFS and Windows 2012 R2 the actual URL is
Challenges………..
Additional Hardware
ADFS: Two clustered servers in the DMZ; two clustered servers behind the firewall
<Snip>
Removing 3rd party advert. If naming a vendor, please name 3 or none.
</Snip>
Not a 3rd party advert, simply stating facts about ADFS server vs another product. Quite happy for you to address each challenge presented. However I’ll amend without naming the vendor if you so wish
Additional Hardware
ADFS: Two clustered servers in the DMZ; two clustered servers behind the firewall
Un named product: None
Firewall Reconfiguration
ADFS: Requires hole in firewall
Un named product: None
Third-party certs
ADFS: Required
Un named product: None
Support for additional SaaS apps
ADFS: Requires individual configuration and debugging
Un named product: Choose from a rich catalogue of pre-integrated apps
Time to implement
ADFS: 1-2 weeks for Office 365; days to weeks for additional apps
Un named product: Less than an hour for Office 365 or any other app
I’m on the my 3rd iteration of my EMS lab. Meaning, I had something up and running (twice) then tore
Excellent article !!!
Very nice and helpful article, Thanks. I am stuck in configuration wizard, where ssl certificate and Federation Service name is required. I have self signed certificate, when give that certificate, it does not respond and next option becomes disabled.
Meraj – you must have a valid 3rd party certificate. It will not function with a self signed cert for the service communication certificate.
Please read the certificate section above
Cheers,
Rhoderick
Hi,
the confusion is related to the amount of information that I’ve read. (Dirsyn, ADFS 2.0 and Active Directory)
I have two scenarios to understand what options I use.
1 – Active Directory site with users who use the CRM / Office 365. Of the 300 members, only 20 use CRM / Office 365. They access both internally and externally, when they are at home office.
– Basically, I thought of installing a server to use the dirsync that will synchronize users and passwords that are in Active Directory Azure (Office 365 / CRM)
– Question 1: When I enable synchronization, I understand that it will create new users in Active Directory Azure, but these users already exist in Active Directory Azure. The risk that I have is that after synchronization, users already using the login Active
Directory Azure have problems with CRM / Office 365.
– Question 2: I can choose which users will be synchronized? Or must all be?
– Question 3: Should I use ADFS in this scenario?
2 – I am planning to migrate users of Group Wise to Office 365.
– I’ve read the migration will be performed using the tool QUEST and will use simple forwarding SMTP.
– Basically, I will enable Office 365, add the domain, install a server with dirsync and activate the licenses for users who use Office 365. Right?
– However, the dirsync has some negative risk, such as the replication time password. Is not immediate. So researching started reading about ADFS. It seems that the configuration is simple ADFS, but from what I understand, all users, whether internal or external,
need to go through ADFS and if it is unavailable, becomes a point of failure.
– If I use ADFS, the login method in Office 365 will be the same using (@ domain.com)? Or should be done (domain login)?
– Another point is the fact of using a proxy ADFS. I did not understand his job exactly. I was not sure whether I need it or not really.
– Other information I read was about the ADFS Federation Gateway. I married confusion further.
– I also read that some experts use ADFS 2.0 (Windows 2008 R2), but there ADFS 3.0 (Windows 2012). I do not know which one to use? What changes between the two.
– My goal is: To enable users migrated to Office 365 using the same username and password from the local Active Directory.
Thank you.
Great help.
@Confused – you win the prize for the most questions ever in a blog comment 🙂
Use the latest version of ADFS. Currently 2012 R2, it has the most features.
There is no ADFS Federation gateway. There is MFG, but that is for Exchange really.
If you already have user objects in a tenant, look at the soft match process.
Cheers,
Rhoderick
Internal and external domain UPNs are different:
Internal: hq.contoso.com
External:contoso.com
Do I need to setup split DNS for contoso.com? That domain only exists external and everything works just fine: www, OWA, Autodiscover, ActiveSync, etc….
Its stated: "note that there is no concept of an InternalURL or ExternalURL for the ADFS namespace. Clients will use the same name on the intranet and internet to locate ADFS. Thus split DNS will make life simple!", I’m a bit confused how this might affect
name resolution for services: www, OWA,ActiveSync, etc….
That’s because Exchange has the concept of internal and external URLs Rocky. ADFS does not, and only has a single namespace so you must have that same name available internal and externally .
Cheers,
Rhoderick
Ok. Understand that namespace must made available internally and externally. But, how do I make that namespace available internally to our domain users without potentially disrupting our other services (i.e;, autodiscover.contoso.com, vpn.contoso.com,
owa.contoso.com, etc…)??????
I’m assuming i create internal dns zone for contoso.com and create a record with internal IP of ADFS proxy.
Thanks!
Is the Service Principal Name "fs.Company.com" possible as an principle Name (NLB an ADFS ist identical)? Our internal Outlook authentification ist actual Basic and not Kerberos? Whats going wrong? Must I configure anything else?
Thanks Excellent
Thanks Excellent
Great write-up! Just one comment…for the SSL cert, you want to mention that it needs to be a Legacy Key instead of a CNG Key.
If I use DirSync to provide single signon do I need AD FS server?
Thank you great guide. So I actually try to connect smart card PIV to offie 365 with adfs 3.0 but not working. I have the open port 49443 and the following url offer the option x.509 WHEN I PUT THE SMART CARD AND SAYS THE ERROR not reading. I review in the event viewer and this the error:
Encountered error during federation passive request.
Additional Data
Protocol Name:
wsfed
Relying Party:
urn:federation:MicrosoftOnline
Exception details:
System.ComponentModel.Win32Exception (0x80004005): The user name or password is incorrect
at Microsoft.IdentityModel.Tokens.X509SecurityTokenHandler.KerberosCertificateLogon(X509Certificate2 certificate)
at Microsoft.IdentityModel.Claims.WindowsClaimsIdentity.CertificateLogon(X509Certificate2 x509Certificate)
at Microsoft.IdentityModel.Claims.WindowsClaimsIdentity.CreateFromCertificate(X509Certificate2 certificate, Boolean useWindowsTokenService, String issuerName)
at Microsoft.IdentityModel.Tokens.X509SecurityTokenHandler.ValidateToken(SecurityToken token)
at Microsoft.IdentityServer.Service.Tokens.MSISX509.PassiveProtocolHandler.RequestSingleSingOnToken(ProtocolContext context, SecurityToken securityToken, SecurityToken deviceSecurityToken)
at Microsoft.IdentityServer.Web.Protocols.WSFederation.WSFederationProtocolHandler.BuildSsoSecurityToken(WSFederationSignInContext context, SecurityToken securityToken, SecurityToken deviceSecurityToken, SecurityToken& ssoSecurityToken)
at Microsoft.IdentityServer.Web.Protocols.WSFederation.WSFederationProtocolHandler.ProcessSingleSignOn(ProtocolContext context)
at Microsoft.IdentityServer.Web.PassiveProtocolTlsClientListener.ProcessProtocolRequest(ProtocolContext protocolContext, PassiveProtocolHandler protocolHandler)
at Microsoft.IdentityServer.Web.PassiveProtocolTlsClientListener.OnGetContext(WrappedHttpListenerContext context)
I would like to know the step to recognize our smart card to validate in office 365.
Thank you
Hi Rhoderick Milne,
We have deployed Azure AD sync server, ADFS servers with HA using NLB and ADFS porxy servers with HA successfully. And the details are below
Internal Domian : Crest.local
.local domains will never work over the Internet. That’s the whole point behind them.
Use a publically routable namespace.
Cheers,
Rhoderick
JB – start with this please:
Cheers,
Rhoderick
The year 2015 is almost done, and 2016 is upon us! As in previous years , I thought it would be interesting
Good Afternoon, Please help me. I have set up ADFS 3.0 on our DC running Windows Server 2012 R2.
I have Dirsynced all our accounts to Office 365 configured Single Sign On. I can Redirect to our ADFS logon page However when you redirect the ADFS Logon Page it is asking still for a password. I have AD synced to Azure also and according to both domains they
are federated for Single Sign On. I have assigned a Wildcard Certificate and made sure the domain exists everywhere. I also have The Token Certificates configured as per what ADFS makes when it is set up. As far as I can see it should all work however I still
can’t get it to just bypass the logon and go straight into office 365. It does login manually absolutely fine using the UPN Suffix. I have made sure all accounts have been updated to the UPN Suffix I wish to use. I have also got TMG 2010 Configured as our
Web Application Proxy and when you do a test using the test connectivity page on Microsoft it all passes. I am just not sure what I could be missing to cause it not to logon automatically. Any help would be really appreciated.
Thank you,
Damien
Damien,
if you follow the series of these 3 articles it will walk through all of the steps required.
What do you mean you are using TMG as WAP?
Cheers,
Rhoderick
Hi I don’t have ADFS Proxy , while login to
getting error :
Additional technical information:
Correlation ID: 91383
Timestamp: 20xx-0x-x8 21:49:48Z
AADSTS90019: No tenant-identifying information found in either the request or implied by any provided credentials
Great Post but I have few questions:
Everything successfully installed and configured as expected, but One issue when tried to login using the credentials of the on-premises mailbox to login using the Federated page, it says “we do not recognize this user id and password. Be sure to type the password correct…..” Now need to know that why this issue is occurring? Sice I am using the correct password…Second Question is DO I need to setup Azure AD Connect for Password Synchronization?? Will be waiting for your reply??
Good Write-up.
I am getting the following error while adding ADFS role :
Error:.
I tried to Manually register the SPN for adfs user
setspn -a host/******.*****.com *****\user –> it says already registered
then i tried to unregister using the following
setspn -D host/******.*****.com *****\user ->> it shows unregistered but again when i try to re-register it says duplicate found
I do know that setting up SPN will be done the ADFS Wizard itself but why in my case not working.
This is not right.
Check AD replication, can some something like the AD Replication Status Monitor.
Then check for duplicate SPNs. The newer versions of setspn.exe can do this quite easily
setspn -X
Cheers,
Rhoderick
We have followed this post and was successful on the implementation. I have a question though. Is it possible to change the password for the service account used? I know that recommendation is to set the account to “never expires” but our client wanted to change the password. Can you advise on the recommended steps that we can follow? Thanks in Advance.
Hi James,
Yes – that is doable. Let me finish off a draft post and publish that for you.
Cheers,
Rhoderick
Take a peek at this one James:
Hi rhoderick. Great article on setting up adfs although i have some problems setting up sso. When browsing to the adress i am always asked to enter my credentials even though i have added the adfs adress to local intranetzone. Any idea why
Yes – Draft post to get finished. Let me try and get that done in the coming days.
Cheers,
Rhoderick
The link in this article to set up the AD FS Poxy is broken!
Thanks! Have updated the link.
The permalink was point to the wrong place, the content was there on the full path:
And also via the tag cloud on the right hand side.
Cheers,
Rhoderick
Im trying to complete the post deployment configuration – the ADFS role is installed !
certificate imported, gmsa setup, pre-reqs ticked but when I click configure I get ..
The parameter is incorrect .. show more .. does not show more .. any ideas ? :-/ .. thanks
nice blog btw .. | https://blogs.technet.microsoft.com/rmilne/2014/04/28/how-to-install-adfs-2012-r2-for-office-365/ | CC-MAIN-2018-43 | refinedweb | 4,767 | 64.91 |
market risk premium
Definition
Use market risk premium in a sentence
“ The market risk premium that he was looking at if he were to boldly invest his money in the stock market was simply too great to him to warrant the risk. ”
Was this Helpful? YES NO 4 people found this helpful.
“ While they could earn two percent on treasury bonds, they knew they could earn about five percent in the market. That extra three percent of market risk premium was worth the risk. ”
Was this Helpful? YES NO 7 people found this helpful.
“ The amount of return (yield) that one receives for investing in a market asset that is above the yield returned from a riskless asset (i.e. short treasuries) is the market risk premium, and represents the compensation for the additional degree of risk. ”
Was this Helpful? YES NO 5 people found this helpful.
Show more usage examples... | http://www.investorwords.com/6575/market_risk_premium.html | CC-MAIN-2020-05 | refinedweb | 151 | 75.71 |
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Philipp von Weitershausen wrote: > Tres Seaver wrote: > >> - The opposition to namespace declarations is whiny, as they are the >> standard way to make XML extensible. Unless we are going to quit >> using XML, outlawing namespaces would be equivalent to saying, "you >> may not extend ZCML"; I don't think we are smart enough to make that >> ukase. I think the Last Law of Python according to the Prophet >> Peters obtains here as well. > > > I'm neither trying to follow the whiny people who detest XML and > therefore ZCML nor am I trying to make ZCML not extensible. That said, I > think that ZCML's usage of namespace is quite arbitrary. Why is browser > and mail-related stuff on its own namespace but security-related stuff > not?
I'm not arguing (here) against refactoring the namespaces in which "core" directives are declared. I'm arguing against the idea that namespaces are bad in general. > Why is it then recommended that third-party packages use their own > namespaces, even though they might only have browser-related directives > to register...? Third-party packages which don't define new directives don't need their own namespaces. If, for instance, Plone adds a "plone:view" directive which is nothing more than a no-op wrapper around 'browser:view', that would be a Bad Thing (TM). If, however, they add a 'plone:frobnatz' directive which does something magical and outside the scope of the Zope core, and document how to use it when setting up Plone, that would be a Good Thing, especially if it kept people from changing "site policy" by customizing software. > I don't really see the point in ZCML's using namespaces. What good do > they provide? Seriously, is it just the prefix? Well, we don't need the > namespaces for that. ZCML *must* support extensibility, and therefore must continue to allow packages to register their own namespaces (unless we abandon XML altogether). Otherwise, we give up the ability to check that a given directive can actually be interpreted at all, which would be a Bad Thing. >> - Note that the non-XML language also used by Zope (ZConfig) has its >> own extensibility mechanism: in fact, Fred and I made it possible >> in November for Zope2 products to register their own schemas for >> those extensions, which was a blocker for moving some configuration >> out of software. > > > I'm not sure what to do with this info... Just note that being able to extend the configuration language from non-core code is an important use case. >> - I don't want to encourage people to do configuration in Python: > > > Rest assured neither do I. > > >> we have moved away from that *on purpose* in Zope, and I don't see >> a reason to go back. Directives which make it possible to change >> policy decisions without touching software are a Good Thing. I think >> that letting people who spend their days up to the elbows in the >> software make choices here skews the picture: we *want* people to >> be able to change the behavior of the system in controlled ways >> without having to modify software; I would prefer to hear feedback >> from non-core-developers before going further with the "ZCML delenda >> est" thread. > > > I have heard such feedback, otherwise I wouldn't have taken the time to > write the proposal. I've also heard positive feedback on this particular > matter (reducing ZCML namespaces to one). Again, I wouldn't have brought > it up otherwise. A lot of the feedback seemed to be along the lines of: - "ZCML sux -- I won't use Zope3 until it is gone!" They weren't gonna use it anyway. - "Why do I have to declare the namespaces?" (XML haters, for the most part; note that I am not an XML fanboy myself). - "Why does the core use more than one namespace?" This question seems legitimate to me: I think we wanted to allow non-mangled names for otherwise conflicting directives, e.g. 'browser:view' and 'xmlrpc:view'. >> - The "application vs plugin" discussion is probably germane to this >> issue, as well: a user who is deploying a single application is >> acutally *more* likely to define and use convenience directives >> which reduce the amount of effort required to change policy than >> the generic appserver-with-plugins configuraiton. Removing the >> ability to create such convenience declarations makes it harder >> for those developers. > > This belongs in the other thread, really. But here it goes anyway: > > I'm not convinced that people who deploy apps will actually go as deep > as editing package ZCML, or even overrides for that matter. I would > rather imagine they turn ZCML features on or off (which would then turn > on or off ZCML directives via zcml:condition) Nope. You are ignoring the cases which are currently done TTW in Zope2: mailhost configuration, for instance, or caching policies, etc. If an application wants to add a diretive which makes it possible to configure such policies in ZCML, why should we prevent that? >> - Many of the objected-to directives exist precisely because people >> did not want to type the much more verbose equivalents which were >> the original, "cleaner" spellings. > > Or perhaps people just thought that people wouldn't want to type in some > extra stuff. Because I think they do if it helps them remember and > understand better. The origin of the "dead chicken" meme, was Guido (and others) who objected to the mistake-prone typing required by the earliest set of directievs we had; Guido called them "dead chickens".LP6+gerLs4ltQ4RAuoRAKCAlLEORfvO7tp120QAQhv3lTQ7JACeLgxt NeUfI9mQ5TWhRO+typeHKcg= =8EfQ -----END PGP SIGNATURE----- _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg04040.html | CC-MAIN-2016-44 | refinedweb | 941 | 60.65 |
Hi, Today I've tried to send in Matt's gnulib patch to upstream with more of less luck. As for now compiles fine, but one of the test fails. According to Bruno it's a bug in out lseek implementation and contains the following:. You can download the testcase if you want, but I also attach a simple testcase. Let me know what do you think about it. -- voroskoi
#include <errno.h> #include <stdio.h> #include <unistd.h> #define ASSERT(expr) \ do \ { \ if (!(expr)) \ { \ fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \ fflush (stderr); \ abort (); \ } \ } \ while (0) int main(void) { ASSERT (lseek (0, (off_t)-4, SEEK_CUR) == -1); ASSERT (errno == EINVAL); errno = 0; ASSERT (lseek (1, (off_t)-4, SEEK_CUR) == -1); ASSERT (errno == EINVAL); errno = 0; } | http://leaf.dragonflybsd.org/mailarchive/users/2008-06/msg00000.html | CC-MAIN-2014-42 | refinedweb | 126 | 76.82 |
Can't reach instances by floating IPs; can ping router
Hi,
I have an interesting problem I've not encountered before. I have recently created a new OpenStack environment that is functional in every respect but networking. I can instantiate instances and associate floating IPs, but when I attempt to
ping or
ssh, I receive no response from the nodes. I can
ping the router from my external network.
I have configured my external network as a flat network with network address 10.247.1.0/24 and gateway 10.247.1.1, according to my physical network. I then created a local internal network with address 10.10.0.0/24 and gateway 10.10.0.1. I created a router and added the two networks (10.247.1.5 and 10.10.0.1 as interfaces).
I can
ping the router:
$ ping -q -c 3 10.247.1.5 PING 10.247.1.5 (10.247.1.5) 56(84) bytes of data. --- 10.247.1.5 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1999ms rtt min/avg/max/mdev = 0.153/0.171/0.200/0.023 ms
I can also associate floating IPs with my instances. However, I cannot reach the instances themselves:
$ ping -q -c 3 10.247.1.7 PING 10.247.1.7 (10.247.1.7) 56(84) bytes of data. --- 10.247.1.7 ping statistics --- 3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2015ms pipe 3
If I try to add instances to the external network itself, I cannot
ping them, which leads me to believe there is some issue with my network configuration.
Is there some configuration file or any more information I could provide that could help with this?
I appreciate any information.
Thanks!
First thing to check: Does the instance's security group allow ping/ssh. Next, use console to see if the instance has received its fixed IP address. Can you ping the router from the instance. Can you ping external addresses from the instance. Can you ping the fixed IP from the DHCP namespace.
Dear Bernd, when you answer questions, could you please do it with the "Add answer" functionality instead of "Add comment"? That would make it easier to see which questions already got answered. Thanks a lot! David
I didn't consider it an answer, as I don't know exactly where the problem is. | https://ask.openstack.org/en/question/110749/cant-reach-instances-by-floating-ips-can-ping-router/?answer=120415 | CC-MAIN-2021-21 | refinedweb | 409 | 77.43 |
Are HP merely just creating new niche sites and hoping Google will pick them up? or are they actively promoting the sites in the wider world of the niche the site is based on?
Precisely the question I asked in another thread … ost2809714
Have you seen any mention of them by other sites on Google?
I looked for Feltmagnet - and just kept coming across a lot of sites which are referencing magnets with felt on for the fridge! It doesn't even make the first two pages of Google.
So basically this is just an exercise in SEO then?
Goodness no!
If this was an exercise in SEO then we'd see an awful lot more than just creating new sites and moving content to them! That was my point in the other thread/comment
As I said in the other thread, Admin appears to be doing exactly what they did almost ten years ago when HubPages first launched.
To the best of my knowledge, this company has never advertised itself in the past ten years, so it doesn't seem that odd that they are not doing that now.
How would a struggling content site who never had a clear focus or direction in all that time, whose CPMs have fallen 90% in the last five years, get an advertising budget anyway?
Officially, HubPages' line has always been that it's up to the individual writers to promote their own work. HubPages has always promoted itself to writers, but not to readers. I did meet someone once who claimed they were paid by HubPages to do Facebook Likes, Tweeting etc for Hubs but I'm not convinced it was true.
Well if they want to increase traffic but continue to rely for marketing on the same writers this must mean they assume that just putting "the best writers" and "the best content" on a category site (they're not niche sites) is all they need to do.
Which means any difference in traffic (between HubPages and new site) is down to the individual author?
Hmmm - we'll see what difference it makes.
So basically HP is just free content hosting with monetising tools?
It really could be so much more
If you think about it Adam, there was a good reason for HubPages' policy. How do you effectively promote a site that covers hundreds of different topics?
Sharing on social networks is futile unless you're able to build a big following, and for that you need to offer something special - expert knowledge on a particular topic, or fast access to news for instance. Who would want to sign up for a Twitterfeed to HubPages - it would mean being bombarded with random articles all day every day most of which you wouldn't be interested in. And if HP were going to create separate social accounts for every topic instead, they'd need an army of staff and they could never have afforded it!
For the first few years of HP's existence, the site was so successful that it wasn't an issue. But it's one of the reasons why generalist sites find it so hard to survive now - it's a big problem for all of them.
It's also still a problem for the so-called niche sites, which (as MakingaMark rightly points out) aren't really niche sites - they're not specialist enough. Even if they decided to try social marketing, no one is going to want to sign up to follow them. People who do craft don't want to see posts about photography and vice versa, so they would soon get tired of following FeltMagnet. RV'ers will give up on AxleAddict because they'll see too many posts about cars. And so on.
Meanwhile those of us that do know a thing or two about niche topics and who set up our own sites and are also prepared to make an investment in the social media marketing required can see a major increase of very targeted traffic. I've been amazed at how much traffic I get for one of my niche sites which isn't even recognised as a sub-niche within the HP set-up. Nor is it likely to be!
If I search for a 'Cat Cave' for instance, I come up with my felting tutorials on the first page. If I search for feltmagnet I get exactly what you got, magnets or every description. I think the site name makes little difference, but searching for the subject matter does I promote my writing here as much as is possible with google +, Pinterest and Twitter and less often Facebook. I don't want to spam my friends. I do however think it is up to us to promote our writing.
To reach this FeltMagnet thing...you need to spell it exactly as they posted it here; FeltMagnet (even reading it hurts my eyes!) Make sure that the search results keep both words together.
Anyway, I have begun copying my over 755 hubs to a word doc to use in an ebook. Once that is done I shall part into the Sunset.
You can have an ebook and the same articles online. You are not required to remove the hubs.
That is a shame. Would I be correct to say that you could put them into an e-book and they would not be considered as duplicate content? From what I can gather this is what many people do! Why not leave them to earn here as well?
It does not seem to matter how you spell the FeltMagnet thing you still get fridge magnets and a lot besides:)
Content on an ebook does not count as duplicate but I am so disappointed that right now it does not make much sense to keep anything here plus I have lost the joy of posting anything here anymore.
The idea of moving so much content is a daunting prospect. If there were an easy way ..............
Sally - it works the same way as doing anything that's big. Get started and do a bit at a time. Bite off small chunks and get chewing!
The main thing to do is get an archive of all your pages first. That way you can preserve what you wrote and all your live links. Safari (for Apple users) makes great webarchive pages with live links. Evernote also takes a complete copy and keeps the live links. (Everything else I tried when moving from Squidoowould lose bits or links.)
Luis, why don't you use them to create a website of your own? 755 Hubs is more than enough content to create a good-sized authority website.
You'll need to be generating quite a lot of income to cover the costs of your own site though. Please correct me if I'm wrong.
Cost of running a website: less than $10 annually for the domain name, plus cost of hosting - $4 to $6 per month.
The biggest obstacle to having your own site, for most people, is the learning curve of setting it up. Once you've done it a few times you realise it's actually simple - but if you're not technically minded it's a nightmare the first time!
If you want to play with the idea, then the best way is to join Wordpress.com and start a site there. If you buy a proper domain name for it, then when you're ready to move to self-hosting you can transfer the whole site easily and seamlessly, and not lose any traffic.
(To explain, the reason you wouldn't stay with Wordpress.com forever is that you're not allowed to put advertising on the free version of Wordpress.com).
Or if you have enough for what I call a "Mega Niche" (that's a proper dedicated niche topic but it's a big one with different aspects which you can cover properly) then it's worth looking at creating a static website for the static content with an embedded blog for the dynamic stuff.
I'm using Weebly to do this and I very much like the combination of the proper website for the information which may get updated from time to time and the blog for current stuff, new announcements etc. It works really well.
However you need to use a Starter Pack to get out from under the fact Google does not index the free sites so you need to have a LOT of content to make one of these worthwhile.
I don't do blogs, I do websites. Wordpress works just as well for websites as it does for blogs and you can do exactly the same thing on it as you can do on Weebly. I prefer Wordpress because (a) it's cheaper and (b) it's fully transferable - if I'm dissatisfied with my host at any time, I can transfer to another host painlessly, whereas if Weebly's service goes downhill you will find it very difficult to export and rehome your content while preserving your URL's.
I can never remember if you also sell your own services as a Wordpress expert.
Hey ho.
Here's a link that seems to summarize the pros and cons quite well.
Yes I do, but I do it for free (or low-cost) for friends far more often than I do paid work! I just finished making the site for Jodah and his creative writing friends.
That article gives a fair comparison and I wouldn't argue with it. However, I come back to the question - what will you do if Weebly closes down? What will you do if Weebly increases its fees again?
With Wordpress, your website is easily transferable to another host and you can continue with business as usual, with only an hour or two of downtime. You'll keep all your URLs, all your comments, all your images, all your links. With Weebly, you can use the RSS feed to transfer your posts but you'll lose all your images and your comments, and your URL's will probably change which means you'll lose all your 'link juice'.
If you're happy to say "hey ho" and just start again somewhere else, then it's not an issue. If (like MakingaMark) you're trying to build traffic and earn income, then having to start from scratch elsewhere would be a disaster.
I don't get the point
I can copy my site really easily and I'd also keep all my URLs and links. (My domain name registration is entirely separate - with another provider - to my weebly subscription)
What's the problem?
Things may have changed at Weebly since I tried it. At that time, it wasn't possible to export the site and import it into another website software, because the Weebly website builder is unique to Weebly. So if you wanted to move everything - not just the pages but also your menus, images, all the comments you've received, tags etc etc - then you'd have to do it piecemeal (which would be a big job for a large site). You might also have to tinker with the permalink structure to get it to match the one on Weebly.
Whereas with Wordpress you sign up with your new host, tell them where your site is currently hosted, and they will usually move the site for you overnight.
But I determine the permalink structure - in its entirety.
Comments are also not an issue. Pages also don't have comments - only the blog posts. I deal with queries offline.
I think maybe you need to go and recheck Weebly before counselling against it.
Did you read the link in Mark's post? I agree with the assessment in that article. Weebly works fine and if you prefer it, you're welcome to use it.
I guess I'm just averse to trusting my content to any single provider any more, after having written on so many sites that have closed down! Whereas with Wordpress, I can use the software forever - even if the company closes down, it just means no more upgrades, it doesn't mean my sites will stop working. And I don't have to worry about my hosting company going bankrupt or getting taken over by a shonky outfit - I can move my content as often as I like with very little effort (and it's automatically backed up once a week so I've got a recovery copy if my host disappears without notice).
I value that independence, but that's me.
What do you mean that Google does not index free sites? The blogs on Blogger are indexed by Google, unless you meant something else.
Some time ago, Weebly made the decision to no-index blogs created on its free service. If you want your blog on Weebly to be indexed, you have to pay.
Excuse me, but in that case, screw Weebly! I mean seriously.
Well, it illustrates why I chose to go self-hosted instead of trusting a provider like Weebly or even Blogger. You never know when they might start charging - and once they start charging, how much the price could escalate. I'm sure the people who had Geocities or Knol blogs never thought of the fact they could close down one day.
It just means you can pay for using Wordpress or you can pay for using Weebly or you use Blogger for free
@ LuisEGonzalez - Do NOT copy to Word. Not unless you copy somewhere else as well. Word loads your content with lots of unnecessary code - which other html sites won't like.
My personal favourite for fast saves is Evernote. Try it and you'll see why.
Here is a good hub about how to copy your Hubpage articles without all of the embedded stuff. … e-Articles
Thanks. Had not thought of that
What about the HubPages Twitter and Pinterest accounts, don't they promote hubs?
HubPages has approximately 14k followers on Twitter. Twitter has approximately 1.3 billion users, of which 65 million are US users. If you take just US users, HubPages followers would potentially represent just .0215% of them. That's not much reach.
...which is why efficient use of hashtags would help spread tweets to a wider audience of non-followers. Personally however, I find very few people seem to click on links in tweets even though they may re-tweet or like. I've often had tweets with over 20, 000 impressions without a link follow. Pinterest seems to be a better source of traffic.
As with everything people are more likely to retweet and click the link if it has an image attached
+1 on that. It's surprising how many Twitter accounts seem to broadcast a constant stream of boring text.
There are thousands of useless Twitter accounts set up by bloggers purely to auto-tweet their posts. Those bloggers may seem to have a decent following, because what they did when they joined Twitter was to look for members with the same interests, and follow them so they could get followed in return (there are even programs to help you do that). But in reality, they never look at anyone else's feeds and may never log in to Twitter at all.
I'll be honest, I have a couple of Twitter accounts like that, because that's what we were all advised to do years ago. I should do something about it but can't remember my logins! Twitter could easily clean up a lot of the dross by suspending accounts that haven't been logged into for a while.
I agree - Twitter only really works if you use it properly and that includes logging in and e.g. writing tweets which don't have a link and retweeting other people's relevant tweets for your topic area
What will I do if Weebly closes down?
Oh heck, I don't know Marisa. I have stopped hoping to make even a few hundred dollars a month from it - that was never my game and the last year of playing with Weebly has proven that. So I would not lose much if they disappeared.
What it has enabled me to do is experiment fairly easily with layouts, ideas, and attempts at sales and income. And prove to myself that I can't do commercial. Weebly is my hobby thing - an honest place for content which gradually becomes more visual and less written.
If they closed down I suppose they might sell on the subscriptions and things would just carry on. Or maybe give some sort of warning so I could copy out anything worth keeping. Maybe I'll do a back up sometime.
If they increase their fees... well that is pretty much guaranteed. No one reduces their costs. At present I cover their costs plus a bit spare. My guess is my income will rise sufficiently to cover any costs they think they can get away with throwing at me. It is not an issue.
To answer a question you didn't ask I think the content market is doomed. If major media players cannot survive on the internet - such as Yahoo for goodness sakes and there are many others - then the monetary options for minor content providers, especially in the 'humour' or 'creative' areas are especially poor. It seems to be a race to the bottom apart from a few stand out winners such as FaceBook (for now).
So arguably - nowhere is safe.
If it's just a hobby thing, then Weebly is absolutely fine. In fact the reason I tried Weebly was that I used to recommend the free version of Weebly to all hobbyists, and eventually I was asked to set up a blog on Weebly for someone - which is when I realised the problem of transferability.
The other issue now is cost, since the free version is not indexed. $8 a month is not much, but it's still more expensive than your own hosting. If you're only earning pennies, then the difference between $50 a year and $96 a year becomes significant!
On Weebly you're paying extra for the ease of use. If you can't cope with the extra learning curve of using Wordpress, then that's fine - but unless you are really really technophobic (which I know some creative people are), then it's not actually that hard.
You're right, nowhere is safe, That's why I like to be sure that I have full control of my content and can painlessly move it anywhere I like, any time I like. The internet is a hobby for me too, now - if I had to muck about copying and pasting pages, I probably wouldn't even bother reconstructing my websites.
I think you forgot the cost of buying a decent theme!
Buying a domain name is of course identical for both.
My point is that most people want to focus on their content and not on the technical side of things. For those who like things nice and simple and easy and above all FUNCTIONAL then I think the hosted webware option is one worth looking at.
However if you don't mind being on your own and wasting a lot of time when things go wrong by all means look at those solutions which involve more independence........
The bit I've never understood (especially given the fact that HubPages was set up by techie web people) is HP HQ don't offer the HubPages webware as a website with an option a pages within the website i.e. everybody is on a completely separate domain name and creating a genuinely independent niche site - and HP Q then gets its revenue streams from
EITHER adverts on the sites of people who use the webware to create their own sites
OR subscriptions to use advert free webware
Renewed this morning for $96 for TWO years including taxes. My minimal Adsense will cover that.
Re technophobe - well spotted! I am in the process of finishing a career in IT which I have grown to hate. As my creative side has emerged I find all IT things to be almost painful. The absolute last thing I want to do is go anywhere near code, experts, gurus, consultants, systems, processes... I'll stop.
All I need, and I appreciate it is different for some, is a basic navigation system (menu), title, text, image and spacer. Especially as mobile takes over the world all the rest of the fripperies are simply time-consuming and annoying.
I have a little point to make about niches. There are hobbyists out there, some like me, who are not surrounding their content with adverts and all the other stuff. They do it for fun, love, freedom. The HP 'niches' will be competing with people who can outbid them in terms of content to advertising relationship.
That's the race to the bottom.
The HubPages niche site are not niches - as MakingaMark pointed out, they are categories.
Oh OK. Not sure why they bothered then.
It worries me too. When they first announced the niche idea, I thought that's what they really meant. A niche site can cover a broad range of subtopics and that's fine, but they seem to be grouping topics that aren't that closely related. You'd think they'd be aware of the potential problems with that, considering their criteria for what's related in Amazon capsules.
All they're doing is breaking up the existing site into its categories and shaving off little bits and leaving out quite a lot of existing content.
I'm at a loss as to why they think this is a bright idea - it's certainly NOT about introducing a number of niche sites in the sense that Google recognises and of the type that does well elsewhere. | https://hubpages.com/community/forum/136061/how-are-hubpages-promoting-the-new-niche-sites | CC-MAIN-2017-39 | refinedweb | 3,682 | 78.79 |
On 01/30/2013 07:45 PM, Junio C Hamano wrote: > The third round. > > - Multi-valued variable transfer.hiderefs lists prefixes of ref > hierarchies to be hidden from the requests coming over the > network. > > - A configuration optionally allows uploadpack to accept fetch > requests for an object at the tip of a hidden ref. > > Elsewhere, we discussed "delaying ref advertisement" (aka "expand > refs"), but it is an orthogonal feature and this "hiding refs > completely from advertisement" series does not attempt to address. > > Patch #2 (simplify request validation), #4 (clarify the codeflow), > and #5 (use struct ref) are new. The are all long overdue clean-ups > for these codepaths. > > The last patch is an illustration why it wouldn't make sense to > optionally allow pushing into hidden refs, and not meant to be part > of the series proper. > > For those who missed it, earlier rounds are at: > > >
Advertising: * I didn't see a response to Peff's convincing arguments that this should be a client-side feature rather than a server-side feature [1]. * I didn't see an answer to Duy's question [2] about what is different between the proposed feature and gitnamespaces. * I didn't see a response to my worries that this feature could be abused [3]. I also think that the feature is poorly designed. For example: * Why should a repository have exactly one setting for what refs should be hidden? Wouldn't it make more sense to allow multiple "views" to be defined?: [view "official"] hiderefs = refs/pull hiderefs = refs/heads/??/* [view "pu"] hiderefs = refs/pull [view "current"] hiderefs = refs/tags/releases with the view perhaps selected via a server-side environment variable? This would allow multiple views to be published via different URLs but referring to the same git repository. * Is it enough to support only reference exclusion (as opposed to exclusion and inclusion rules)? Is it enough to support only reference selection by hierarchy (for example, how would you hide contributed branches from your repo)? Can your configuration scheme be expanded in a backwards-compatible way if these or other extensions are added later? * Why should this feature only be available remotely? It would be handy to clone everything but usually only see some subset of references in my daily work: "GIT_VIEW=official gitk --all &". Or to hide some remote branches most of the time without having to remove them from my repo: [view "brief"] refs = refs refs = !refs/remotes refs = refs/remotes/origin refs = refs/remotes/my-boss I think there are still more questions than answers about this feature and FWIW vote -1 on merging it to next at this time. Michael [1] [2] [3] -- Michael Haggerty mhag...@alum.mit.edu -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at | https://www.mail-archive.com/git@vger.kernel.org/msg17484.html | CC-MAIN-2016-44 | refinedweb | 474 | 54.93 |
A few days ago Kurt Cagle posted a blog entitled “Where is XML Going”. He lists a number technologies and trends of interest in the XML development community. There is nothing in his post I would disagree with (well… I am always a bit cautious when RDF is presented as part of XML; this is [...]
03 Mar 2007 by Ivan Herman's blog
Back [...]
25 Feb 2007 by Ivan Herman's blog; [...]
25 Feb 2007 by Ivan Herman's blog [...]
13 Feb 2007 by Ivan Herman's blog [...]
09 Feb 2007 by Ivan Herman's blog
Social standards and coding fugues
I got Cryptonomicon for Christmas; chalk one up for Amazon wish-lists. It walks the line between geek culture and popular culture in a way that makes me want people close to me to read it so they'll understand me a little better. This bit from p. 819 struck a chord...
nerdisim. And so he asks the above question as nothing more than a perfunctory guesture, the subtext being I wish you would go away but minimal standards of social decency dictate that I should say something.
In other news, Advogato does foaf, the Semantic Web social networking standard. Rock on, robogato!
09 Feb 2007 by Advogato blog for connolly
Several times recently I’ve needed to explain how I add gps information to my photos. I thought it would help to document it here. I’m not saying this is the best way to do things, but it seems to work reasonably well. If your browser window isn’t wide enough to show the right side of [...]
06 Feb 2007 by ishida >> blog.
25 Jan 2007 by connolly's blog
Chris Bizer and friends have recently announced their dbpedia site, which provides a mapping of the structural content of Wikipedia in RDF. For example, the categorization data of the Wikipedia entry on the Indian writer Amitav Ghosh can be seen as: raw RDF/XML, via a Sparql interface via a simple HTML dump of the same data, or [...]
24 Jan 2007 by Ivan Herman's blog
Roman photo, sur les traces d'Agnes.
14 Jan 2007 by Mes deux neurones
I just blogged elsewhere on BibSonomy, an alternative to del.icio.us that also includes bibliographical references. The core terminology used by the system (for bibliographical information) is based on BibTeX but entries can also be dumped to other formats. See, for example, a portion of my references in BibTeX or RDF. However… which RDF terminology
A new page has just been added to ESW Wiki: list of converters to RDF. Clearly necessary and useful… and having it on the Wiki makes it possible to keep it up-to-date more easily! B.t.w., the SWEO group will create a separate task force on Resource Gathering which will look at pages like this one. Still [...]
09 Jan 2007 by Ivan Herman's blog
I used blosxom for a long time as a blogging software. It was quite all right but, I must admit, I got a little bit bored to keep it up myself if I had to do any change. So I decided to become lazy and switch to WordPress… I tried to do my best to [...]
07 Jan 2007 by Ivan Herman's blog
A review of my life in 2006, or at least the bits that I want to share.
.
Exchange 2000 Server requires a file name in the Content-type header. Q12: How does Exchange handle attachments? Microsoft Article 836555
I bet you can guess the rest of the story, but I hope to write it up later today.
05 Jan 2007 by Advogato blog for connolly:
All the files are in the swap/test/reason directory: witch.n3, witch-goal.n3, witch-pf.n3, witch-pf.txt. Enjoy.
03 Jan 2007 by connolly's blog
12 avril 2000 - 31 décembre 2006, carnet Web Karl
Vous pouvez enlever le feed de vos agrégateur, il ne sera plus mis à jour. Merci de m'avoir lu jusque là. Les archives restent en lignes.
31 Dec 2006 by Karl - Le carnet Web
Il y a quelques années, le 11 décembre 2000, dans un billet « HTML et les premiers navigateurs » sur Karl & Cow - The Boring Weblog qui était assez mal écrit sur les technologies Web et le HTML, j'insistais sur les conséquences de nos toutes premières décisions. Et je concluais par « Les premières fois sont très importantes. »
代官山, 日本
Il y a toujours ce magnifique sentiment lorsque l'on explore de nouveaux territoires, cette excitation de chaque instant, cette envie permanente et folle de créer. C'est une belle aventure, un parfum de chèvrefeuille invitant à la libre pensée. La trajectoire du papillon, le bonheur unique du plaisir, le sourire au bout des doigts, les mots sont naïfs, les phrases sont jeunes.
Les choses se raffinent, se patinent et prennent le charme de l'ancien. C'est un vieux fauteuil écossais en cuir au coin du feu, c'est un chemin qui nous fait sourire car on y trouve du confort, c'est le parfum d'une table en bois couverte de cire d'abeille. La maturité nous apporte son lot de rides, son assurance tranquille et la tendresse de la maîtrise. Qu'il est doux cet instant de sérénité.
Être ébloui, s'extasier du quotidien, vivre passionnément le banal est le feu qui m'illumine. L'exploration des horizons lointains jamais ne cesse. La découverte est une invitation.
Du bonheur qui n'est que de l'anxiété différée. Du bonheur bleuté, d'une insubordination admirable, qui s'élance du plaisir, pulvérise le présent et toutes ses instances.
Feuillets d'Hypnos, 145, René Char
恵比寿, 日本
rêverie
30 Dec 2006 by Karl - Le carnet.
23 Dec 2006 by connolly's blog
appscript and office automation
My wife does office work for a local professional and whenever I see her doing work that I know the computer could do for her, I chip in. The end-of-the-month scramble is a clear case: they take client reports, print them out and then manually sort them by officer and fax them out.
Surely I could do better with faxaway, I thought. The only question was: since the reports are in MS Word and the database is in FileMaker Pro, all on a Mac laptop, how much would I have to sell my soul to Apple and Microsoft in the process?
appscript let me drive the process from python. I did quite a bit of HyperTalk programming, but somehow I'm still a bit mystified by AppleScript: which are the language keywords and which are the application vocabulary? The FileMakerAppscriptingOverview made it trivial to crib bits like:
fm = app("FileMaker Pro") if not fm.databases[db].exists(): fm.open(FSSpec(path % db)) return fm.databases[db]
FSSPec is deprecated in the Carbon docs, but I never did figure out a replacement.
appscript's integration of AppleScript references into python with its and con is particularly cute, but I pulled a bit of hair out before I figured out how to use it:
def officerFax(db, oName, cName): # hmm... I'm not sure why this str() is necessary... officers = db.tables['officers'].records[ its.fields['name'].cellValue == str(oName)]
If FileMaker has a way to use real SQL, I can't find it. Plus, we're running a PowerPC version on an intel MacBook with only 0.5GB of RAM. Emulating FileMaker and MS Word is using a lot of RAM, I suspect. I looked into open source alternatives and found that OpenOffice's Base looks quite capable, and I'm sure oowriter would do the job as an MS Word replacement. I hope the python-uno bridge works on OS X so that I can switch the whole operation over one of these moths.
I did pay a price for not doing it The Apple Way. Technical Q&A QA1018 Using AppleScript to send an email with an attachment shows exactly how to attach a report to a mail message and send it to faxaway. I was able to create and address a mail message from python/appscript, but making the attachment stumped me. After verifying that the AppleScript example does work as advertised, I gave up and wrote a separate mailfaxes.py program that uses python's email and smtplib modules and skips Mail.app altogether. I had to be a little careful since the laptop runs python2.3 and the email modules have been rearranged a bit in python 2.4 and 2.5, but it was reasonably straightforward.
Driving MS Word was, predicably, even klunkier:
TMP="fax_job.htm" def asHTML(w, dirpath, fname): """save current doc as HTML """ w.do_Visual_Basic('ActiveDocument.SaveAs FileName:="%s",' ' FileFormat:= wdFormatHTML,' ' HTMLDisplayOnlyOutput:=True' % (TMP,))
Office X has an AppleScript interface, but it's not as rich as the Visual Basic API. I got Word to save as HTML (for processing with BeautifulSoup) but I never did figure out how to tell MS Word which directory to put it in. I wrote a posix2mac() routine to convert /posix/paths to ::mac:paths as used in AppleScript but that didn't help; I ended up with a hard-coded kludge.
Switching syntaxes with do_Visual_Basic is a little bit painful, but when it goes bad the diagnostics are pretty good. "ActivePrinter is read-only on the Macintosh," it said, where w.active_printer = p had just failed silently. The modern VB.NET PrintOut documentation isn't hard to find, but it's a little more tricky to find the 2002 PrintOut docs that are more relevant. I never did get PrintToFile working, nor did I find a way to script the PDF option in Apple's print dialogs. Thank goodness for the Appscript, Word and PDF clue which pointed me to CUPS-PDF for Mac OS X. It worked as advertised, though writing code to wait for a new PDF document in ~/Desktop/cups-pdf/ was tricky; we sent a number of reports to the wrong place due to a timing bug.
The Python Bindings for Quartz 2D rock; composing fax cover pages couldn't be easier than this:
htmltxt = coverHTML(oName, fax, subject, pages) ctx.drawHTMLTextInRect( CG.CGDataProviderCreateWithString(htmltxt), pageRect.inset(72, 72))
and concatenating several PDFs into one was similarly straightforward. It doesn't hurt that faxing is Apple's example application.
For reference:
hh-fax2$ hg log --template '#rev#:#node|short# #date|shortdate# #desc|firstline|strip#\n' 11:7b497e5881d8 2006-12-07 fixed nasty timing bug with PDF virtual printer 10:5fbd62cf7025 2006-12-07 fixed SMTP details 9:adbc7966d42d 2006-12-07 back to faxaway 8:89f2688b85fc 2006-12-07 smtp host arg 7:eb4eba0ed22c 2006-12-07 mailfaxes.py starting to work 6:c317d0cb9956 2006-12-07 prepares one PDF doc per officer 5:fe8a79a7ed9f 2006-12-06 faxjob.py iterates over reports and looks up fax numbers 4:52f42112c287 2006-12-06 better diagnostics 3:862514804543 2006-12-04 officer update mostly working 2:61dfc88ab652 2006-12-04 connecting to FM from py works 1:a1f813e53e79 2006-12-02 HTML/CSS page break test 0:aa2d0cc8a7e9 2006-12-02 save as html, doc export working
09 Dec 2006 by Advogato blog for connolly
I installed the latest version of Opera Mini on my Treo 650 PDA, inspired by all the pretty good feedback I read here and there; unfortunately, I never got it to run properly, as it seems to insist on crashing (and on making my palm reboot) as soon as I'm ...
30 Nov 2006 by Don't call me DOM
16 Nov 2006 by connolly's blog
Mike ran a few Web sites through the Mobile Web Best Practices checker, and noted that: Here’s a few things to pay attention to: checking Nokia.mobi yields 50 errors Vodafone.mobi has 85 the .mobi site for dotMobi itself has 5 errors the output of Google’s mobile transcoder yields about 18 per page the validator seems to ...
13 Nov 2006 by Don't call me DOM
I will be presenting the Mobile Web Best Practices twice in the upcoming few days: during the MWI Seminar in Paris on November 16; I'll have 20 minutes to give an overview of the principles behind the Best Practices, and where we're headed with mobileOK next Monday at 11am CET, I'll be ...
13 Nov 2006 by Don't call me DOM:
And while the OWL errata do include a repeated sentence and a missing word, there have been no substantive problems reported in the normative specifications.
How did we do that? The OWL deliverables include:.
11 Nov 2006 by connolly's blog
This is a test post, to see what happens when I add a link to a video I uploaded to Google video. The video is of Le Thoronet church, in the south of France. Beautiful simple architecture, with haunting audio. Hmm. Could be worse, but it loses a lot of quality compared [...]
10 Nov 2006 by ishida >> blog
In the vast cyberspace of the Web galaxy, a new Planet is born: Planet Mobile Web weighs 20 blog feeds (and growing), seems to be pretty active already, and hopefully has a bright future before her. I'm pretty excited this has come to fruition; I think it will be a useful ...
09 Nov 2006 by Don't call me DOM
New picker I finally got around to studying the Tibetan script. To help with that I created a Tibetan picker. This picker includes all the characters in the Unicode Tibetan block. The default shows all characters as images due to the rarity of Tibetan fonts. Consonants are mostly in a typical articulatory arrangement, with vowels below, and [...]
06 Nov 2006 by ishida >> blog
The data displayed here comes from the following sources: Karl Dom Yves Dean Olivier DanC DanC (DIG) TimBL Danny Steven Ivan Ivan Richard
News aggregation available as an RSS feed.
Unfortunately due to the nature of the content we are unable to guarantee this page is valid XHTML. Some portions are Copyright W3C 2005.
Information on POAK including configuration and source code - Dean Jackson. | http://www.w3.org/2005/06/poak/team-lite.html | crawl-002 | refinedweb | 2,364 | 70.43 |
Plano Metro Rotary Club’S Mardi Gras Casino Night – Youtube Casino ~ Free Demo Play
Selection of hors d’oeuvres Main courses including carvery 2 Course Garden Buffet All-You-Can-Eat Buffet Saratoga Casino Hotel. CA – Senior Benefits Specialist – San Manuel Casino Conduct and coordinate benefit education meetings i. e. , NEO, 401 k , Open Enrollment, wellness. Tragamonedas con bonus gratis sin descargar huuuge casino reviews Juega GRATIS a las mejores tragaperras y juegos de casino online de de. 6 hours ago — They escaped the foul air to play the slots inside the Hard Rock Hotel & Casino. Trejo, who uses supplemental oxygen due to breathing problems. Find all the online casinos owned, operated and managed by Digi Markets N. V. and learn more about online gambling sites associated with Digi Markets N. V. Computer casino slot games the Peugeot Partner, causing the referee to stop the new and unique to the collection all sorts of interesting new gameplay. Free Online Flash Casino – Free online casino bonus codes You’re able to opt for for you to guess utilizing poker chips and even attain. Platino Hotel & Casino 3 STARS. CL av. estrella sadhala, frente a pucmm, Santiago de los caballeros, Santiago de los caballeros, dominican republicView. Casino bar bern – Zrich casino baden, Casino beef week steam train rides you could management to profits and business capital want Zrich casino baden in. Trip would prove to see st augustine casino 258mi. Serrano buffet they have no government buildings. All st louis casino hotel activity on a relaxing atmosphere. Burswood Casino Perth, Western Australia Media Man Australia. Podívej se v Burswood saw a restaurant and modern amenities and a srovnání cen.
| You’d like to be able to win some so you could play for awhile, that was very. Hollywood casino buffet prices – 25 Years Online. Allsots Casino 15 online casinos that accept paysafecard J’ai beaucoup rit, bought five 10-pound bags of ice. The transfigured life which follows upon that inward renewal, 7 reels casino online with real money review protects the casino against fraud. Gambling age bahamas atlantis deals – 35 Years Online. thermal power in theme from the royal oasis needs a gambling age limit visa casino royale.
Play Free Spins Kaufmanns-Und No Deposit Bonus! – Roulette Casino ~ CashBack
Had to gamble x initial deposit £ before converting from bonus balance BetMGM Bonus Code “LINEUPS” – $, + $ Casino and Sportsbook May. Graton Hotel & Casino. 630 Park Ct, Rohnert Park. Open 24 hours 5306 C. Old Redwood Highway, Petaluma. Closed. Store closed. In store. And btc games offers new players a vip no deposit 30 free spins, plus 100%. Join the fun at bitstarz casino and get your hands on up to 200 free. A detailed review of Emerald Casino – Curacao Marriott Beach Resort, they have 12 table games and 135 slot machines and are located at By Alex H. $5 Minimum Deposit Casino in Australia — The minimum deposit amount of the majority of welcome offers in Australia is around $10 or even $20. Royal ace casino $200 no deposit bonus codes 2021 Com u 1 l 8 ul x wul x user coibot editsummary id 37009611 lang en wikidomain w namespace pagename ha. . RIVER RAILWAY -13. 2467 131. 1117 153 23000 ADELAIDE WEST TERRACE -34. 9333 12022 CASHMERE DOWNS -28. 9706 119. 5669 450 58063 CASINO AIRPORT -28. 8778. Now, it is expected that the Casino at Royale will see the Adopted the name ‘Le Chiffre’ ‘since I am only a number on a passport’. Cheap Parking Melbourne – Secure Parking. The Crown casino in touch with Crown Casino’s activities are calculated, Year-on-Year Overall Still Lagging Poker. Chiropractors & Spinal Adjustment Services in LISMORE, 2480 NSW. Found: 16 Results Duffy James V. 101 Uralba Street. LISMORE NSW 2480. 02 6622 2800.
| Un problème avec un casino, Dénnoncez le dans Avis Arnaques des Casinos en ligne. du casino live je voulais avoir si c’est vraiment réel oui ou non ? •Immigration: as a convict 18 JUL 1831 Sydney New South Wales Aust Bega, New South Wales died 18 Sep 1952, Casino, New South Wales. Stolen casino bmx. Paradise casino yuma. It directly on a week. It was the public. Great attractive feature of other events. Admiral casino non c’è nome solo una scritta generica ferrero, Free no download slots with bonus police were called to the scene of a traffic accident. The #1 finance app in the App Store. For example, at Gday Casino you Slots spin the reels 50 times on the Aloha slot machine games. Play slot machines for free without registration. Mirage slot machines. Online casino with real money no deposit bonus. Are bitcoin casinos safe to play?
Bonus Casino Enfield Ct – Secret Party Slot – Near Me
He new agreement will see Funfair, which operates over 25 casinos across Ireland, utilise Aspire Global’s gateway AspireCore Platform PAM. The flexible and. Read players own experiences with Casino Empire no deposit bonus, for the bonuses remember that the T’s & C’s are super important when. CARDING List of 10,000 Cardable Websites. rtf – Cardable Casino Sites 10bet. com 24hbet. com 5dimes. com admiralbet. com allstar. com alpenland-online. at. The best 41 synonyms for gambler, including: highroller, risk taker, punter. associatedwords: decoy, gamester, numbers runner, darer, risker, operator. Rockstar Games releases a new set of bonuses for Grand Theft Auto Online this week, with details on how players can earn and enjoy them. Big Fish Casino for Android cheats – Cheating Dome has all the latest von A bis Z mal eben kurz in diesem Land Maß diesem Gremium bin. Learn how to find the best instant banking casino in New ZealandThanks to the good old internet, the best games of all time. December 2003, the Government’s Mini Budget of 16 April 2004, The Casino to Murwillumbah rail line is a single gauge track of. For GREAT bonuses and FREE spins on trusted casinos: wins,casino games,casino grounds,big slot. This article first appeared in the June 2021 issue of WGM. The recently renovated Jai Alai casino. Play • Gaming insights • Gaming.
| Sale Slot e bar non offrono nulla di tutto ciò, daily promotions. A big win will be returned to you for the maximum amount that you wish.
Online Casino In El Paso – Theatre Arts Tulsa Slot ~ Play Online
Cashman casino vegas slot machines 2m freeon first deposit, they were supposed to put cash back emu casino manic monday · free slot machine games 77777. . golden fall spring hom billh water text xw k sdct itl dir vti inf boadmin cgi spelled reformulate phrases indexes casino megan uniforms prepositions. Jane Lynch 2Jane Lynch K-9 Casino Night 1 · All You Need · Bye Bye Doggy Aches · Bye Bye Pup Worries · Inverted Ceramic Dog Bowl Set in Berry Red. Best sites for online casino wagering: 40x. brimbank pokies policy combs concert: ref vieedge0411 b brown pelicans. 1 usdt 7777 live casino, online bitcoin casino win real money free. Quelle est l’adresse de petit casino ? petit casino est situé au 17 pl gén de gaulle. 13 hours ago — Not just the Casino Estoril, but casinos around the world, and more specifically, the different kinds of games that can be played. Doubledown casino promo codes by pink eye – Any Currency – Only for our on the latest one will be used any of chips play free credit rm10 visit betfair? Not all tribes currently participate in the responsible gambling/self-exclusion Chickasaw Nation Chisholm Trail Casino, 7807 N. Hwy 81, Duncan, OK 73533.
| Get sold price history for this house & median property prices for Casino, $290k. median sale price. CURRENT. Casino median sale price trends last 10. Volatility of slots. Not only that but you can play them for free before playing them for real money, fun. The most wonderful innovation of the latest. Holmes hit a $175K Divine Fortune slot jackpot on Stars Casino “The site has some of the best games, the best running software. Discover the luxury, comfort and privilege of staying in one of Cactus Petes Casino Resort’s newly-renovated rooms. tower king hotel room.
Free Spin Gambling Bot Seller – Play In Online Casinos – Bright Hawk Slot Machine – Review 2021
Don’t see what you’re looking for? See all available properties in Genting Casino. View all properties. Lowest nightly price found within the past 24 hours. Now that I’m 68, know when to run. Fairway casino interrogating Casino croydon we wrote an article on the process, 2021. You can remember the losing. Bets to avoid in otherwise safe casino gambling games. A has the exposed tiles as, children can use their bodies in self-directed play.
| Blackpool is set to under go massive change in the near future as the big American Casino Corporations move in.
Play Quick Hit Slots – Free Bonus Coins – 17Th July 2021 – Social… Casino – Play Online
Best casino games for android bluetooth. Best offline casino games for android bluetooth Netent slots casino uk gambling games is a set their software. When it comes to gambling, cashpot casino no deposit bonus and German players The maximum cash reward on offer is 1,000x multiplier, you can restore it. Download and install Offline Vegas Casino Slots:Free Slot Machines Game in PC and you can install Offline Vegas Casino Slots:Free Slot. 15 Ships in the Celebrity Cruises fleet Full of thrills and free of smoke, Celebrity Beyond’s Vegas-style casino features plenty of gaming fun in a. CASINO EDGE OUT CASUARINA BEACH IN CLOSE CONTEST · Eloise Le Gros – June 23, 2021. 12Page 1 of 2. Avatars by Sterling Adventures. The sequel to the original Foxin Wins slot, please visit our Privacy Policy. Although Americans are deemed adults at the age of 18, but you should remember that. 11 minutes ago — While standard blackjack, roulette and other table games Slot free 888 casino net, casinodeutschlandkostenlos monsters from an ‘s. Visit PayScale to research Crown Casino salaries, bonuses, reviews, With dozens of no deposit bonus casinos, alleyways or. World’s premiere gaming said casinos and limited social gatherings and wear masks and he said. Some running show. Harrah s las vegas casino, new keys were. Two of them were the Leica M9-P ‘Edition Hermès’ and Leica M9-P Then a quick visit to Cercle d’Or district around Place du Casino to do. Casino Night Fundraiser Hosted By Janice’s Women’s Center. Event starts on Saturday, 30 October 2021 and happening at 4302 E Ray Rd, Phoenix, AZ.
| Risking real money. Food service at online casino bonuses, fortune. One major cards. Play with our ubledown codes for bingo games and regulations. No deposit. Fox Wood Casino Games to download now: no deposit bonus slots 99 slots bonus codes he concluded the game was not paying her as it. Twin spin megaways slot / Restaurant Crown Casino / Free blackjack card game Hausgemachte Kuchen und Torten, leckeres Eis oder warme Waffeln können auf. Many renowned online casinos offer free spins to players who would rewards with lavish bonuses and can be played with live dealers who.
Free Demo Play Hard Rock Classic Casino – Double Win In The – Learn4Results Casino ~ Play Online
Non-Stop Casino Excitement and Winning Action, west of loathing poker y las estamos acompañando para cumplir sus metas profesionales y. Boyd Gaming adds cleaning, safety protocols as 9 casinos reopen Thursday. Redeem online rewards points at any MGM Several progressive jackpot slots Excellent mobile app Promotions keep coming even after sign up. Eurobet casino speaking of the Surface Connect port, and you feel intrigued. free casino without downloading online investing in a mobile app can be a. Big hit at the casino in 1943, players need to line up at least three Bonus symbols. For this reason, but I have a certain expectation of my. Roller coaster fruit machine for sale ,virtual casino no deposit bonus codes 2021,the best correct score site in the world,casino rizk bonus code,free $50. Crown casino perth accommodation nzxy. . royal ace casino 25 free spinsAn Ardent Group subsidiary, Gaming1 currently operates over 20 online gaming brands. Brookside star’s Mersey Ferry hotel set for approval despite coronavirus The ultimate night out on the Mersey – Liverpool’s Vegas Casino Cruise is. “But how come we never talk about angry White men w/guns? Windows are broken at the Mandalay Bay resort and casino in Las Vegas on Oct. How to Become a Casino Dealer. control the pace of the game, keep a mental record of all the bets so that the winner doesn’t surprise you. The Wild Horse Pass Hotel & Casino is located in Chandler, Arizona, 12 miles south of and 12,000 square feet of meeting space, along with a variety of. Unsurprisingly, they don’t offer any of Evolution’s European tailored language roulette tables. But they do offer baccarat, with a live Italian dealer in the. Sam runs Lickety Splitz in name only because, as a felon, Ruth cannot be associated with Marty during state scrutiny of the casino application. Buddy’s health.
| Odawa Casino Petoskey Michigan – What casino payouts are, una domanda generica da porre o un dubbio inerente alle transazioni o alla. 【 Joseph】over under jets game · 【 Ingram】stephen nover picks · 【 Berger】rivers casino website · 【 Donahue】weekend football predictions tips · 【 Hugo】nba. 14 hotels — Mindil Beach Casino and Resort – Formerly Skycity Darwin Offering an outdoor pool and spa centre, Frogs-Hollow Backpackers is situated in.
Play New Online Casino No Deposit Bonus Uk – How To Play And Win Casino – Free Demo Play
This application is latest update of the sky slots will progress through four. Be used to strictly enforced security must remain high quality, we apologize for. By N Barberis · 2021 · Cited by 179 — distribution generated by his planned gambling strategy. 0, the casino offers the agent a 50:50 bet to win or lose a fixed amount $h. If the agent turns. Announced that capacity at all venues including Optus Stadium and RAC Arena would music events, galleries, the casino and Perth Zoo. Conservative hoaxers face $5. 1M fine for election robocalls Concerts and promotions coming to Soaring Eagle Casino this fall! eightWest / 6 hours ago. Low-Cost tickets are now as if bonus on any. Save time is dedicated to mmmmm, htc windows phone that flies at a single market. Flixbus’ goal of people have. Casino Furniture Removals Thanks Mark We dont have a run from the Gold Coast to the Northern Rivers so for us to give you a price it was a special trip. Thunderbolt Casino Bonuses. Code: BIGTHUNDER. Thunderbolt Casino: 150% up to R 2500. 1. Match Deposit Bonus. Terminated. Terminated. Terminated. He Yaozu added a few words Boss, you must not think that Zhaos Casino is a cbd cream for sale and no one thought that the latter would best e cig for. Grab up and the gold casino dozen spins casino eurofortune casino elf slots. Beginner friendly guest minimum cash out in times per day, and what f. Don Johnson won nearly $6 million playing blackjack in one night, hoodie had struck it rich, had beaten the casinos black-and-blue. We hope this will help you to understand Thai better. Here is the translation and the Thai word for casino: บ่อนคาสิโน Edit · Casino in all languages. Address: 8001 E Cedar Hills Road, where they can earn money the fun way. Biloxi casino vacation packages most of us have some works of writing or film. Casino game x demographic map tx casino in boonville missouri united states Residents of citycenter, and moon casino honolulu zip codes casino game real. Microgaming is among the highly recognized online casino game providers, slots signup bonus Ignition isn’t doing anything wrong by serving. The Lucky Bird Casino App is a multi-brand online entertainment resource where players with Android, iOS and Windows Phone machines of all configurations. Betvictor casino people may certainly play with their favourite games in the The Q, but statistics are everything in casino betting. CASINOS in Cambodia could regain three-fifths of the sector’s pre-pandemic revenue this year, led by the VIP segment, a recent report has.
| Great savings on hotels in Geelong, Australia online. Good availability and great rates. Hotels near Crown Casino Melbourne. Hotels close to a popular. Aug 1998. #. J. Litoria caerulea. Casino, NSW. July1996. *. A 96/692. Brisbane, Qld Bat Cave. 53160 683950. Nullum SF. Nc4. McNamaras. 53190 684030.
Free Spin Adelaide Casino Membership | Try The New Slot Machines For Slot Machine – Play Online
State prosecutor opposes parole of bank embezzler Etti Alon He visited almost every casino in Israel and many abroad, and owed them vast. Alf casino bonus codes,atp finals betting odds,goalliveprediction,patriots 2021 at 12:03pm PDTAlso Read Alaya F Recalls Her Parents Reaction To The. Drive from downtown L. A. to Downey and you might see views similar in Hawaiian Gardens and Bell Gardens aren’t actually casinos at all. Wind Creek Bethlehem A 28-year-old Monroe County man is facing charges Brandon L. Pearsall-McNealy, of East Stroudsburg, met a person at the casino on. Have fun playing the instant-win games, aristocrat pokies online catch plenty of working in a casino, each of the X dice having F faces.
| World Free Casino Games Online promotions on free casino bonuses If you dream of earning money, top game slots engaging. Play slot machines for free without registration. Which slot machines have the best odds. Online casino with real money no deposit bonus.
Play Online Casino Online Page Celtic Casino Slot Machine –
New partnership sees jackpot. com launch Playtech Casino and Live Since its launch in 2021, Jackpot. com has become a world leader in the. Wealthy investors think it s one reason, no deposit bonuses, a few hurdles. Where you have just look no deposit starting june 2021 do release, las vegas slot.
| Glamorous Red Rock Casino Birthday Celebration – Revelry Event Designers. More information new year Backdrop DIY – DIY Holographic Balloon Backdrop. Sky casino adelaide this card shuffle can hold up to 4 decks at a time, the request, C. Therefore, play casino card games and D – play as a team. Mobile flamantis casino no deposit bonus online con bonus book of these brands. very the industry is also important to have visite g. Crown Casino en Melbourne: 3 opiniones y 2 fotos. Crown Casino Under investigation By NSW Regulator. Only Nevada now has a larger casino industry. Anzac Day. Free slot machines to download The gan. z online casino cehgme offers players 21 blackjack download moviePirates Plenty:We first heard of the new Pirates. Several different procedure to learn more than 20 free, poker market are now Mohegan sun online session will work with one site of other casino sites is. 14 hours ago — to work out some Poker Rtl7 cool and exclusive no deposit bonuses Net als RTL 4, RTL 5, RTL 8 en RTL Z, maakt de zender onderdeel. Pa online gambling it is a billiards-roulette game with billiard balls that the top prize of 50,000x the bet, elles peuvent pourtant être évitées. Enjoying free casino slots is one particular of the best gaming ordeals there is to have. They functionality a great deal like aged flash online.
Crown Casino Poker Tables : Editor’S Choice – Solactis. Chargeback Online Gambling | Licensed Online Casino List – Nail. Casino Royal Club Casinomeister Accredited – Bartosz. Casino Dunedin | Online Casino Games With Live Dealers – Abundant. Slot Machine Brick Bar Bangkok Cheap – Siddiq Alvi. Treasury Issues New Bank Secrecy Act Guidance For Casinos. Photos: Hamilton Princess Unveils Casino Plans – Bernews. Test Slot Games | 6 Online Casinos With The Highest Payout. Two Dead, Gunman Slain At Wisconsin Casino – Augusta. Casino Host Job Duties | Lotobc – Bravenet. Mgm Park Casino – Free Casino Bonus And No Deposit Bonus –. 24Vip Casino No Deposit Bonus【Wg】Puerto Rico Loteria. Buy Blackjack Tables – Fun Casino Nights. Limo Joe’S Casino Shuttle – Mapquest. Desert Diamond Casino & Entertainment Tv Commercials. Virgin Games Casino, Joo Casino Promo Codes, Poker Starz. Best Casino Pc Games – The Online Casino Mobil Bonuses In 2021. All Online Casinos That Accept Netellers – Riviera Fiduciary. Casino Victoria Cherry, Minsk | Destimap | Destinations On Map. Australia Ace Play Casino 2021 Review. Free Pokies Dragon Link | Online Casino No Deposit Bonuses. Casino Deposit Methods For Usa Players – Legal Gambling. Zuma Slot | Blueprint Gaming Exciting Online Slot. Prairie Band Casino And Resort – Banksia Partners. Lebanon Casino Mhanna Beirut See 102 Unbiased. Casino Fortuna – Book Binge. Maple Casino Review – Youtube. Parkwest Casino Lodi – Tile Floor Buffing. Review Of Arizona Charlie’S Boulder Casino Las Vegas – Huddle. I’D Rather Be At The Casino Windproof Headwrap Unisex Balaclava. Squirrel Warriors Slot By Gamesys ▷ Review July 2021. Parx Casino Sportsbook – Elevation Ministries. Codeshare Doubledown Casino. Free Non Expired Chips For Doubledown Casino 2021 – Austhetic. Casino Beach Boardwalk Pensacola Florida – Complete Turf. Bally Casino Slots Online Casino Dealer – Ibs Bremen. Casino Slots Games Pc | Free 3 Reel Slot Machine Online – Bonsabor. No Jobs At Ameristar Casinos In Dallas | Glassdoor. Best Online Casino Macau – Felix Competitions. The Legal And Reliable Online Casino Sites – Rit Parcel Courier. Fallsview Casino Resort And Casino Niagara Raise Ca. Ballys Casino Colombo Sri Lanka, Ballys Casino Ac To Ac Convention. Real Casino Slot Machines For Sale – Casino With Virtual Money To. Ron White Casino Nb | How To Play Online Casinos – Whitley. How To Win The Slots Machine At The Casino – Amigos. The Most Luxurious Casino-Resorts Around The World Perfect. Average Cost To Build A Casino – – Real Fert. Uber And Lyft- Including Discount Codes Transportation: Taxis. New Post Empire Casino – Kampala, Uganda – Iliper.Com. Austin Casino – Sushi Tokami
Casino Rewards Mega Moolah %Ec%9A%B0%Eb%A6%Ac%Ec%B9%B4%Ec%A7%80%Eb%85%B8
James Gold And The Mummy Riches Slots Mobile Grandwild
Scioto Downs Casino Columbus All Categories Of Slot
Big Rock Casino Bowl Casino Espanola Locale Online
Moncton Casino Event Schedule Foreign Legal Online Casinos
Grand Casino Bakery Cafe Culver City Yelp
Sportsbook Casino Philipe L Harrington Somatic Therapist
Top Best Online Casino Berve Lacantarida Com Carte
Pokies Carlton Rate Pokies Parlour Casino Professor Good
Free Demo Slots Online Casino Review And Opinions Bonuses
Which Casinos Offer Free Slots Play Free Ballymore Services
Clay Composite Poker Chips Used In Las Vegas And Chegg
Bet365 Casino Bonus Codethe New Years Eruption
Bitstarz Casino No Deposit Bonus Codes 2021 How To Tell When A
What Are The Best Casinos In Florida Szafa Gwiazd
Word Heaps Level 293 Casino Gamers Answers
Slot Machines At Turning Stone Casino Tom Ferr
Coral Deputy Manager Blew 7K Stolen From Bookies In Casino
Online Casino Slots Betvictor
Flamantis Casino Bonus Codes 2021 No Deposit Bonus 2021 | https://haitiliberte.com/advert/4-secure-online-casinos-with-faster-withdrawals-laurel-main/ | CC-MAIN-2021-43 | refinedweb | 3,776 | 66.33 |
This is an automated email from the git hooks/post-receive script. gregoa pushed a change to annotated tag upstream/2.4.2 in repository libmouse-perl.
at cb2821d (tag) tagging 549af4a71732c4a5db7b9c3f6b066423080d28ec (commit) replaces upstream/2.4.1 tagged by gregor herrmann on Sat May 30 22:12:28 2015 +0200 - Log ----------------------------------------------------------------- Upstream version 2.4.2 Brett (1): Resolve [rt.cpan.org #61613] Compile failed for version 0.71 on cygwin. Chris Prather (5): doc patch for lazy_build if you are gonna blame me, get the spelling correct Add dump method from Moose::Object into Mouse::Object set perl version to 5.008 and document 5.6.2 bugs in POD add minimum version for Test::More and Test::Exception so that we at least test the same standards as Moose Daisuke Maki (14): branch correctly just a simple XSLoader for now 024 fails, but successfully loads and uses the XS versions of Scalar::Util functions attempt to require MRO::Compat. If that fails, use our own oops, copied the wrong sub change location put a hack around in there don't attempt to require Scalar::Util if we're going this far trying to optimize check for has_default too reverting change: the correct answer is, I want parameterized types... I want it! properly commit the newly created parameterized type to the registry (cache!) Make coercion work for parameterized types oops, that used confess Daisuke Maki (lestrrat) (6): implement Maybe fix portability between Moose/Mouse's class_type move stuff from Meta::Attribute to Util::TypeConstraints, work with $_ and such Add a dummy TypeConstraint namespace so you can treat them as objects Export find_type_constraint look under %TYPE first Dann (3): suppress warnings when we use around and has "+..." use Data::Util to make modifier fast if Data::Util is installed refactored out fast method modifier as Class::Method::Modifiers::Fast and used Class::Method::Modifiers::Fast David Steinbrunner (3): typo fix typo fix typo fix FUJI Goro (gfx) (17): add failing tests for #17 disabled metaclass cache in Mouse::Meta::Role::Application (#17) Checking in changes prior to tagging of version 2.3.0. Merge pull request #35 from gfx/fix-for-blead-perl Checking in changes prior to tagging of version v2.4.0. Merge branch 'master' of github.com:gfx/p5-Mouse Checking in changes prior to tagging of version 2.4.1. Merge pull request #37 from kentfredric/master fix #38; avoid warnings introduced in perl 5.21.x update changes add a test file for #29 Merge pull request #43 from gfx/skip-test-if-thread-is-disabled close #39; avoid warnings in perl 5.21.x ignore 017_issue29.t temporarily (related to #29 and #42) fix #40, #41 update autogenerated files Checking in changes prior to tagging of version 2.4.2. Fuji Goro (7): XS(foo) must be external Remove debug messages because xsubpp problems have been resolved Resolve RT #70569: Prototype mismatch: sub Mouse::Util::get_linear_isa($;$) vs none at Mouse/Util.pm line 131 Ignore MYMETA.json Checking in changes prior to tagging of version 0.94. More tests Checking in changes prior to tagging of version 0.95. Fuji, Goro (269): Add RT57144.t, but it is not fixed yet... Workaround RT #57144, caused by Perl_call_sv()'s bug Checking in changes prior to tagging of version 0.57. PERL_CONTEXT has been chaned in 5.12 Fix mouse_call_sv_safe() again Checking in changes prior to tagging of version 0.58. Update Makefile.PL Disable a part of tests on 5.13.0 Improve error messages Fix a test Checking in changes prior to tagging of version 0.59. Update podspell.t Move overload stuff to XS Tidy and docs for meta type constraint class Tidy Make code simple Docs on Mouse::Util Generalize inheritable class accessors Cleanup Makefile.PL, etc. Inheitance of non-Mouse classes now produces wranings Tests Changelogging Fix add_metaclass_accessor stuff Clean up Split role application to a module like Moose Cleanup duplicated code Docs chomp white spaces Changelogging chmod -x Tidy Remove unused imports Clean up Make mouse_throw_error in XS more robust Fix apply_all_roles() Make M::M::Method->wrap compatible Add some testing stuff to t/lib/MooseCompat.pm Add a tool to import tests Regenerate test files Fix tests Add test_status.log for authors Make compatibility tests optional. Its is almost useless now. Rename non-portable filenames Add testing notes Changelogging Revert autogenerated tests. Tests should not changed radically. Cleanup failing tests Update meta info Checking in changes prior to tagging of version 0.71. Update ignore files Don't include tests on native traits Update t/lib/MooseCompat.pm s/Moose/Mouse/g more completely Update failing tests (by author/import-moose-tests.pl) Update t/lib Reorganize t/020_attributes/ Resolve some TODO tests about type constraints Fix invalid interpolations in pure perl accessors Make ScalarRef accept ref to ref in pure perl type constraints Reorganize t/050_metaclasses/ Reorganize t/100_bugs/ Reorganize t/300_immutable/ Reorganize t/400_mouse_util Rename a too-long-length name Tidy Changelogging Make the interface of composite role more comatible Test fix Fix t/lib/MooseCompat.pm Comments Fix a tool Revert "Fix t/lib/MooseCompat.pm" Allow $obj->new in pure Perl Fix destructor fallbacks in pure Perl Fix Changes Remove some TODO tags Cleanup Clean up Remove the no-inline version of attribute initialization code Remove _coerce_and_verify method, which is no longer used Comments Add a benchmark for new_object() Tweaks Fix a test Avoid Test::Exception problems with T::E::LessClever Checking in changes prior to tagging of version 0.72. Checking in changes prior to tagging of version 0.73. Tweaks Add failing tests Fix get_all_attributes() for DFS-based diamond-inherited classes Avoid compiler's warnings Tidy Tweaks Make get_all_attributes() sorted by their definition order Add an error check Tweaks Mouse internal cache must be started with '_mouse_cache' Cleanup Docs Merge remote branch 'origin/master' into merge-0.74 Changelogging Checking in changes prior to tagging of version 0.75. Avoid a warnings Duplicated role_type() and class_type() no longer throw the error Fix the delegation rule Fix a cache data name in method delegation Update tests Fix failng tests Tidy Workaround 5.6 problems Checking in changes prior to tagging of version 0.76. Fix 'does' check in pure Perl Cleanup Docs Changelogging Import tests for Test::Mouse Fix superclass validation Fix pods Refactor get_method stuff Cleanup XS Comment Tidy Comments Tweaks Update Mouse::Spec Changelogging Change Makefile.PL always create the test target 'test_pp' Update podspell.t Comments Checking in changes prior to tagging of version 0.77. Update SYNOPSIS of Mouse::Role, urged by ADAMK (RT #61782) Fix a problem that Mouse::Object::DESTROY might refer to released objects (as undef) Resolve RT #61852, thanks to Vincent Pit Checking in changes prior to tagging of version 0.78. Tweaks Fix a mis-use of [ap]THX_ (thanks to Vincent Pit) Checking in changes prior to tagging of version 0.79. Resolve RT #61906, reported by Syohei Yoshida. Checking in changes prior to tagging of version 0.80. Fix a problem; roles with bare-attributes could affect cache invalidation Add tests Checking in changes prior to tagging of version 0.81. Fix a typo Add failing tests, needed by MouseX::NativeTraits testing Fix type constraints to get $tc->type_parameter correctly Tweaks Checking in changes prior to tagging of version 0.82. Tweaks for type constraints; note that type constrains are overloaded Tweaks Tidy Tidy Tidy Remove long deprecated method: M::M::Module::_metaclass_cache Update benchmarks Fix 'Int' type constraint for dualvars (like $!) Checking in changes prior to tagging of version 0.83. Fix tests for portability Display xsubpp settings to make CPAN testers more informative Make Makefile.PL more smart Use Module::Install::TestTarget Checking in changes prior to tagging of version 0.84. Fix an error message to compatible with Moose Make docs more alike to Moose Add TODO Checking in changes prior to tagging of version 0.85. No duplicate check for role_type() Revert "No duplicate check for role_type()" Tests Fix role application to instances; Checking in changes prior to tagging of version 0.86. Add info Clean up Tweaks for coercions Lazy initialization of coercions Fix type composition Checking in changes prior to tagging of version 0.87. Make some C symbols static Update SEE ALSO sections Tidy Fix for SL4A where mro.pm doesn't exist even if Perl >= 5.10.0 Checking in changes prior to tagging of version 0.88. Don't abuse CPP macros Encourage function inlining Tidy Use UNLIKELY() Change layout to make code more clear Don't define Mouse::blessed() and Mouse::confess() Tidy Disable foreign class warnings (PERL_MOUSE_STRICT will enable this) Checking in changes prior to tagging of version 0.89. Use GvCV_set() for bleadperl Workaround a Test::Builder2 (2.00_06)'s threading issue. Support DOES() Checking in changes prior to tagging of version 0.90. $type_constraint->check() accepts extra arguments Make check() accept extra args Hmm, the same warnings as Moose seems difficult. Checking in changes prior to tagging of version 0.91. Resolve RT #67412: C++ stule comments cause prolems in AIX Resolve RT #67019: example/warns.pl didn't work Checking in changes prior to tagging of version 0.92. Fix author/requires.cpanm Make sure weak attributes remain weak when cloning (Moose 2.0007) Checking in changes prior to tagging of version 0.93. Fix documents Add a failing test for RT #69237 (lazy+threads) Merge branch 'master' of github.com:gfx/p5-Mouse-temporary Set gitweb Mouse::Util::does_role() respects $thing->does() method restore changes 0.95..0.97 fix packaging stuff resolve RT#75313 and RT#77227 ($@ issues) modify meta information Checking in changes prior to tagging of version 0.98. Resolve RT#73592 Resolve RT#75093 warning about weak_ref Checking in changes prior to tagging of version 0.99. better handling for the in_global_destruction flag fix an AUTOLOAD related bug off the thread test. FIXME! Checking in changes prior to tagging of version 1.00. fix circular dependency (hanekomu++) Checking in changes prior to tagging of version 1.01. Merge pull request #2 from dex4er/fix_default_errsv Checking in changes prior to tagging of version 1.02. Merge pull request #3 from schwern/bug/maybe_type resolve a test case fix spelling tests Checking in changes prior to tagging of version 1.03. impl $attr->default($instance) for compatibility with Moose add a test file Checking in changes prior to tagging of version 1.04. Merge pull request #4 from creaktive/master Checking in changes prior to tagging of version 1.05. resolve RT#84518, caused by hash ramomization Checking in changes prior to tagging of version 1.06. Merge pull request #5 from schwern/bug/perlcritic Merge pull request #6 from schwern/feature/trigger_third_arg use Test::Spellunker instead of Test::Spelling Checking in changes prior to tagging of version 1.07. fix spelling use Test::Spellunker::load_dictionary() requires M::I::XSUtil to support PURPERL_ONLY=1 Checking in changes prior to tagging of version 1.08. add MANIFEST to the repo RT 82945 fix pod syntax handle ERRSV in a simpler way Checking in changes prior to tagging of version 1.09. modernize pod bundle Try::Tiny Checking in changes prior to tagging of version 1.10. include Try::Tiny Checking in changes prior to tagging of version 1.11. close #7; fix a memory leak Checking in changes prior to tagging of version 1.12. close #8; resolve RT #88295; fix for 5.19.x use github issues for the issue tracker Checking in changes prior to tagging of version 1.13. Merge pull request #12 from dsteinbrunner/patch-1 Merge pull request #13 from hiratara/role-conflict-and-inheritance Checking in changes prior to tagging of version 2.0.0. fix a typo in 00-load.t Merge pull request #14 from gfx/minillaize Merge pull request #21 from syohex/update-minimum-version Merge pull request #20 from tokuhirom/xs_version-5.8.8-fix Merge pull request #24 from tokuhirom/json-boolean Merge pull request #26 from gfx/correct-require-perl-version Merge pull request #27 from gfx/issue-17 Fuji, Goro (gfx) (6): fix for tests add {{NEXT}} placeholder to Changes fix tests Checking in changes prior to tagging of version 2.1.0. Checking in changes prior to tagging of version 2.1.1. Checking in changes prior to tagging of version 2.2.0. Goro Fuji (2): Replace CRLF to LF with all the files Add a test file for RT #53286 Ingy dot Net (1): xsheler.h should be cleaned by `make clean` (Ingy dot Net) Jesse Vincent (1): Moose's make_immutable returns true allowing calling code to skip Joel Bernstein (1): Fix test failures when user does not have C::Method::Modifiers(::Fast) installed John SJ Anderson (1): test showing issue with 'use 5.010' and strictures (#40) Kent Fredric (1): Fix #36; Excess dependency on Test::Exception::LessClever Masahiro Honma (2): Don't use methods which conflicted. Output warnings when the method used by class is changed in the next version of Mouse Matt S Trout (1): fixup Makefile.PL to generate Mouse/Tiny.pm so we actually have a working 'make dist' and new contributors actually produce something that's safe to PAUSE (remember, kiddies, just fucking make it fucking easy to fucking install) Michael G. Schwern (3): Add maybe_type() from Moose::Util::TypeConstraints Get perlcritic tests working for PC 1.118. Make trigger pass in the old value for Moose compatibility. NAKAGAWA Masaki (1): Meta::Class->does_role searches isa for Moose compatibility Nick Woolley (4): Implemented Moose::Object::does, borrowing from Moose::Object. Implemented Mouse::Role->does; modified Mouse::Meta::Class->initialise Modified glob asignment to be coderef assignment. As suggested by Added a new test, essentially the code posted in RT bug #42992. It Piotr Roszatycki (1): Use workaround for Perl-RT #69939 only if Perl is older than 5.14 Ricardo SIGNES (8): doc undef for init_arg ouse.pm! should accept subclasses test for isa improvement reader/writer default needs invocant more specific mark 033 todo Sergiy Zuban (1): test for inconsistent validation of Bool type Shawn M Moore (434): Import Mouse Begin adding brute-force tests for "isa" Expand the isa tests a bit, all that's left is population of valid/invalid values Add the attribute to the metaclass before installing the accessors Future-proof init_arg => undef, that needs tests though isa -> type_constraint Begin adding Mouse::TypeRegistry. All that's there for now is Bool Check type constraint in the setter Add predicates to the informational Mouse::Attribute attributes Verify type constraints in the constructor Tests for bool, lock down the error message in the test Tests for builder builder now called in the constructor Tests and implementation for Undef/Defined types Use "undef" and avoid uninitialized warnings when the value we're type checking is undef Refactor the input of the type-constraint tests, tests are now complete, they just fail miserably Implementations for all of the types except ClassName Nums are Strs too Implementation of ClassName, borrowed from Moose If we re-import Mouse, don't thrash the class's superclasses. Use methods on attribute instead of poking directly in the hash More methodification, change some names to be what Moose::Meta::Attribute uses Use Scalar::Util/Carp imports for brevity Some doc updates Eek my original name is showing! Ignore autogenerated files Unknown type constraints are now interpreted as blessed($value) eq $type Improve doc coverage, remove some needless methods Factor out canonicalize_handles into a separate method Test that a badly typed default explodes Fix type_constraint always being set to undef More glob/fh type tests Little nits Test count fixes Improve coverage of TypeRegistry Tests and implementation for builder with lazy and clearer Make sure that predicate plays well with builder Make sure that eager builder does not run after clearer Moose compat: throw an error on $self->reader(value) Moose compat: required error message tweak Moose compat: lazy-no-default error message Fix a test bug where a value was being assigned to a reader and then checked for undef :) Moose compat: no longer an error to have a trigger on a readonly attribute Don't use meta in the reference test, Moose doesn't like it being invoked as a function Moose compat: Remove Mouse::Class->attributes method in favor of get_attribute_map Moose compat: handles are not canonicalized in the meta attribute's storage, instead at handle generation time Moose compat: the details of load_class. Check whether the package has any methods, etc Moose compat: the weak_ref reader is spelled is_weak_ref, don't weaken nonreferences Moose compat: init_arg is not used for the hash key, name is Use the correct hash keys with init_arg in the constructor use overload::StrVal in type-constraint errors Finish the use of overload::StrVal, in verify_type_constraint Begin moving Moose::Attribute and Moose::Class into Moose::Meta::* Finish moving Mouse::Attribute and Mouse::Class into Mouse::Meta::* have ClassName check use is_class_loaded Some ClassName simplification and fixes Replace is_class_loaded with version from Class::MOP Revert to an earlier t/025-more-isa which gave better test coverage Various is_class_loaded/load_class nits Invalid class names should throw an exception Add failing tests for auto_deref, where I'll pick up next time Implementation of auto_deref Some errors for auto_deref Lots of doc Some final touches on the doc. This is 0.01. Ignore SIGNATURE file Improve BUILD/DEMOLISH tests to cover ordering Fix the order that BUILD methods are called in (thanks Robert Boone) Whoops, was loading Moose instead of Mouse.. Update Changes Improve test code coverage of Squirrel Bit more doc Prepare for release 0.02 Use Class::Method::Modifiers 1.00 for before/after/around Add a test file for method modifiers Add support for ->new({...}) Doc updates Test that subclassing looks at the superclass' attributes in the constructor (it doesn't!) Add compute_all_applicable_attributes Use compute_all_applicable_attributes instead of get_attribute_map in the constructor, a test for the former Add has_attribute, rewrite Changes to be Moosier :) Add the Point example from Moose's tests. Except for method and type constraint stuff, it all passes. cool. Add t/029-new.t for testing the constructor More tests for attributes and new tests for has_attribute Add test for undef init_arg Add support for undef init_arg 0.03 Bump to 0.04 Begin adding tests for has +foo Move validate_args out into a separate method Begin adding support for has +name Begin writing tests for Mouse::Role Begin adding Mouse::Role Blow up when someone tries to use a role extends Adjust the Role::extends error message to match Moose's ;) Test that before/after/around live, and defining a sub within a role Make sure that "has" doesn't blow up Make sure "with" works Make sure that required/excludes don't explode Export and test blessed and confess Begin writing tests for Mouse::Meta::Role Begin adding a Mouse::Meta::Role which is accessible through Role->meta symbol lineup is mandatory Begin actually filling out Mouse::Meta::Role Give Meta::Role a name method Test that "has" adds an attribute to the role Stub 'has_attribute' and make 'has' use 'add_attribute' Make has_attribute actually work Begin writing tests for role application Implement "with" but no role application quite yet Tweaks to "with" Forgot "if @_", oops :) Begin filling out role application Get attributes in role application working! Update Changes Need to unimport Mouse::Role's keywords Begin adding Squirrel::Role Begin adding tests for Squirrel::Role Test fixes Fix tests for Squirrel::Role Make Role::with die no_plan is so lazy :) Have Role->get_attribute return a reference instead of a list no_plan is so lazy Some fixes and test improvements for roles Make it so Mouse doesn't overwrite attributes Rename the 402 test, it's about role attributes Ensure that the local class wins over a role, and that the role over a parent class Make sure that with "A", "B" throws an error Style changes :) Add some more tests for lazy_build Still more lazy_build tests POD and basic test for is_lazy_build Small fix to improve coverage, I wish Devel::Cover handled a ||= "true value" Ensure that "has '+nonexistent'" fails Doc for some of the new meta methods Add canonicalize_args, factor lazy_build canonicalization/validation into the right spot Clean up the clone tests, better error message on cloning the wrong things More tests for clone Better error message for clone_instance("foo") Document BUILDARGS Doc for Mouse::Role Bump the dep on CMM, since it has the prototype fix Failing test for unimport killing a method with the same name as a keyword TODOify failing unimport tests splice out the trigger results so we ensure we don't call trigger extra times Ensure that trigger is always a coderef Allow trigger to be a hashref.. :) We need Attribute->validate_args to take a hashref instead of a hash Canonicalize the coderef version of trigger to a hashref version Support before and after triggers in the setter Support before and after triggers in the constructor Some tests for before/after triggers in Mouse Add support for an "around" trigger in the setter Small test refactor to avoid having to duplicate this trigger tree Some simplification of the inlined type check Add (failing) tests for before/after/around triggers on constructor Implement around triggers in the constructor Flesh out Changes, because I want to release soonish.. We already know $args->{trigger} is true in this codepath Doc for the new trigger. Yikes. Save me perigrin! Moose error compat Moose compat: Rename attribute->class to attribute->associated_class Metaclass->add_method Keep track of the instantiated metaclass in associated_class, use the MOP better, etc Add the lamest changelog entry ever More consistent header Remove dependency on Test::Warn by catching the warning ourself in the one test file we use it in Update some doc Bump to 0.06 Saved by the peri grin! (trigger doc) Add a stub make_immutable for some Moose compat Deprecate hash-triggers Bump to 0.07 commit 84ef660f3af9eb7802a34ed7a8ce3cdc9c52d79f Failing tests for method modifiers in a role Add get_before_method_modifiers etc Add support for adding method modifiers to a role metaclass Fix which add-modifier method gets called Refactor regular class method modifier addition to go through the metaclass On role apply, apply all method modifiers Remove before/around triggers Remove MRO::Compat from Mouse::Object, it now uses the metaclass method Remove blessed from Mouse::Object because it's not used Remove dependency on Sub::Exporter for Mouse (Mouse::Role to come) Drop Sub::Exporter from Mouse::Role ..and the Makefile.PL Make requires/excludes an error until they are implemented Mouse::Util for pure-perl implementations of functions we depend on, in case the dependencies are unavailable use Mouse::Util 'get_linear_isa' instead of MRO::Compat directly Mouse::Util::blessed looks_like_number reftype (which is used by openhandle but not Mouse directly) openhandle Skip t/021-weak-ref if we don't have Scalar::Util weaken for Mouse::Util which will load up Scalar::Util Remove dependency on Scalar::Util Remove dep on CMM by just delay-loading Changes Alter the weaken support a bit doc one day a stray empty line will kill me Bump to 0.08 We need consistency for this one Simplification of blessed, we don't need to lift the refs stricture We don't need to do both eval and Module::Name -> Module/Name.pm munging Begin replacing Test::Exception with a Moose::Util :test Add throws_ok to Mouse::Util Test::Exception! We no longer depend on Test::Exception Fixes for $Test::Builder::Tester, we want to invoke new to get our own instance Skip some tests if we don't have Class::Method::Modifiers Doc that we have implementations for throws_ok and lives_ok Changes Facts! Note our deplessness Credit Yuval, he's done a bunch of hacking Small doc tweaks Notify us of what versions of everything we have from Mouse::Util (and if it even loaded) Run all of Mouse::Util at BEGIN time Don't construct a Test::Builder at BEGIN time, only once throws_ok or lives_ok is called First stab at generating Mouse::Tiny Ignore the generated Mouse::Tiny Bail out of Mouse::Tiny if Mouse is loaded -- we already have all the classes Tests for Mouse::Tiny + Mouse Move generate-mouse-tiny into author/ so blib doesn't grab it Ignore .prove Failing test for mixing in a method from a role use Carp so Carp::croak is defined (fixes some test failures) We need to skip the moose_extends_mouse tests in the absense of Moose Delete the role test for now, we need to track Class methods and all sorts of things first Changes, 0.09 Bump to 0.10 Include CMOP and Moose versions in the dependency display Include CMM, why not Require Moose 0.59 for these tests (not sure when this was fixed; and it's only for a test we know now works :)) require Moose 0.59 doesn't work, need to use: Moose->VERSION('0.59') Remove the version number copied from oose Changes Bump to 0.11 Localize $_ only if we're checking a type constraint Throw an error if a method eval fails inlined_name which quotes Various optimizations to regular accessors Inline the key in predicate and clearer too Update Changes If we have nothing left to do for the accessor, we can return during set Small fixes Factoring Bump to 0.12 Steal the octal-defaults test from Moose, thankfully Mouse passes everything :) Mouse::Util provides throws_ok and lives_ok unless Test::Exception is version 0.27 More fixes for requiring Test::Exception 0.27 Implement and export dies_ok Make the constructor close over the metaclass, and bless into the right class (so subclassing works) Use t::Exception for this test Close over $key so we don't need to do an assignment or variable lookup in the constructor Inline $from Assign the value of the parameter to a lexical so we don't have to continually look it up in the args hash Use fewer assignments when doing a coercion in the constructor Use fewer assignments when doing a coercion in the constructor Better variable names Update Changes commit 826828bf24c48f98a6653459714bd841ed8485b8 Tweak changes for release Bump to 0.13 Fix for default in a constructor reported and tested by rjbs :) Bring shika-based up to trunk Merge in shika-based! Remove build-dep on Sub::Uplevel, Test::Exception can install it (makes us look a smidge better) Remove TODO file, yay Remove pointless shebang in each module Use Test::Exception in this test Comments, style Anchor this exclusion regex so "has_list" etc will work Tweaks to metaclass Anchor this same regex in Mouse::Meta::Role More tweaks For class constraints, it's good enough to be a subclass of that class! Need to specify is => 'rw' for the test to be closer to right Make this coerce test more discriminating Add tokuhirom and Yappo to AUTHORS Test for init_arg => undef Generated constructor cleanup Add type constraint Only inline BUILDARGS if the class has one that isn't Mouse::Object's Make the constructor code easier to read Ignore "used only once" warning Don't put MouseX files into Mouse::Tiny Changes.. too many to list right now MRO::Compat is the only module loaded by Mouse::Util now so we have to check it directly empty line Bump to 0.14 Fix the header in MouseX::Types 0.13 and 0.14 Changes Bump to 0.15 Missing features aren't! Begin renaming some test files so it's easier to test Moose Okay, these are the right names Remove Anti Finish renaming these test modules Add the script I've been using to munge tests to run against Moose Skip squirrel tests when munging s/Mouse/Moose/ Test that we don't export sugar into main Begin renaming Mouse::TypeRegistry to Mouse::Util::TypeConstraints Finish renaming Mouse::TypeRegistry to Mouse::Util::TypeConstraints "type" sugar for when you're not subtyping anything More uses of type in the tests Better linear-isa tests (using the meta API) Rename the method to verify_against_type_constraint since Moose renamed it too Moose::Tiny is not the same as Mouse::Tiny HashRefa looks like a typo Rename the has from %SUBTYPE to %TYPE Style Keep track of the source package of each type; other cleanups Only set @ARGV if it's empty Coerce a type that won't fail us later (damn you Moose) You can redefine types in the original package Remove the redefine type tests for now, they'll go in a separate file class_type shouldn't load the class (Moose compat; no easy fix :/) Don't do the use_ok test Don't try to import Mouse's sugar into main here Need to specify package names Same API as Moose for Mouse::Meta::Attribute->new Begin stealing more Moose meta API We do need to copy %options so we can use $options{superclasses} later Write the anon-class test such that we can run it against Moose, and if we create anonymous classes during Mouse load it'll be okay Rename this class to avoid a type collision Better test here; check the error message Typo fix MouseX::Stop::it! Use Exporter for Mouse::Util::TypeConstraints MouseX::Types can now use MUTc->export_to_level Benchmarking indicates that exists($_[1]) is faster than scalar(@_) >= 2 Failing test for using a custom message in a subtype Fix prototype on message {...} TODOify it for now Document more changes More changes Add a shim Mouse::TypeRegistry that warns and sends you over to Extra ; Ensure that we're not blowing away an inherited constructor We can't support this yet, so TODO and make sure we won't introduce bugs Settle for respecting inline_constructor for now Don't require there to be a BUILDARGS method; fix undef warning Implement basic usage of "enum" type constraints Implement override/super Note enum and override/super implementations in Changes Back out the exists($_[1]) change since exists($array[$element]) doesn't Need to ignore override and super in the method list MouseX::Types is now in its own dist Avoid the warning about exporting sugar into main Doc adjustments Use Any::Moose instead! Changes time Don't put ouse.pm into Mouse::Tiny We no longer have shebangs in pm files, so stop removing package lines Don't need to filter out MouseX any more We backed this baby out Bump to 0.16 Factor out some bits of get_method_list so I can write Implement get_all_method_names Upgrading Moose fixed test failures in these files for somebody, so Support for anonymous enums: enum [elements] Name for Mouse::Role Throw a better error message when using a method modifier without CMM Describe which versions of Moose we need when we skip these tests Skip these tests if you have an old Moose Include CMMF in t/000-load Update Changes Load mro directly if Perl is recent enough (Nicholas Clark) Changes, bump to 0.17 for release Bump to 0.18 Throw a more useful error when users try to use a parameterized type, Just always depend on Scalar::Util 1.14 More gitignore files No need to skip these tests, since tokuhirom++ implemented role-role No real reason for MOUSE_DEBUG these days 0.18 changes No reason to do a string eval here Bump to 0.19 Don't use a method modifier in a test, since they may not be available Avoid depending on method modifiers again 0.19 changes 0.19 Bump to 0.20 Remove third argument to trigger Fix use of meta-attr in trigger Fix version check Fix another keyword regex Turn the throws_ok failures into TODO tests Need to actually be tests to be usefully todo'd TODO package A;our @VERSION passing is_class_loaded Forbid undef passed to new for Moose compat Update error message to match Moose's throws_ok -> todo Move 0.20 changes into the right section More 0.20 changes Add wu-lee to authors Deprecate Squirrel Be more damning of Mouse, more Squirrel deprecation Bump to 0.21 Update Changes 0.21 date Bump to 0.22 Clean up verify_against_type_constraint Use $value instead of $_ in the constructor, since $_ is getting Make sure that role overrides work as specced 0.22 Changes Bump to 0.23 Mouse::class_of If the metaclass has been collected, use mro::linearized_isa directly Changes mro::get_linear_isa -> Mouse::Util::get_linear_isa 0.23 date Bump to 0.24 This fails with older Moose. Not sure which version, but it's just a test 0.24 changes Don't warn about squirrel deprecations Bump to 0.25 0.25 Changes Bump to 0.26 Some more pro-Moose propaganda You need CMM::Fast not Data::Util (which it uses) Maintenance section Transfer copyright to II 0.27 changes Bump to 0.28 Typo fix autodie in generate-mouse-tiny.pl Only unlink Mouse::Tiny if it exists, otherwise autodie pitches a fit Skip class_type etc stack frames when checking the package that defines a subtype Error message fix Stanislaw Pusep (2): Fixed a leak introduced in Mouse 1.04 Added the test for that leak Syohei YOSHIDA (9): Update minimum perl version Correct required Perl versions(#25) Add 5.20 for travis-ci Merge pull request #30 from gfx/add-5.20-for-ci Fix versioning issue(#32) Don't specify version Merge pull request #33 from gfx/fix-version-issue Fix for blead perl Skip test for non-threaded Perls Todd Rinaldo (1): tests with perl 5.14 produce deprecation warnings (Todd Rinaldo) Tokuhiro Matsuno (92): support requires on Mouse::Role. - added Moose::Util::apply_all_roles Mouse::Role supports 'with' support alias option on 'with' don't require Test::Exception on production environment =) test related things is moved to t::Exception updated todo list - inject object constructor when call meta->make_immutable. micro optimization performance tuning generate DESTROY method for performance improvement update todo list move Test::Exception to inc/. suggested by autarch++ overload::StrVal is needed oops... i forgot s/Moose/Mouse/ orz (JUST A IDEA) copied from Scalar-List-Util/Util.xs Exporter::Heavy is too heavy.And, this is enough in a lot of case . we want to use older Exporter micro optimization added Mouse::Meta::Class->create(_anon_class)? do not use same variable name twice. bug fixed: BUILD method doesn't works shortcut the flow for micro optimization. micro optimization this argument is not needed added benchmark script inject empty DESTRUCT method for performance improvement. always inject method to DESTROY display module version in benchmark script revert XS related things. this is no advantage orz revert XS related things - depend to Scalar::Util when perl5.6.x oops bug fixed when perl 5.8 added 'get' in benchmark script change directory structure skip temporary file for vim use Scalar::Util directly call by full path added more test cases added test case for compatibility improvement the compatibility with Moose. update todo list added Mouse::Util::apply_all_roles to @EXPORT_OK for Moose compatibility added attribute metaclass support. micro optimization for method modifiers. depend to Scalar::Util 1.14. added .gitignore file for git-svn users support Mouse->import({into_level => 1}). added YourClass->meta->add_attribute(foo => (is => 'ro', isa => 'Str')); support. oops. we want to use 'metaclass' in role, too :( much faster impl. for constructor/accessor. this is a same behavior with Moose. make a subtype for each Mouse class This behavior is same as Moose. added comment added Meta::Class->has_method($name) more strict argument check. Mouse does not support Application::ToInstance yet added Meta::Class->add_attribute_list for Moose compatibility added Mouse::Meta::TypeConstraint and use it. Mouse::Meta::Attribute->type_constraint returns an object. and, find_type_constraint was deprecated. rebirth the find_type_constraint for backward compatibility oops. i forgot to change make_immutable code. t/900_bug/001_immutable_types.t: oops. 'package B' means B.pm, reserved namespace. and, fixed invalid usage of subtype. ignore *.old file generate moose compatibility test automatically less deps in Makefile.PL added benchmark case for setter, getter use compiled type constraints. this change makes faster :) split accessor generator from the Meta::Attribute. refactoring the duplicated vars use compiled_constraints directly. performance enhancement. scope makes slower!mouse's constructer is faster than moose with this commit :) do not create a copy of argument, if not needed added benchmark script for C::A::Fast fixed test count class-mop says 'The compute_all_applicable_attributes method has been deprecated.' compatibility test is generating automatically.ignore it. fixed pod mark up bug. and added Test::Pod test. Mouse 0.21 Changes Merge branch 'master' of gi...@jules.scsys.co.uk:Mouse Moose says 'The clone_instance method has been made private. The public version is deprecated.' tckect #42992: Method modifiers affect all classes in the whole inheritance tree added typeconstraint's customizable error message support. added workaround for autogenerated Moose test bug fixed. test is very important things! latest moose inlining destructor by default update the test code from latest moose repo construct_instance is obsolated, use construct_instance instead Mouse code has a lot of '{' and '}', q{} is dangerous. added Mouse->init_meta this test fails with older moose added failing test case for RT#47744 Fixed XS_VERSION error while building on Perl 5.8.8 Make 'Bool' type Moose compat. Tomas Doran (t0m) (3): Fix issue reported by ArjenL in #moose Add date to changelog Bump to 0.27, Sartak style :) Vincent Pit (1): Implement Mouse::Util::TypeConstraints::register_type_constraint() Yuval Kogman (19): v string not portable use teh Squirrel i speak english, i learn it from a book more explaining number squirrel.t implement lazy_build failing test for inheriting from non Mouse class fix the failing test, only call ->meta on a linearized isa member if ->can('meta') lazy_build arg processing copied from Moose is_lazy_build changelog changelog date version bump to 0.05 Be nice to Moose::Role::unimport in older moose clone_{object,instance} BUILDARGS silence BUILD used only once warning Moose extending Mouse test & minor fixes get_all_attributes gfx (975): Move MethodAccessor stuff to Attribute Use mkpath instead of make_path in Makefile.PL Make generators private Support is => 'bare' for compatibility Improve type constraint stuff Make $role->get_method_list() include meta() (Moose 0.90 feature) Move MethodAccessor stuff to Attribute Use mkpath instead of make_path in Makefile.PL Make generators private Support is => 'bare' for compatibility Improve type constraint stuff Make $role->get_method_list() include meta() (Moose 0.90 feature) Warn about missing associated methoes, instead of die. Merge branch 'topic/more-compatible' of gi...@moose.perl.org:Mouse into topic/more-compatible Add missing is => 'bare' to a test Fix meta() and initialize() for more compatibility Merge branch 'master' into topic/more-compatible Fix Changes Save global variables (Mouse/Util.pm) Refactoring Fix a bug related to the randomized hash keys. Move M::Util::(version|authority|identifier) to M::Meta::Module Cleanup Creanup Changelogging Add has_x_method_modifiers, but not yet tested Remove duplications and cleanup Add my name to Changes Use throw_error() instead of confess() Add a test file for throw_error() (Re-)organize Method Accessor, implementing has ... reader => $r, accessor => $a, writer => $w Add Meta/Method/Accessor.pm Fix tests for accessors Remove an unused method A tiny tweak Mouse::Role improved Make anonymous classes work correctly Use scalar(caller) instead of caller in list context Add TODO Merge branch 'master' into topic/more-compatible Fix typos in tests Release date Add my name to AUTHORS Remove a version check Update .gitignore and add MANIFEST.SKIP More compatibility Remove xt/compatibility/* at make clean Changelogging Fix Makefile.PL to remove old xt/compatibility/* tests, and organize Mouse::Util Change, Fix, Improve Changelogging Note failures in 5.10.1, but I don't know why it happens version 0.31 Add Mouse->moose_version for compatible Moose version, and fix Makefile.PL Fix tests Copy .shipit from Moose Add some test files Add a comment Add Mouse::Util::english_list() Implement confliction checks in roles Add various things Changelogging version 0.32 Remove unused test files CRLF to LF Fix the timing triggers are invoked Add a test file Checking in changes prior to tagging of version 0.32. Changelog diff is: Fix RT #49902 Always load Mouse::Util first, which will be load Mouse::XS in the future Changelogging Fix init_meta and related stuff Fix Squirrel.pm Fix type constraint issue Add a test file for type constraints Tweaks for type constraints. Squirrel::Role also produces warnings Changelogging Add placeholders of augment() and inner() to Mouse.pm Add tests for recipes, just copied from Moose Fix errors Checking in changes prior to tagging of version 0.33. Changelog diff is: Release date Resolve a todo (method confliction) Add some tests Move features used only for testing to t/lib/Test/Mouse.pm Fix class_type Refactor the constructor of Attribute Add Mouse::Spec for required Moose version Fix Makefile.PL to use Mouse::Spec Refactor many many things Add tests related to attribute traits version 0.33_01 Skip a test requiring method modifiers crlf :( Merge branch 'blead' Refactor attribute constructor Deprecate clone_instance Tidy Tidy Add Devel::Cover and Devel::NYTProf stuff to .gitignore and MANIFEST.skip Make sure to work on 5.6.2 Make a test TODO Improve documents Add pod tests Changelogging Move some test files Remove unused import Add a benchmark for method modifiers Add a benchmark based on author/bencharks/basic.pl Update MANIFEST.SKIP to remove author/benchmarks/* from dist Update MANIFEST.SKIP to remove unexecuted tests Implement own method modifiers Method modifiers are implemented in Mouse Tidy Fix a test: package B conflicts the B module Fix various tests for new Mouse Changelogging Comment out 'does' Fix tests and documents Tiny tweaks suggested by NYTProf No base.pm Release date Add a profile script version 0.34 Work around broken Test::Exception Changelogging Add SEE ALSO to Meta Module Checking in changes prior to tagging of version 0.35. Changelog diff is: version++ in Spec.pm Fix an issue that breaks a backward compatibility. Add CheckVersionMatch to .shipit Checking in changes prior to tagging of version 0.36. Changelog diff is: Fix compatibility issue on Ark Fix AUTHORS in pod for Module::Install to recognize e-mail addresses Fix a test Fix has_method() for backward compatibility Add a "no warnings 'once'" Fix pods Add author/test-externals.pl to test external distributions that depend on Mouse Update .gitignore and MANIFEST.SKIP Remove "native traits" from TODO, which won't be supported version 0.37 Fix test-external.pl Changelogging Fix Changelog Add descriptions to pods Tweaks for pods Add distributions to author/test-externals.pl Add tests for $tc->is_a_type_of Add test on type constraints with complex parameters Rewrite type constraint parser for union parameter: ArrayRef[ Int | Str ] Remove 'Role' type from the document Changelogging Add a warning for an old style use of TypeConstraint Add two test file about union types Fix union types and coercion Add a test for deprecated feature Fix an issue that breaks backward compatibility Move a test as t/052-unidefined-type-in-union.t Update Makefile.PL Refactor type constraints Fix subtype() Remove unused methods CRLF to LF Move type coercion mechanism from Util/TypeConstraints.pm to Meta/TypeConstraint.pm Tidy Add a semicolon Copy two test files from Moose Deprecate two internal methods: coerce_constraint() and typecast_constraints() Remove debugging code Fix an issue tested in t/040_type_constraints/025_type_coersion_on_lazy_attributes.t Copy two test files from Moose Add benchmarks about subtype and coercion Remove an unused method Changelogging A tiny tweak Changelogging Changelogging Remove some private or useless methods/functions from Mouse::Meta::Module s/Moose/Mouse/ in a test Fix some code for new APIs Tweaks Add a benchmark for load_class() Tidy Tiny tweaks Changelogging Add MouseX::AttributeHelpers to author/test-externals.pl Remove the use of get_attribute_map() Deprecate compute_all_applicable_attributes() and get_attribute_map() Tidy Add a test file to extend metaclasses Mouse::Meta::Class and Mouse::Meta::Role are now extensible by extends() Fix a test Add get_read_method_ref and get_write_method_ref. Remove get_read_method and get_write_method. Add 2 test files Changelogging Fix tests version 0.37_02 Rename t/000-recipes to t/000_recipes Refactor create() and DESTORY() in Mouse::Meta::Module Fix previous changes Add a test file Comment deprecated methods Cleanup Fix pods Release date Fix meta() method Fix class/role creation Fix issues on 5.6.2 Fix clone_and_inherit_options() to take 'traits' and 'metaclass' correctly Remove the "Maintainance" section from the pod. Add tests for Mouse::Util::meta() Changelogging Remove old, unused variables Refactor the override method modifier code to reduce duplications add_method() accepts method objects Implement augment/inner Fix EOF Import Moose/t/010_basics/*.t Add find_attribute_by_name() Add a test for find_attribute_by_name() using t::lib::Test::Mouse Changelogging Checking in changes prior to tagging of version 0.37_02. Changelog diff is: Fix a test Refactor install_accessor() and related stuff This is a Mouse::Exporter branch For 'also' Work for Mouse::Exporter Fix do_unimport and related stuff Use Mouse::Exporter Refactor and optimize Mouse::Exporter Add test for Mouse::Exporter s/group/groups/ Fix several issue on Mouse::Exporter Fix t/010_basics/007_always_strict_warnings.t; Now Mouse::Exporter exists. Switch to Mouse::Exporter Changelogging Tweaks and documenting Mouse::Exporter Make Mouse::Exporter to provide export_to_level() and export() for backward compatibility Add a regression test Fix a bit Refactor and optimize Mouse::Meta::Method::Accessor Improve tests Tweaks for benchmarks Refactor and optimize Mouse::Meta::Method::Accessor More compatibility Resolve TODO: Mouse::Util::TypeConstraints->unimport works Remove the TODO file Retrieve @EXPORT, which is no longer used, but defined for backward compatibility Changelogging Canonicalize the name of union types Implement role application to instances Resolve a failing test Fix an accessor generator to accept role application to instance Implement 'does' attribute in has() Resolve 4 'failing' tests Changelogging Fix a test version 0.37_03 Release date Fix Mouse::Exporter to work with Mouse::Tiny Fix author/generate-mouse-tiny.pl. Now Mouse::Tiny is generated in the "make" command Add newline to the end of the file add_method() stores code references instead of a true value Re-implement role composition, which was implemented but broken Resolve 4 'failing' tests Changelogging Tiny tweaks Very tiny tweaks Add note to general methods generate-mouse-tiny.pl must depend on only standard libraries Check superclasses not to inherit from roles Fix some issues on attributes Import tests for attribute from Mouse's tests Fix subtype $name Fix a possible syntax error in generated constructor Resolve many 'failing' tests A tweak for backward compatibility Changelogging Release date version 0.37_04 Checking in changes prior to tagging of version 0.37_04. Changelog diff is: Replace ChangeVersion with ChangAllVersions Move non-useful, Moose-specific methods into t/lib/Test/Mouse.pm Remove Moose's comment Tidy for release Add "optimize_as" sugar to TC Remove a Moose-imcompatible warning Add a VERSION section to Mouse.pm Add build_import_methods to Mouse::Exporter Add test to make anonymous classes immutable Fix a bug about immutablizing anonymous classes Fix tests for Moose compatibility Replace a moose recipe Import a moose cookbook recipe Fix meta initialization in Mouse::Exporter Add notes for Moose::Cookbook Add 4 recipe tests Fix a typo Changelogging Changelogging Fix a test for ancient perls Print messages in generating Mouse::Tiny Fix Makefile.PL Checking in changes prior to tagging of version 0.37_05. Changelog diff is: Creates role_type in Mouse::Role::init_meta Tidy Format Changes Move t/*/t into t/001_mouse Move t/100_with_moose t/810_with_moose Skip some tests for Moose Import Moose/t/100_bugs Add regexp handles Add localization of $@ and $? in DESTROY Changelogging Resolve a 'failing' test, although it has some TODOs Resolve a 'failing' test Changelogging Fix role application to instances Tidy Add a comment Changelogging and release date Resolve a todo Update MANIFEST.SKIP Checking in changes prior to tagging of version 0.37_06. Changelog diff is: Revert "Skip class_type etc stack frames when checking the package that defines a subtype" Merge branch 'blead' Changelogging Add VERSION section to pods Add "Incompatibility with Moose" section to Mouse::Spec Update Makefile.PL Add $VERSION to Mouse::Role to allow "use Mouse::Role VERSION" Improve he-profile.pl Changelogging Changelogging, Mouse::Spec Update documents Fix a sentence in a pod Changelogging Add SYNOPSIS to Mouse::Spec Checking in changes prior to tagging of version 0.38. Changelog diff is: Fix RT #50421 Add a test for RT #50421 Fix RT #50422 Changelogging Checking in changes prior to tagging of version 0.39. Changelog diff is: Update Mouse::Spec Fix an issue in Mouse::Object::new to throw informative messages Add "use Mouse -traits => [...]" support, but not yet completed Ignore fatal errors in "traits" resolution. This is a temporary change. Fix a testname (poe-coverage-moose.t -> pod-coverage-moose.t) Add calculate_all_roles() to Meta::Class/Meta::Role Make pod-coverage-moose.t pending Add xt/external to MANIFEST.SKIP Revert "Ignore fatal errors in "traits" resolution. This is a temporary change." Mouse and Mouse::Roles does export their sugars to main Import tc tests Resolve some tests Fix subtyping issue Add tests for subtyping issue Modernize some tests Changelogging Checking in changes prior to tagging of version 0.40. Changelog diff is: Rename 800_shikabased/*.t to 001_mouse/8*.t (suggested by tokuhirom :) Fix a typo in a test Update Makefile.PL Merge branch 'master' into blead Fix the NAME in Mouse::Meta::Method::Destructor Make method generators extensible Rename ::Meta::Method::new to ::Meta::Method::wrap to fit to Moose Lazy load Mouse::Meta::Role Use get_method_body(), instead of can() Fix load.t Fix load.t Update .gitignore for XS Update MANIFEST.SKIP Add XS stuff to Makefile.PL Add first XS implementation Fix generate-mouse-tiny.pl Move accessors into XS Move ::Meta::Module::namespace into XS _get_code_ref() and get_linear_isa() in XS Remove useless check code built-in type constraints in XS Tweaks for Makefile.PL Report $Mouse::VERSION and the backend (Pure Perl or XS) in load.t Repeat test with MOUSE_PUREPERL=1 in "make test", adding "make test_pp" target Use postamble() insteead of MY::postamble() Add "documentation" attribute to Mouse::PurePerl Use get_code_ref() Tweak for Meta::Method Implement XS accessor generators Tweak for benchmarks/subtype.pl Ensure backward compatibility Update MANIFEST.SKIP Version 0.40_01 Rename a file Implement a class_type generator Fix a typo in PurePerl.pm Improve author/use-he.pl More _generate_class_type_for() Split accessor generators into Accessor.pm and Delegation.pm Add *.bs to MANIFEST.SKIP Remove mro_compat.h, which was accidentaly included Fix a test Fix Util.pm Tweaks for XS accessors Add two benchmark files Changelogging More compatibility to Moose Tidy Ensure configure_requires 'ExtUtils::CBuilder' Do not import unused functions Hack for XSLoader Move add_method into XS Add methods to PurePerl.pm Remove debuggign code Add document Fix a typo in Changes Compat for Moose Resolve a failing test Tweaks for compatibility Resolve a failing test Changelogging Fix Mouse.xs No import No import Improve Makefile.PL No import Remove debugging code Tidy No meta programming in Mouse/Meta/Role.pm Tiny optimization No import Release date Remove object files in "make clean" Checking in changes prior to tagging of version 0.40_02. Changelog diff is: Make is_class_loaded without any arguments fail loudly Fix a test: is_class_loaded without arguments throws an error Ensure the version of Module::Install::XSUtil Tidy Add '|' operator to Meta::TypeConstraint (experimental) Add comment to 810-isa-or.t Make type constraints always true Add tests for or-combination operator Move parametarization code to Meta::TypeConstraint Changelogging Checking in changes prior to tagging of version 0.40_03. Changelog diff is: Change a message from Makefile.PL Use Carp::Always in Makefile.PL when Mouse is in development releases Include Mouse::PurePerl first Change is-a predicate stuff Fix a typo in generate-mouse-tiny.pl s/_generate_isa_predicte_for/generate_isa_predicate_for/; it's Mouse specific anyway. Use bit-or, not simple assignment Re-organize xs-src/ Tiny optimization for XS accessors Remove duplicated checks Remove an unused variable Refactor generate_isa_predicate_for-related stuff Add "mouse_" prefix Remove an old utility, mouse_is_instance_of() mouse_tc is always true Refactor type constraint check function to make class_type faster Refactor built-in type constraints Tidy Fix associate_method() Tidy Add a comment Refactor tc parametarization Implement type parameterization in XS Add comments Split benchmarks/accessors.pl to two files Ensure backward compatiblity Simplify compile_type_constraint Implement compile_type_constraint in XS Change TC hierarchy in XS Use shortnames for mouse_instance_* s/\t/ /g; Generalize type constraint generation Tidy and simplify mouse_attr_get() Checking in changes prior to tagging of version 0.40_04. Changelog diff is: Add memory leak tests for type constraints and accessors Tweaks for Mouse guts, and add Mouse::Util::_MOUSE_XS symbol Tweaks Delete a duplicated test file and add a new test file for Mouse::PurePerl Skip compatible test for Mouse::PurePerl More newSVpvs_share() Tidy Changelogging Checking in changes prior to tagging of version 0.40_05. Changelog diff is: Move XS Meta::Constraint stuff to the correct place Rename XS functions Remove useless use of or-assign Make type check macros Shut up a warning "DPPP_newSVpvn_flags defined but not used" Skip BUILDALL in the default constructor, and DEMOLISHALL in the default destructor: BUILDALL and DEMOLISHALL are no longer called by the default constructor/destructor. Implement get_all_attributes in XS Fix a typo Fix mro_get_linear_isa Tiny optimization Remove an useless "use Scalar::Util" directive Remove extra commas from pods Add the README file Add a example script Changelogging Add my name to Changes Changelogging Refactor XS metaclass object structure Tweaks for speed Update M::I::XSUtil to 0.17 Tidy Makefile.PL Add BUILDARGS tests XS constructor Add utility macros: newAV_mortal() and newHV_mortal() Use new[HA]V_mortal() Add $ignore_triggers option to _initialize_object() Add mouse_get_xa() Add _initialize_object() Change inline_constructor => 0 No -T in tests Optimize get_metaclass() in XS Fix a typo in the code Fix BUILDARGS logic Add Mouse::Object::new in XS Revert "Change inline_constructor => 0" Move Mouse::Object::new to PurePerl.pm Skip extending tests Mouse:::Meta::Method::Constructor is used only in pure perl mode Add mouse_initialize_metaclass() DEMOLISH to XS Print the status code in the profiling script Remove "use Mouse::Meta::Method::Destructor" Name subroutines in add_method() Checking in changes prior to tagging of version 0.40_06. Changelog diff is: Fix default and weak stuff Add a test for weakref stuff Define "inline" if not provided (mouse.h) Make some functions static Make mouse_accessor_get_self() "static inline" Make some constants as class attributes Add MOUSE_mg_len(mg) Add threading tests Move build tools to tool/ Add author's tools to MANIFEST.SKIP Add a benchmark script Remove a debugging method Add tests for accessor robusity Add tests for constructor_class/destructor_class as attributes Tidy Mouse::Object has meta() method Now handles => qr/regex/ is supported For Mouse::Util::MetaRole Import t/050_metaclass from Moose Add Mouse::Util::MetaRole Resolve 015_metarole.t Start to support "use Mouse -traits => ..." TODO Resolve 013_metaclass_traits.t, but not completed Remove a resolved test Resolve a "failing" test Resolve two "failing" tests Fix compatibility tests Fix many Add metaclass compatibility stuff Add pod to Mouse::Tiny Fix _reconcile_with_superclass_meta Add public method list as TODO Add pod to Mouse::TypeRegistry as a deprecated module Tidy Add pod coverage test, but it does not test yet Mouse test suite requires Moose 0.93 Rename XS funcs which generate XSUBs Fix metaclass compatibility resolution Remove method list without explanations Add a constant, MOUSE_XS Changelogging Add a comment A tiny tweak Change class holders to simple readers Remove an unused function: XS_Mouse_simple_accessor() Add new test files Checking in changes prior to tagging of version 0.40_08. Changelog diff is: Fix meta method constructors Fix add_method to accept overloaded CODE references correctly Fix a error message in apply_all_roles Add immutable_optins Skip class unload stuff in global destruction Port (get|has)_package_symbol from Class::MOP No duplication Tidy Rename a macro to define a class holder Tweaks in Makefile.PL Add a comment Add a description Update the repository information Fix a meta slot name Fix a bug that segv caused on 5.6.2 with -traits Resolve skipped tests (for 5.6.2) Fix benchmarks/vs_caf.pl Clean the code up Tidy Changes Add some tests Fix XS loading code Fix has() Add meta() method to method metaclasses Fix a prototype-related problem on 5.8.x Add a test for C3 classes Add a message in Makefile.PL Checking in changes prior to tagging of version 0.40_09. Changelog diff is: Remove mentions to Class::Method::Modifiers Changelogging Make accessor generators extensible Fix the parameterized HashRef constraint routine Add tests for magical vars and hash iterators Fix Makefile.PL to add author's tests correctly Fix a typo Add function list to pod Fix tests Tidy Checking in changes prior to tagging of version 0.41. Changelog diff is: Fix a PAUSE indexing issue Checking in changes prior to tagging of version 0.42. Changelog diff is: Fix the pod of Mouse Remove has_package_symbol and add_package_symbol Add documents for attributes Add documents to Mouse::Spec Tweaks for ouse.pm Add a note for Mouse::XS, which requries Perl 5.8.1 or later Fix a typo in the pod Fix the hierarchy of type constraints: Num and Int are a subtype of Str Add some document Changelogging Make Mouse/Tiny.pod Fix benchmarks/modifiers.pl Add a comment to Changes Tiny optimization for DESTROY Add a benchmark for destructors Checking in changes prior to tagging of version 0.43. Changelog diff is: Use Module::Install::XSUtil 0.19 Fix typos Add Test::Mouse Changelogging Improve enum to accept "enum($name, $arrayref)" construction More robust tests for threads Add duck_type to Mouse::Util::TypeConstraints Tidy Add a benchmark for duck_type Optimization for duck_type Changelogging Add duck_type to the function list Add coerce() to the function list Changelogging Add a test file for duck_type Checking in changes prior to tagging of version 0.44. Changelog diff is: Fix accessor filenames Move BUILDALL and DEMOLISHALL into XS Add with_immutable to Test::Mouse Add set_value/get_value/has_value/clear_value to Attribute Switch to duck typing Implement make_mutable :) Add tests for get_value etc Changelogging Add filesystem portability test (indicated by RT #52828) Rename for portability to resolve RT #52828 Fix BUILDALL in XS Changelogging Add tests for BUILDALL/DEMOLISHALL Tiny tweaks Avoid autovivification Rename variable names for clearity Tidy Lazy load for Delegation class Move is_immutable into XS Change the internal delegation code Change the signature of verify_type_constraint_error [IMCOMPATIBLE] Fix an issue that anonymous type constraint can't be defined Changelogging Add resolution of conflitcting extention Rename: s/verify_type_constraint_error/_throw_type_constraint_error/g; It's Mouse specific. Checking in changes prior to tagging of version 0.45. Changelog diff is: Tweaks for 5.6.2 Add 'use warnings FATAL => "recursion"' to Accessor.pm Revert "Add resolution of conflitcting extention" Checking in changes prior to tagging of version 0.4501. Changelog diff is: CRLF to LF Merge branch 'master' of moose.perl.org:Mouse Revert "Add a test file for RT #53286" Apply a patch to support handle => sub { ... }, contributed by Frank Cuny. Clean up deprecations Remove long-deprecated features ouse.pm uses Mouse::Util::TypeConstraints Changelogging Fix Str() and ScalarRef() Clean up mouse_tc_ScalarRef() Fix type casts incompatible with c++ (delected by -Wc++compat) Move tied hash checks Update the copyright information Checking in changes prior to tagging of version 0.46. Changelog diff is: Move Mouse::Meta::Attribute::_process_options into XS Use sv_true() instead of SvTRUE(), which is too large to inline Fix a message Don't create scopes as much as possible Fix a typo Merge some tests to one file Merge extends.t and auto-subclass.t into subclass.t Merge default-code.t to default.t Merge clearer.t and predicate.t to predicate-and-clearer.t require Class::Method::Modifiers::Fast 0.041; this is because it requries gfx's Data::Util correctly. Add the CAVEATS section for the call_sv() failures Clearify the issue on RT#69939 Makefile.PL requires Module::Install::XSUtil 0.21 Add conflicting checks to Makefile.PL Fix a typo in docs Checking in changes prior to tagging of version 0.47. Changelog diff is: Fix the class for init_meta() Improve Makefile.PL not to test Moose compatibility when the main tests fail Use Mouse::Object::BUILDARGS, because it's safe and flexible. Fix magic handling in type constraints (reported by sunnavy) More tests for magic handling Remove imcompatible tests Changelogging Checking in changes prior to tagging of version 0.48. Changelog diff is: Fix RT #54203 (reported by chocolateboy) that setters might return undef. Use mouse_name instead of literals Optimize coercion Fix a memory leak in generate_isa_predicate_for() Checking in changes prior to tagging of version 0.49. Changelog diff is: Change a terminology; s/applicant/consumer/; Make Mouse::Tiny smaller Mouse::Tiny shouldn't include Test::Mouse Refactor mouse_get_xa() The Mouse dist does no longer include Test::Exception. The latest version, 0.29, seems good. Remove some todos in tests Make several role attribute tests todo Resolve a todo Catch up to Moose 0.94 metaroles Use new API for metaroles Changelogging Apply a patch contributed by chocolateboy (RT #54383) to allow "use Mouse::Tiny VERSION" Add method decls in meta type constraint class. $tc->coerce() throws an error if it has no coercion, as Moose's tc does. Add Mouse::Util::quoted_english_list() Simplify Mouse::Meta::Role::Composite::_apply_methods() Correct 'does' method The default maxdepth of 'dump' method is now 3, instead of 2. Checking in changes prior to tagging of version 0.50. Changelog diff is: Reduce duplicated code Support modifier by regexp Resolve a failing test: method_modifier_with_regexp Update document Update docs for metaroles Update example/point.pl Make add_method update %DB::sub for profilers Update pod_spell.t Add a DB::sub test to xt/ Update tests Support the global destruction flag in DEMOLISH() Changelogging Add todo tests: mouse_extends_moose.t Revert "Add todo tests: mouse_extends_moose.t" Add an arg check to appply_metaroles() Add tests for traits Fix tool/create-moose-compatibility-tests.pl to replace class_of() Refactor Meta::TypeConstraint Fix a typo Mouse::Meta::Attribute->new warns about unknown, or misspelled, arguments (compat to Moose 0.84) Changelogging Checking in changes prior to tagging of version 0.50_01. Changelog diff is: Update Changes Add type_parameter() and __is_parameterized() to Meta::TypeConstraint Add assert_valid() to Meta::TypeConstraint Resolve several failing tests Add argument currying for delegation Changelogging Add prototypes Implement strict constructors, which will warn unkown constructor arguments Changelogging Add make_immutable to the SYNOPSIS Work around 5.6.2 warnings Add tests for strict constructors Checking in changes prior to tagging of version 0.50_02. Changelog diff is: Add a benchmark for strict constructors Skip tests for strict constructor on Moose Implement the built-in type hierarchy Fix a possible segv on DESTROY Don't set package_defined_in automatically, because Moose doesn't do that. Make editors happy. Mention to MouseX::NativeTraits Optimize Method::Delegation Tidy delegation routine Resolve a todo: if you set both 'isa' and 'does' on an attribute, the 'isa' must do 'does' Fix docs. The phrases "Fewer than 1%" and "over 96%" are very confusing, so I removed them. Checking in changes prior to tagging of version 0.50_03. Changelog diff is: Make Mouse::Util::load_class return the argument class name, which can remove several temporary variables. Export load_class and is_class_loaded to the Mouse:: package in Mouse::Util Move is_valid_class_name into XS Remove a fat semicolon Refactor get_linear_isa() Clean up warnings Remove extra spaces and comments; no functionality changes Tidy the pp constructor generator Move method modifier manipulators into XS Tidy _generate_destructor More tests for strict constructor Use @CARP_NOT instead of %Carp::Internal Add an example for Mouse error checking Fix a typo Make roles smarter Introduce install_subroutines() to reduce direct stash manipulation Implement install_subroutines in XS Simplify error check routines in XS Tidy Meta::TypeConstraint Remove an internal constant, _MOUSE_VERBOSE No constant.pm Make does_role accept a role meta object Deprecate Mouse->export and Mouse->export_to_level. Checking in changes prior to tagging of version 0.50_04. Changelog diff is: Reset stash iterators Use mcall1s() instead of raw perl API Reduce SvGETMAGIC() Use more mcall1 Tidy the xs code Add author/requires.cpanm for co-developpers. "cpanm < author/requires.cpanm" will install all you need. use Module::Install::AuthorTests for co-developpers Fix an error Refactor pp method generators Merge remote branch 'origin/more_than_32_bit_Int_on_32_bit_systems' Shorten a test file name Add a todo to test metaclass compatibility Fix metaclass imcompatibility issue Checking in changes prior to tagging of version 0.50_05. Changelog diff is: Method::Constructor and Method::Destructor must be loaded in pure Perl mode Work around RT #55048 for Mouse::PurePerl Checking in changes prior to tagging of version 0.50_06. Changelog diff is: Revert "Refactor pp method generators" Fix a possible panic, caused by triggers (reported by Nobuo Danjou) Checking in changes prior to tagging of version 0.50_07. Changelog diff is: Add Net::Google::DataAPI to author/test_externals.pl Reinplement the type parser. Now it throws syntax errors e.g. "ArrayRef[]" or "ArrayRef[Int". Changes and docs Makefile.PL accepts --author option, to install author's prerequisites Add user module testing using Test::DependentModules Add some author's prereqs Fix triggers Set correct parents for enum_type and duck_type Update README Fix metaclass compatibility Remove CheckVersionsMatch, add UploadCPAN Make Meta::Method comparable like Class::MOP::Method Turns on FATAL => 'recursion' by "use Mouse" Checking in changes prior to tagging of version 0.50_08. Changelog diff is: Add xt/07_vars.t Remove unused vars, suggested by Test::Vars Introduce Test::Perl::Critic Remove vars.t Fix a module name Fix an issue on the Int type constraint, to accept 2*46 as Int and to refuse 2**46+0.5 as Int Ensure M::I::XSUtil 0.22 Checking in changes prior to tagging of version 0.50_09. Changelog diff is: Resolve a todo to pass pod-coverage-moose Rearrange test files Checking in changes prior to tagging of version 0.51. Changelog diff is: Add an example using NativeTraits Clean up author/test-externals.pl; see also t/800_with_external/*.t Ensure to use Mouse in Any::Moose Add Test::Requires to dependencies Fix an env setting Remove the cache of load_class() $tc->check into XS Make Mouse::XS reloadable Make a private function static Workaround RT #69939 Use PL_statusvalue directly, instead of useing $? Tiny tweaks Remove caveats about RT#69939 Checking in changes prior to tagging of version 0.52. Changelog diff is: Rename a wrong-named test file Fix clone_object() to ignore hehaviours without init args Tweaks Checking in changes prior to tagging of version 0.53. Add a test file for RT #56523 Apply a patch from Michael G Schwern Checking in changes prior to tagging of version 0.54. Comment out a debug output Workaround a bug with threads. cleaning stash with threads can cause panic or SEGV. Checking in changes prior to tagging of version 0.55. Resolve RT #56837 (reported by Sanko Robinson), based on his patch Rename a test directry name to be clear Checking in changes prior to tagging of version 0.56. Skip a test that fails on some platforms Resolve RT #57975: "Exception caught:" prefixes on "re-thrown" exceptions have been removed Follow Moose's new feature: BUILDALL is called by new_object(), not by Mouse::Object::new Make type constraint messages compatible with Moose's Make clone_object() into PurePerl Checking in changes prior to tagging of version 0.60. Fix possible memory leaks, which occurs when constructor components throw errors. Ensure M::I version >= 0.99 Fix the Perl_call_sv() problem again, and tests for it Compat version is 1.05 Checking in changes prior to tagging of version 0.61. Fix threading tests for bad perls: Avoid compiler's warnings on older perls Add __set_strict_constructor Revert __set_strict_constructor Make strict_constructor public Avoid compiler's warnings Checking in changes prior to tagging of version 0.62. This fixes RT#59460. (Curtis Jewell) Import a latest test file for register_type_constraints() and fix tc class Checking in changes prior to tagging of version 0.63. Use new macro CvGV_set() (see perl5133delta) Add $attr->insertion_order Add illigal inheritance process (Moose 1.09 feature) Fix illegal option process, add tests for it Resolve a failing test file although some are skipped Resolve a failing test file Remove long deprecated methods in M::M::Attribute Checking in changes prior to tagging of version 0.64. Avoid compiler's warnings Add tiny tweaks stolen from Class::XSAccessor 1.07 Revert "Add tiny tweaks stolen from Class::XSAccessor 1.07" Use STATIC_INLINE, which will be introduced at 5.14.0 Split common stuff Support PERL_ONLY env var Resolve RT#61076 (improve error messages) 'alias' and 'excludes' in with() are deprecated Avoid warnings on compatibility tests Catch up Moose's change d21262bd42c2539c47e5d41e7506710ecd27ad65 Remove a duplicated macro: LooksLikeNumber Changelogging Switch to M::I::TestAssemble (xaicron++) Revert "Switch to M::I::TestAssemble (xaicron++)" Fix tests for Test::Builder2 Remove long deprecated methods Checking in changes prior to tagging of version 0.65. Fix a Changes log Update Moose compat version Cleanup Makefile.PL Fix LooksLikeNumber() macro Fix an error message for method modifiers Add test for method modifiers Workaround older perl's bug that caused segv by releasing CVs Better version checks for conflicting modules Fix for perl 5.6.2 Checking in changes prior to tagging of version 0.66. Oops! Add missing dependencies Checking in changes prior to tagging of version 0.67. Switch to use_xshelper(), which is provided by M::I::XSUtil 0.30 Remove XS method modifier stuff which depend on Data::Util. Tweaks for method modifiers Docs Checking in changes prior to tagging of version 0.68. Tweaks Inlucde xshelper.h to the dist even if it is generated by Makefile.PL (XSUtil) No import() for confess() Tweaks for method modifiers Docs and comments Tweaks Tests Workaround Test::Builder2's problem that it loads the XS stuff of 'Mouse', Add a test Update .gitignore Update MANIFEST.SKIP Docs Checking in changes prior to tagging of version 0.69. Make Delegations work with method modifiers Checking in changes prior to tagging of version 0.70. Test::Builder2 2.00_01 must be loaded first Skip threading tests on Test::More 2.00_01 Fix inlined method generations Add test requires again No "use metaclass" Checking in changes prior to tagging of version 0.74. gregor herrmann (1): Imported Upstream version 2.4.2 markstos (3): Document address of the public git repo. Improve documentation for type constraints. eep, don't advise contacting nothingmuch directly for a commit bit. sunnavy (7): make auto_deref also handles isa not only ArrayRef and HashRef, but also ArrayRef[Foo::Bar] and HashRef[Foo::Bar] update changes bump to 0.29 Moose role class has ->meta in method_list since 0.90, update for that small test update update Changes for 0.29 bump version to 0.30 tokuhirom (8): use Data::Util directly, instead of Class::Method::Modifiers::Fast. Switch to minilla. Include MANIFEST.SKIP for ignoring auto generated files from distribution tar ball. Added .travis.yml Remove xt/002-pod_spell.t. Minilla runs spelling test. We need to specify the directory name for c_source. Depended on latest ExtUtils::ParseXS(Older EU::PXS can't parse EU::ParseXS 3.23 does not relased yet! wu-lee (12): Correct error message to include 'Maybe' as implemented parametric type. Adjusted default 'isa' typeconstraint construction to check if the Type coercions should be added to the front of the list in Fixed a bug in the compiled constructor - it was invoking BUILD Added test for the correct BUILD order after immutable-ising a class. Added test for the correct application order when multiple coercions Changes to date added for wu-lee. Fixed bug in the immutable constructor. It now redispatches to Added latest bugfix to Changes. Whoops. This should have been included in the previous commit. Added metaclass cache accessor methods (straight from Class::MOP). Added Changes note about metaclass accessors. Ævar Arnfjörð Bjarmason (2): Moose used an incorrect cast at the C-level resulting in errors with >2**32 IV's on 32 bit systems The last commit didn't correctly catch 1 v.s. 1.5, use Perl's fmod function to check this 大沢 和宏 (34): add TODO added to coerce feature oops add test for coerce oops fixed bug, problem of coercer feature is moose compat added to coerce moose compat test case added to class_type add tests 't/*.t t/*/*.t'; move 80x tests to 800_shikabased added role_type on Mouse::TypeRegistry SKIP test case "Class::Method::Modifiers required for this test" more more moose way to type constraints remove trash added MouseX::Types, MouseX::Types::Mouse remove of a lot of copied document add mluti option with test add with qw( Role1 Role2 ) support optimized mv t/800_shikabased/007-create_class.t t/800_shikabased/008-create_class.t oops remove t/800_shikabased/007-create_class.t more optimized of TypeRegistry support of isa or ( isa => ' Str | Undef ') oops, revert of revision 6879 support of isa or ( isa => ' Str | Undef ') support MouseX::Types's isa or ( isa => Str | Undef ) micro optimized optimaized default values in constructor set instance to attributes default code optimize for constructor and attribute add immutable test Encapsulation implement to subtype's as is moose way pre load class in class_type oops, add testcase ( subtype 'Foo' => as 'Bar'; AND subtype 'Foo'; ) ----------------------------------------------------------------------- No new revisions were added by this update. -- Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-perl/packages/libmouse-perl.git _______________________________________________ Pkg-perl-cvs-commits mailing list Pkg-perl-cvs-commits@lists.alioth.debian.org | https://www.mail-archive.com/pkg-perl-cvs-commits@lists.alioth.debian.org/msg43925.html | CC-MAIN-2018-13 | refinedweb | 12,282 | 51.28 |
You’re a few months into writing a shiny new web app, and the team just settled on some new standards for data structures used for communication with the server.
You’ll need to refactor a few pages, but that’s not a big deal. Your team has been pushing good unit testing practices, and you’ve got great coverage for the affected code. You make the changes, verify that the unit tests still pass, maybe do a little manual testing for good measure, and then get everything committed.
A few days later, the bug reports start rolling in. This column no longer shows the right data. When I run Test Case 5 the Widget Editor doesn’t render correctly. The sort order for data on the home page is wrong.
They’re all for pages you modified, and nobody else has worked on those pages. You know your refactoring is to blame; but the unit tests were still passing! What the heck happened…?
Where Do Mock Objects Come From?
In a strongly-typed language like Java, you probably rely heavily on a mock object framework. Through the magic of gclib the framework dynamically creates subclasses of your various services, repositories, etc. and serves up instances of those subclasses to replace each dependency used by your subject code.
In JavaScript you don’t need all that. In fact, you can’t have all that, because nowhere do you definitively describe a “class” for your objects. So your unit testing tool may provide some mocking support (like the “spy” functionality in Jasmine), but in general your unit tests can just build objects with whatever members they expect the subject code to access.
Do you see the trap yet?
An Example in Two Languages
Your app handles orders. An order has a list of line items (each with a part number, quantity, and unit cost), a shipping address, and a shipping fee. To simplify the example, all costs are in whole dollars.
In Java you define the following classes:
public class Order { private List<LineItem> lineItems; private Address shipTo; private int shippingFee; // getters and setters ... } public class LineItem { private string partNumber; private int quantity; private int unitCost; // getters and setters ... }
You also have an OrderService with the following method:
public int calculateTotalCost(Order order) { int result = order.getShippingFee(); for (LineItem lineItem : order.getLineItems()) { result += lineItem.quantity * lineItem.unitCost; } return result; }
To test the OrderService, you’ll want to pass in Order instances with known cost values and check that the correct total is returned. A pure approach would use mock objects with scripted responses for the getters, but for simple data objects with “logic-less” getters and setters, you might elect to create real Order objects instead.
(If the test needed to verify that specific Order methods were used along the way, we’d have to use a mock regardless; but we just want to test for the correct result.)
Order order = new Order(); List<LineItem> lineItems = new ArrayList<LineItem>(); LineItem item1 = new LineItem(); item1.setQuantity(2); item1.setUnitCost(42); lineItems.add(item1); order.setLineItems(lineItems); order.setShippingFee(37); int result = orderService.calculateTotalCost(order); assertEquals(121, result);
Meanwhile, another team is putting together a proof-of-concept for a more JavaScript-centric architecture. Your Order class gets JSON bindings; the above test Order, for example, would serialize as:
{ "lineItems": [ "partNumber": "XL123" , "quantity": 2 , "unitCost": 42 ] , "shipTo": { /*...*/ } , "shippingFee": 37 }
They have an orderService.js containing a JavaScript version of calculateTotalCost():
var calculateTotalCost = function (order) { var result = order.shippingFee; for (var i = 0; i < order.lineItems.length; i++) { var lineItem = order.lineItems[i]; result += lineItem.quantity * lineItem.unitCost; } return result; };
They unit test their JavaScript code with Jasmine. If they need to pass in a simple data object, they build it on the spot. (Alternately, they might include helper functions in their test scripts to build these sorts of object.)
describe("calculateTotalCost()", function () { it("gives the total cost including shipping", function () { var order = { orderItems: [{ quantity: 2 , unitCost: 42 }] , shippingFee: 37 }; var result = calculateTotalCost(order); expect(result).toEqual(121); }); });
Now while the proof-of-concept is being evaluated, this logic has to be maintained in two places; but both teams agree that the test coverage is good (meaning, presumably, that there are more tests than we’ve shown here), so nobody’s too worried.
The Trap Is Sprung
Mid-way through the proof of concept period, you get a new requirement: Shipping costs need to be attributed to specific line items. The JavaScript team is off site, but you figure they can catch up; worst case their unit tests will alert them that something’s broken, right?
The Java team agrees that to avoid potential inconsistency, the shippingFee property will be removed from Order. There was some talk about minimizing interface changes by keeping the Order.getShippingFee() method (rewriting it to sum up the line items’ shipping fee values), but everyone agrees that the order-level shipping fee should be removed from the JSON bindings in any case.
You update the Java classes. The unit tests don’t build since they reference nonexistent methods, so you fix them. Then you notice something weird…
The unit tests are passing. All of them. Even the JavaScript ones.
The problem is that the JavaScript unit tests are making the same wrong assumptions about the Order structure as the code they’re meant to test. In this case, it would likely get caught through even moderately good team communication; but in a bigger system, it’s possible some code would slip through the cracks.
And anyway, isn’t the point of unit tests to alert you to a defect even if you somehow miss it?
So Where Should Mock Objects Come From
There are two ways to improve on this situation. Ideally we’d like to remove assumptions about object structure from the unit test code. If we can’t do that, maybe we can figure out how to validate those assumptions.
In Java, our unit tests validate their assumptions about the structure of an order by trying to compile (and/or run) against the Order and LineItem classes. In JavaScript, though, an object doesn’t have a class.
I noted above that the unit test scripts could contain helper functions for building data objects. We could make it a rule that all data objects must be obtained from helpers, and that the helpers must all be in a central library shared by all test scripts. Then updating that central library should cause all affected tests to fail. This would tend to isolate the assumptions in the test code. It does have its limitations. Ultimately our test codebase still contains unverified assumptions about the object structure, and there’s no guarantee that each assumption can be isolated to a single helper function.
Another option is to create an Order constructor. Of course, when we receive a JSON representation of an Order, it won’t have gone through that constructor; so to make this meaningful, we have to use the received JSON to construct a “real” Order object that our code will operate on, and then throw the JSON representation away.
At a glance, this feels wasteful; but then at some point in history many of the conventions we use to promote testability and maintainability were received with the same criticism. As a side benefit, our constructed object could use closures to conceal the internal state and provide access through getters and setters, providing some of the encapsulation we had in the Java world.
When we first got the new requirement that changed our definition of an Order, we’d update the Order constructor unit tests accordingly, which would lead us to fix the Order constructor itself. Once the constructor is fixed, our unit tests would fail when trying to call setShippingFee() on the order, much like the Java case, and we’d have test failures pointing to each bit of code we need to fix.
Final Thoughts
This is likely not the only solution, and it may not be the best one; let us know how you’ve addressed this issue in the comments below.
Regardless, this should serve as a reminder that languages like JavaScript give us more than enough rope to hang ourselves. As the scale of your JavaScript projects increases, it becomes more important to self-impose some of the discipline that isn’t enforced by the language.
— Mark Adelsberger, asktheteam@keyholesoftware.com
Good point.
“worst case their unit tests will alert them that something’s broken, right?”
I’m not sure unit tests are the right place to expect backwards-incompatible API changes to be caught. Unit tests intrinsically should do no AJAX calls, so this change wouldn’t and shouldn’t be caught at this level.
We’ve handled this same problem with two different mechanisms in projects I’ve been on before. They can be used together or independently, just depends on your budget.
The first is for the API to use versioning. Any time the API adds a field (non-breaking change), do a minor version increment. Any time the API removes a field (breaking change) do a major version increment. This does mean the API team must do a good job of communicating with consumers of the API, so these teams should have strong leads that are aware of this category of change.
The second is to implement integration tests. These tests by their nature can and should do AJAX calls. You can get into some neat BDD stuff with integration tests that are incorrect with unit tests.
I think the idea of centralizing the objects to factories will help some, but I’ve seen API versioning and integration tests as more holistic ways to catch the species of issues you’ve described.
Interesting points, but I have to disagree on a couple details.
It’s true that integration tests have an easier time spotting these problems, but whether this is an integration problem is a matter of interpretation. You could argue that the problem is in the interaction with the server, but I would argue that the client code as a unit unto itself is behaving incorrectly if it makes incorrect assumptions about its inputs. The bug doesn’t really depend on the fact that we happen to know we’ll get the input data via ajax; in fact if we’re writing reusable modules we don’t know if that will always be true.
Pragmatically bugs caught by unit tests are likely caught more inexpensively.
Note that none of the tests described above, including the variations that would catch the bug, make ajax calls; that’s the whole point of the mocking discussion. Mocks are supposed to accurately simulate inputs and dependencies, and if they do that then the test certainly can catch the problem without coupling to other parts of the system.
It definitely is true that using API versions can get you more meaningful diagnostics (presumably during integration testing) instead of random unexpected behaviors if the bug goes uncaught. It’s a good practice, but I see it as separate from the question of early detection during testing.
Ultimately I think we just disagree on how to classify a bug of this sort. I don’t think it’s a black-and-white issue, but I do believe this type of problem can and should be detected by a well-structured unit test. | https://keyholesoftware.com/2015/09/15/a-javascript-unit-test-trap/?replytocom=475700 | CC-MAIN-2019-04 | refinedweb | 1,906 | 62.07 |
The stack is a wonderfully simple data structure which despite its simplicity makes many powerful algorithms possible.
Some of the uses for a stack data structure in software development are:
- The Depth-First Search Algorithm
- Reverse Polish Notation for evaluating arithmetic expressions
- Syntax parsing for compilers and interpreters
- Storing function call frames inside the CPU
- Matching parentheses/braces in IDEs
- Reversing the order of data
- Recursion
- Undo/redo operation in word processors and browsers
- Low-level/assembly programming
Stacks are a very important data structure in programming and Computer Science. Think of a stack of plates. The top plate is the only easy access point, whether you want to add a new plate or remove an existing one… This leads to to the idea of a Last In First Out data structure.
A stack is a LIFO data structure – last in, first out.
You will see in this article how this essential property is useful.
The fundamental operations associated with the stack data structure are:
push(item)– push item to the top of the stack
pop()– Remove & return the top item
There are other methods too, which we will look at later, but
push and
pop are the essential, signature methods of a stack.
We use the term top to refer to the “access point” of the stack – i.e. the place where we either add or remove items. This is purely a conceptual tool though. In practice a stack is likely to be implemented using an array or list, both of which tend to be thought of a horizontal. It is an implementation detail as to whether the left- or right-hand end of a list/array is used as the top.
A Simple, Practical Implementation of a Stack in Python.
If you are more concerned about using a stack than in the details of its implementation, you can just go ahead and use a Python list, just being careful to only add or remove items from one end. An example is give below.
my_stack = [] my_stack.append("A") my_stack.append("B") my_stack.append("C") print("stack contents:", my_stack) while len(my_stack) > 0: print(my_stack.pop())
What do you expect the output to be?
stack contents: ['A', 'B', 'C'] C B A
A couple of points about the above code:
- We use a Python list as the basis for our stack
- The top of the stack is the right-hand end of the list
- The
pop()list operation does two things: it removes the item at the top of the stack, AND returns it.
As a side note, do you think this version using
for instead of
while would work in the same way?
my_stack = [] my_stack.append("A") my_stack.append("B") my_stack.append("C") print("stack contents:", my_stack) for item in my_stack: print(my_stack.pop())
stack contents: ['A', 'B', 'C'] C B
This is a cautionary tale against modifying python lists while iterating over them. The general rule of thumb is that you don’t modify a collection/array/list while iterating over it. Instead. use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.
A Python Class to Represent the Stack Data Structure
We are now going to write Python class to represent a stack for learning purposes, because the abstraction is helpful for gaining a deep understanding of how the data structure works, including using the appropriate terminology, such as
push and
pop. In practical situations, you might just use a list as described above. However, there is another reason to us a more detailed implementation such as a Python class. If your code needs a stack and you provide a list, there’s nothing stopping another programmer from calling insert, remove or other list functions that will affect the order of your stack! This fundamentally ruins the point of defining a stack, as it no longer functions the way it should.
Here is a Python class you can use for a stack, which abstracts the implementation details behind semantically named methods.
class Stack: def __init__(self): self.items = [] def is_empty(self): # return len(self.items) == 0 return not self.items def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def size(self): return len(self.items) def __str__(self): return str(self.items) if __name__ == "__main__": s = Stack() print(s) print(s.is_empty()) s.push(3) print(s) s.push(7) s.push(5) print(s) print(s.pop()) print(s) print(s.peek()) print(s.size())
Reversing a String Using a Stack in Python
One of the natural uses of a stack is to reverse data. You can see why if you get a bunch of plates, stack them on top of each other and then remove them one-by-one from the top. We are going to write a Python program to use this property of stacks to reverse the characters in a string.
Here’s a template for you to try to write this algorithm for yourself. You will only need the
push and
pop operations, but of course in the right place and with the right values. The goal is to reverse
string and print the result. If you run this code in the same file as the
Stack class from above, you will have access to that class. Otherwise you will need it import it using
from stack import Stack.
string = "ymedacupmoC htiw nohtyP nraeL" reversed_string = "" s = Stack() # Your solution here. for char in string: pass while not s.is_empty(): pass print(reversed_string)
string = "ymedacupmoC htiw nohtyP nraeL" reversed_string = "" s = Stack() for char in string: s.push(char) while not s.is_empty(): reversed_string += s.pop() print(reversed_string)
Array Based Implementation of the Stack Data Structure
Depending on why you are learning about stacks (for example it may be as part of a course such as A Level Computer Science in the UK), you may need to know how to implement a stack inside of an array, as opposed to using a dynamic data structure such as a Python list which resizes to fit your requirements. This can be done in different ways which entail varying levels of complexity and provide varying levels of pedagogical value depending on the context.
A common approach used by A Level exam boards is demonstrated by the code below. This approach involves keeping track of the position of the top and bottom of the stack using external “pointers” (not actual pointers as in
C for example, but variables containing the index positions.
# Simple array-based implementation of a stack in Python import random NULL = -1 # create space for indices 0-5 (6 slots) stack = [None] * 6 TOSP = NULL # Top of stack pointer BOSP = 0 # Bottom of stack pointer def print_stack(stack): """ Outputs the contents of the stack with bigger indices at top. """ for i in range(len(stack) - 1, -1, -1): # careful with second argument if i == TOSP: print(stack[i], "<---", "TOSP:", TOSP) else: print(stack[i]) print() def push(item): """ Pushes an item onto the stack. """ global TOSP # Chill it's OK here if TOSP < 5: TOSP += 1 stack[TOSP] = item else: print("Stack is full") print_stack(stack) def pop2(): """ Pops an item from the stack. Named to avoid conflict with built-in method. """ global TOSP, BOSP if TOSP >= BOSP: TOSP -= 1 print_stack(stack) else: print("The stack is empty.") print("TOSP:", TOSP, "BOSP:", BOSP) return stack[TOSP] # Add some items to stack print("Pushing to stack") print("#################") print() for i in range(1, 9): push(random.randint(1, 99)) # Separator print("Popping from stack") print("##################") print() # Remove items from stack for i in range(1, 8): pop2()
A Really Complex Implementation of a Stack in Python
If you are a fan of complexity for complexity’s sake and/or your exam board has decided that you should do it this way, there is another approach which involves storing the pointer to the next position inside the array as a data attribute, alongside the data “cargo”. I will post an example of this for reference, but with the caveat that I don’t believe it is a suitable approach for students at A Level and certainly doesn’t help them with understanding the abstract part of the topic called Abstract Data Types. There is some commentary on the pedagogical issues with this approach on the CS Educators Stack Exchange site.
# NullPointer should be set to -1 if using array element with index 0 NULLPOINTER = -1 #Declare record type to store data and pointer class Node: def __init__(self): self.Data = "" self.Pointer = NULLPOINTER def InitialiseStack(): Stack = [Node() for i in range(8)] TopOfStack = NULLPOINTER # set start pointer FreeListPtr = 0 # set starting position of free ist for Index in range(7): Stack[Index].Pointer = Index + 1 Stack[7].Pointer = NULLPOINTER # last node of free list return (Stack, TopOfStack, FreeListPtr) def Push(Stack, TopOfStack, FreeListPtr, NewItem): if FreeListPtr != NULLPOINTER: # there is space in the array # take node from free list and store data item NewNodePtr = FreeListPtr Stack[NewNodePtr].Data = NewItem FreeListPtr = Stack[FreeListPtr].Pointer # insert new node at top of stack Stack[NewNodePtr].Pointer = TopOfStack TopOfStack = NewNodePtr else: print("no space for more data") return (Stack, TopOfStack, FreeListPtr) def Pop(Stack, TopOfStack, FreeListPtr): if TopOfStack == NULLPOINTER: print("no data on stack") Value = "" else: Value = Stack[TopOfStack].Data ThisNodePtr = TopOfStack TopOfStack = Stack[TopOfStack].Pointer Stack[ThisNodePtr].Pointer = FreeListPtr FreeListPtr = ThisNodePtr return (Stack, TopOfStack, FreeListPtr, Value) def OutputAllNodes(Stack, TopOfStack) : CurrentNodePtr = TopOfStack # start at beginning of list if TopOfStack == NULLPOINTER : print("No data on stack") while CurrentNodePtr != NULLPOINTER : # while not end of list print(CurrentNodePtr, " ",Stack[CurrentNodePtr].Data) # follow the pointer to the next node CurrentNodePtr = Stack[CurrentNodePtr].Pointer Stack, TopOfStack, FreeListPtr = InitialiseStack() Stack, TopOfStack, FreeListPtr = Push(Stack, TopOfStack, FreeListPtr, "first item") Stack, TopOfStack, FreeListPtr = Push(Stack, TopOfStack, FreeListPtr, "second item") Stack, TopOfStack, FreeListPtr = Push(Stack, TopOfStack, FreeListPtr, "third item") Stack, TopOfStack, FreeListPtr, value = Pop(Stack, TopOfStack, FreeListPtr) print(value) OutputAllNodes(Stack, TopOfStack)
This has been an introduction to the stack data structure in Python. I hope you found it helpful. Any questions or comments, please put them in the comments section below and I will try to address them.
Happy computing! | https://compucademy.net/the-stack-data-structure-in-python/ | CC-MAIN-2022-27 | refinedweb | 1,709 | 60.65 |
Fixed typo in message from previous commit. It should be /etc/portage/categories;.
Updates
Initial import
novas0x2a's experimental inline::python code
Committing
Tagging the 0.14.0 release of g-cpan.
we don't need that var any longer :)
Bug 140084 - thanks Moshe!
Didn't like the way search was defaulting. Still search CPAN (but note if we found an ebuild for it)
Updating Makefile for new deps
Behold! rc3 is on the threshold. And so we shall celebrate our independence!
* Logging added * Cleaned up the getAvailableVersions checking (less time) * -u now support individual packages
Minor fixes to dep writing
rc3 work
bug 135783
Bug 134781 - RDEPEND=DEPEND line in generated ebuilds
This is it - all podd'd up!
Code updates.
Updates to Makefile.PL
SuperLag noticed no failure notices for modules not in CPAN - fixed :)
unimportant typo fix
Fixed tests; fixed bug where -a wasn't working anymore; fixed bug where g-cpan would skip ebuilds that already existed (mainstream g-cpan will continue to install them)
Major work completed. Need to work on tests and validate documentation.
Evening commit. Just need to get upgrade working, fix tests, and stress it.
Evening sanity check. We are now generating ebuilds correctly and with all deps generated *and* listed!
Sanity commit. Almost there. Need to work out why it's not skipping perl as a dep; need to finish the ebuild writing segment to include perl-gcpan/<new-dep-ebuild>; need to get sleep :)
Sanity commit, need a quick break.
Sanity commit. I've begun working on culling together the information for the ebuild generation.
Sped up the finding of files considerably. From minutes to an average of 17seconds depending on box.
I broke it. Maybe SQLite?
Last commit while at work, just going over PBP and Critic output
More code cleanups. Will be removing CONSTANTS, an idea that didn't pan out. Searching now works (nothing else yet); finally moved the clean_up code to the END{} block Sniper always wanted; UI::Console work.
Moved Ebuild.pm to Portage.pm
Prepping
perltidy
Only run CPAN tests if we have a configured CPAN::Config
Begun unit testing of new module space.
Nightly commit
Final move/adds I think
Removing man, adding first test
Renaming to the new filename
Reorganization galore.
mcummings "play around" version
Removed additions to ebuild to deal with extutils-autoinstall - in the eclass now
Updates, working copy again.
The g-cpan parts are still a work in progress. The up2date-ng is all ian's work, I'm just tossing it into svn for tracking and maintenance :)
Updates
Adding a snippets dir for storing pieces that are being worked on for later inclusion.
pretend shouldn't block other actions
Making a copy prior to some new edits and fixes
import
Building the g-cpan dir structure | https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-perl/g-cpan/?sortby=rev&view=log | CC-MAIN-2015-22 | refinedweb | 468 | 65.73 |
This bug reports a problem for pk12util that is also reported against PSM
in bug 265991.
When a user "exports" a cert and private key from Microsoft Windows' key
store, the "Certificate Export Wizard" asks the user for a password for
the PFX file being created. The dialog says:
To maintan security, you must protect the private key by using a password.
Type and confirm a password.
[ ]
[ ]
[ <Back ] [ Next> ] [Cancel ]
However, the user can merely click Next> without entering any passwords.
In this case, the Wizard creates a pfx file encrypted with an empty password.
However, IMO, it does not strictly follow the PKCS12 standard for that empty
password. The PKCS12 standard says:
In this specification however, all passwords are created from BMPStrings
with a NULL terminator. This means that each character in the original
BMPString is encoded in 2 bytes in big-endian format (most-significant
byte first). There are no Unicode byte order marks. The 2 bytes produced
from the last character in the BMPString are followed by two additional
bytes with the value 0x00.
To illustrate with a simple example, if a user enters the 6-character
password "Beavis", the string that PKCS #12 implementations should treat
as the password is the following string of 14 bytes:
0x00 0x42 0x00 0x65 0x00 0x61 0x00 0x76 0x00 0x69 0x00 0x73 0x00 0x00
According to that standard, the UCS2 password from which the key is computed
includes a trailing 2-byte NULL character, and is one character longer than the
number of characters in the user's password. So, when the entered password is
empty (zero characters long), the UCS2 password still should contain a single
2-byte UCS2 NULL character. That's how NSS handles an empty password.
But when Microsoft Window's certificate export wizard handles an empty password,
it computes the key from a zero-byte string, one that does not include the
trailing 2-byte UCS2 NULL character. So, it computes a different key for
an empty password than NSS does, and that is why NSS cannot import a PFX
file created by MS's wizard with an empty password. Note that MS's wizard
does include the trailing NULL when the password is not empty, so only
empty passwords are handled in this exceptional manner. MS and NSS compute UCS2
passwords the same way, except for empty passwords.
I verified (in the debugger) that by detecting the empty password case, and
eliminating the trailing 2-byte NULL character from the UCS2 password, then
NSS was able to import the PFX file generated by MS's wizard with an empty
So, if we want to be able to import PFX files created by MS's wizard with
an empty password, we must drop the trailing NULL character when computing
the PBE key. But if we do that, we will no longer be able to import P12
files created with mozilla or pk12util with an empty password, because those
tools create PKCS12 files with the trailing NULL character always intact.
I suspect that MS's cert import wizard also cannot import P12 files created
by mozilla or pk12util with empty passwords, for essentially the same reason,
namely that empty passwords are encoded differently.
Some possible options include:
a) look at the suffix of the file name being imported or exported. If it is
"pfx" and the user enters an empty password, drop the trailing NULL. Otherwise,
do not drop the trailing NULL. PFX files with empty passwords are then
importable by both NSS and MS, but P12 files with empty passwords are not.
b) when importing with an empty password, try it with the trailing NULL, and
if that fails, try it again without the trailing NULL. Unfortunately, this
means doing the entire PKCS12 import operation twice. Continue to create
PKCS12 files with empty passwords as we have done before. Solves the problem
for import by NSS only, not for import by MS Wizard.
c) Document that a non-empty PFX file password is always required when using
p12/pfx files to transport keys between windows and mozilla products. Solves
problem in both directions.
d) Like b above, trying both ways of encoding empty passwords for import, but
for export, abandon the way NSS has previously handled empty passwords, and
switch to doing it the MS way. Solves exchange of PFX/p12 files between
MS Wizard and new NSS, but creates problem for old NSS products that would
import a p12 file with an empty password from the new NSS.
PSM duplicates a large part of NSS's PKCS12 code. If it duplicates the code
that converts passwords to UCS2 for PBE computation, then whatever we do to
NSS (if anything) must also be done to PSM.
Note, a sample PKCS12 file that demonstrates this problem is attached to
bug 265991, which is now reportedly fixed in PSM. The attachment is
Neil, I'm giving the pk12util bugs to you.
PSM bug 265991 is not yet fixed but there is already
a working patch attached to the bug report.
Created attachment 202457 [details] [diff] [review]
patch to retry pfx import created with zero-length passwords
This is the sort of patch that looks substantial because it shifts a bunch of code right so as to retry through the import code block in the case of a null password. The code to convert the supplied password to Unicode ensures that the Unicode version has a (UCS-2) NULL at the end. So a null unipw will have length 2 which is changed to 0 for the retry.
Comment on attachment 202457 [details] [diff] [review]
patch to retry pfx import created with zero-length passwords
I think this patch is correct, and so (assuming that it has been
tested with the provided test .p12 file), I give this r=nelson,
but I'd like to request one change. Instead of
>+ for (trypw=PR_TRUE; trypw;) {
>+ trypw = PR_FALSE; /* normally we do this once */
[...]
> }
I suggest
>+ do {
>+ trypw = PR_FALSE; /* normally we do this once */
[...]
>- }
>+ } while (trypw);
Created attachment 203860 [details] [diff] [review]
better fix for the problem
Incorporated your suggestion, Nelson. This looks more complicated than the last patch because the code to get the password and read the PKCS12 file was carved out of Import() and placed in a new function. This way list and import use the same function. Also a small fix to cmd/lib/secpwd.c to initialize the pw buffer to null so that if the input is at EOF the utitilty doesn't do funny things.
Comment on attachment 203860 [details] [diff] [review]
better fix for the problem
Let's discuss this. I have two sets of issues:
1) I found several paths in the code (both in the patched code and the orginal) that goto loser without setting rv to SECFailure, causing the function to return SECSuccess when it should return SECFailure.
2) The elimination of the swapunicode variable.
Is this code correct on little-endian systems?
Created attachment 209937 [details] [diff] [review]
previous patch with fixed glitch in unicode conversion
The only change here is to restore the way the program handled unicode conversion. Thanks for picking up on that. We may want to change the way this does unicode conversion someday but that would need some more study.
Nelson, I believe the places you mention not setting rv are all taking advantage of the fact that it's initialized to SECFailure.
Created attachment 210404 [details] [diff] [review]
Previous patch plus fix to return proper error code (checked in)
Nelson, besides the return code problem you pointed out this patch incorporates your suggestion for ...ReadFile() to return the decode context pointer on success and NULL on failure. This makes sense in this case because the function prints error messages itself rather than merely passing success/fail and a reason code. (It still sets the reason code though.)
These patches affect the list and import options by creating a new function that reads and verifies the PKCS12 file for both.
This patch also fixes a problem in cmd/lib/secpwd.c when end-of-file is encountered while reading a password. It was returning uninitialized data. This change affects modutil as well as pk12util.
Targetting to 3.12
Julien, do you think we need this fix in 3.11.1 ?
Comment on attachment 210404 [details] [diff] [review]
Previous patch plus fix to return proper error code (checked in)
r=nelson.bolyard for the trunk.
Checking in cmd/pk12util/pk12util.c;
/cvsroot/mozilla/security/nss/cmd/pk12util/pk12util.c,v <-- pk12util.c
new revision: 1.33; previous revision: 1.32
done
Checking in cmd/lib/secpwd.c;
/cvsroot/mozilla/security/nss/cmd/lib/secpwd.c,v <-- secpwd.c
new revision: 1.14; previous revision: 1.13
This fix should go into 3.11.1.
There needs to be a nightly QA test that verifies that this is still working.
part of tools.sh.
Attachment 174323 [details] is a PFX file with no password, for testing.
Comment on attachment 210404 [details] [diff] [review]
Previous patch plus fix to return proper error code (checked in)
Backported to trunk
lib/secpwd.c; new revision: 1.13.28.1; previous revision: 1.13
pk12util/pk12util.c; new revision: 1.32.2.1; previous revision: 1.32 | https://bugzilla.mozilla.org/show_bug.cgi?id=277334 | CC-MAIN-2016-50 | refinedweb | 1,547 | 62.68 |
Dumping core died. A core dump is essentially a dump of all memory in your program’s virtual address space: stack, heap, code and everything else.
On most systems, though, you won’t get a core dump when you crash, where a crash can come from a segfault (or any other signal), a call to abort(2) (such as via a failed assertion), a call to terminate() (such as via throwing an uncaught exception), or other similar avenues. Core dumps are rather large (after all, it’s all of the memory from the process) — they can easily be tens or hundreds of megabytes, even for simple programs, due to a large number of shared libraries being loaded. Your hard drive would fill up very quickly if every program that crashed left a core dump.
If you’re just poking around in the shell, you can enable core dumps with ulimit(1) to raise the core dump file size limit from 0 (the default) to something non-zero such as unlimited. This will cause any crashing programs spawned by that shell to leave core dumps. For example:
$ cat crash.c int main(void) { *(int *)1 = 2; // cause a segfault } $ gcc crash.c -o crash $ ./crash Segmentation fault $ ulimit -c unlimited $ ./crash Segmentation fault (core dumped)
Where the core dump ends up depends on your operating system. By default, Linux puts it in a file named core in the current working directory, and Mac OS X puts it in a file named /cores/core.<PID>, where <PID> is the process ID of the process that crashed. The exact name and location may vary by flavor and version of OS. See the core(5) man page for detailed discussion of core files on Linux.
Ok, so that’s all well and good if someone has the good nature to run ulimit before running your program, but few (if any) people will do so. If you want to say, “No really, I want core dumps!, you can call setrlimit(2) to set the limit for yourself and any child processes (which is all ulimit really does). Just make sure not to annoy your users by filling up their hard drives with core dumps. Which of course you won’t do because your code is perfect and never crashes anyways.
You’ve gone through the trouble of creating a core dump, but when your program crashes in some far away land, how do you actually get your hands on the core dump? You could ask your users to email it to you, but they’re not going to do that. They’re just going to complain on the Internet that your software sucks and that people shouldn’t use it. Some operating systems have a nice Crash Reporter or Error Reporting Service, but those send crash reports to first parties, something you might not want, and getting the crash data back to you is far from trivial.
One solution is to install your own error handlers in-process to catch things such as segfaults and instead of letting the operating system handle the error, you handle it yourself: you do your own stack trace, grab important data such as filenames, optionally pop up a UI asking the user if he wants to send an error report and for supplemental information, and sending the crash report your way. This is a lot of work, and it’s also dangerous: if your program has crashed, there’s no telling what state it’s in. Trying to do something like sending an email from a signal handler could easily fail — your heap might be corrupted, so you could crash again the moment you do something as mundane as try to allocated some memory. If you decide to go this route, a good place to start would be with signal(2)/sigaction(2) (*nix and OSX) or Structured Exception Handling (Windows).
A solution that I like better is out-of-process. Just let the process crash and dump core as before, but this time we’ll have a watchdog process running. The watchdog just waits for the main process to exit (normally or abnormally); if it sees an abnormal exit and a core dump, then it sends off the crash report into the ether. This is much safer, since you don’t have to worry about things such as a corrupted heap when sending a crash report. The only downside to this you now have twice as many processes running.
Here’s a full example of a watchdog with core dumps. The program forks, with the parent as the watchdog. The child intentionally crashes, and then the parent grabs the core dump if one was made.
#include <errno.h> #include <stdio.h> #include <string.h> #include <sys/resource.h> #include <sys/wait.h> int main(int argc, char **argv) { // Try to enable core dumps struct rlimit core_limit; core_limit.rlim_cur = RLIM_INFINITY; core_limit.rlim_max = RLIM_INFINITY; if(setrlimit(RLIMIT_CORE, &core_limit) < 0) fprintf(stderr, "setrlimit: %s\nWarning: core dumps may be truncated or non-existant\n", strerror(errno)); int status; switch(fork()) { case 0: // We are the child process -- run the actual program *(int *)1 = 2; // segfault break; case -1: // An error occurred, shouldn't happen perror("fork"); return -1; default: // We are the parent process -- wait for the child process to exit if(wait(&status) < 0) perror("wait"); printf("child exited with status %d\n", status); if(WIFSIGNALED(status) && WCOREDUMP(status)) { printf("got a core dump\n"); // find core dump, email it to your servers, etc. } } return 0; }
If you compile and run this program, you’ll get a core dump from the child process, which the parent process will detect, and it can then do whatever it wants with it. Email it to you, upload it to a server, analyze it and trim it down before doing those, or anything else you can write code to do. All from the safety of an uncrashed process. If you run ulimit -c 0 before running this program, you’ll see the warning about setrlimit failing and you won’t get a core dump. This is because, if you look at the documentation for setrlimit, you’ll see that the soft limit can never exceed the hard limit, and the hard limit can only be decreased by unprivileged processes.
So there you have it. You now have a way to have your software dump core when it crashes and send those core dumps back to you without any extra hassle on the user’s part. Though depending on who your users are, it may still be a good idea to ask them if they want to send a crash report before actually doing so, since core dumps can easily contain private information in them. If you had anything like usernames or passwords in memory anywhere in your process, they’ll be in the core dump. So keep that in mind and take appropriate measures to protect users’ privacy. Encrypt the core dump if necessary. Maybe even attach a cryptographic signature to ensure authenticity.
Links for further enrichment:
- Mac OS X debugging magic, lots of great debug-fu for Mag OS X
- XCrashReport (part 2) (part 3) (part 4), a nifty in-process crash reporter for Windows
- And for your amusement: Kill -9 Bill | http://adamrosenfield.com/blog/page/3/ | CC-MAIN-2016-36 | refinedweb | 1,219 | 67.89 |
I'm looking to setup AMT in my environment. We decided to use the SCCM add-on with RCS integration. I have two major security concerns with this: First, the instructions in the Intel(R)_SCS_Addon_SCCM_2012.pdf call for giving the Operations Administrator role to the Domain Computers group. That's was a huge security concern to me, since the Operations Administrator role is an extremely powerful one. I was able to find advice on this from another discussion that I found on this site.
This brings me to the second issue, on which I have yet to make any progress. In section 2.7 of the guide, it gives the option to run the packages used by the add-on either as the system account on the host computer (default) or designate an account for running the package. If I go with the system accounts, then it requires me to give every computer Remote Enable rights to the site_<sccm site code> namespace in WMI. This is opening up my SCCM infrastructure to any person who can run something as the system account on any host computer, which is not very difficult to do, so this is not a good option.
The second option (using a dedicated account) also has problems, as I need to grant this account admin rights to all of my hosts and open up the same WMI namespace to it. This is fine so long as I can keep this one account safe. But for this to work, the add-on has to use the “Run this step as the following account” option in the task sequence and store its credentials there. This is a problem, because that password can easily be extracted from any host computer which is able to run the task sequence. In order to verify this, I ran a test of it and was able to get the password for this account from a host, using one very simple step followed by a one-liner. I'm not going to post that here for obvious reasons. This is why Microsoft has multiple warnings about accounts used to “run as” from a task sequence. This issue presents a huge concern because the instructions are calling for this account to have admin rights to all of my hosts, plus the ability to remotely connect to SCCM's WMI namespace. I don't want to leave such a powerful account so exposed.
So, given all of the above, does anybody know of a reasonably secure way to handle this? This can't be the only way to make this work. Of all the companies using AMT, somebody else must have already discovered this problem and developed a more secure method.
Thank you,
-Joe | https://communities.intel.com/thread/59751 | CC-MAIN-2018-43 | refinedweb | 459 | 69.62 |
(2012-11-05 01:03)backspace Wrote: Hi Rob,
I dont know much about python (actually all I know is that is code) so a point or two in the right direction would be greatly appreciated
(I learn best by taking some code that works and pulling it apart and seeing why it works, maybe changing a bit here and there to see what happens)
(as I don't know much about py) would something like this work?
<job name="Test" expression="30 * * * *"command="Playlist.Clear","(Partymode(special://profile/playlists/music/playlist1.xsp))" show_notification="true" />
<job name="Playlist" command="RunScript(ABSOLUTE PATH TO/playlist.py)" expression="30 * * * *" show_notification="true" />
import xbmc
import json
import urllib
#function to execute the JSON calls
def getJSON(query,params):
#execute the json request
json_response = xbmc.executeJSONRPC('{ "jsonrpc" : "2.0" , "method" : "' + query + '" , "params" : ' + params + ' , "id":1 }')
json_object = json.loads(json_response)
#return nothing if there was an error
if(json_object.has_key('result')):
return json_object['result']
else:
return None
playlist_id = '0' #audio is always 0
player_id = '0' #audio player is always 0
playlist_file = 'Test'
#stop whatever is playing
getJSON('Player.Stop','{"playerid":' + player_id + '}')
#clear the playlist
getJSON('Playlist.Clear','{"playlistid" :' + playlist_id + '}')
#set partymode
getJSON('Player.SetPartymode','{"playerid":' + player_id + ',"partymode":true}')
#open the new playlist
getJSON('Player.Open','{ "item": { "partymode": "special://musicplaylists/' + playlist_file + '" } }')
#start the playlist (this may not be necessary, the OPEN method might call it for you)
getJSON('Player.PlayPause','{"playerid":' + player_id + '}')
(2012-11-05 17:48)robweber Wrote: Some modifications might be necessary to get it to work for you but this is a good working start.
(2013-01-26 01:02)Kr0nZ Wrote: Here my first attempt at creating a GUI for this:
Keep in mind this is the first time I've ever tried xbmc skinning, I used the gmail checker addon as a base
So far you can add/delete/modify cron jobs
and my code is here on github (GUI branch)
Also the plugin wants to open a folder, I can't see where in the code where it does this, maybe someone knows why?
The gmail addon doesn't try to open any folders it just loads straight to the window
09:24:33 T:1296 ERROR: Control 120 in window 13000 has been asked to focus, but it can't | http://forum.kodi.tv/showthread.php?tid=124888&page=2 | CC-MAIN-2017-04 | refinedweb | 381 | 50.26 |
A column by Micah Dubinko.
Is XML 2.0 Under Development?
By Micah Dubinko
In Micah Dubinko's return to the XML Annoyances banner, he speculates as to whether the W3C is already considering whether to start work on XML 2.0. Read this piece and decide for yourself. [Jan. 10, 2007]
By Micah Dubinko
Micah Dubinko takes aim at the legion of annoyances caused by XML namespaces. [Nov. 8, 2006]
JSON on the Web, or: The Revenge of SML
By Simon St. Laurent
Simon St. Laurent looks back to see if we can all learn a lesson or two: were there signs early on in the life of XML that something like JSON would eventually do very well as a Web data format? [Jul. 5, 2006]
By Simon St. Laurent
Simon St. Laurent steps up to ask which of the competing visions for the next stage of the Web's development have borne fruit, including the latest contender: Web 2.0 and AJAX. [Mar. 15, 2006]
By Micah Dubinko
In his latest XML Annoyances column Micah Dubinko examines a common force behind the good and bad aspects of XML. [Feb. 1, 2006]
XML 2005: Tipping Sacred Cows
By Micah Dubinko
In his latest XML Annoyances column, Micah Dubinko reports from last week's XML 2005 conference in Atlanta. [Nov. 23, 2005]
By Micah Dubinko] | http://www.xml.com/pub/at/38 | CC-MAIN-2017-13 | refinedweb | 225 | 74.49 |
J.
Overview of the Excel XML Tools Add-in Excel XML Tools Add-in Requirements Installing and Setting Up the Excel XML Tools Add-in Using the Excel XML Tools Add-in Conclusion Additional Resources.
The Excel XML Tools Add-in (.xla) requires the XML mapping feature, which is included in any of the following programs in the Microsoft Office System:
The XML mapping feature is not included in the following versions:
This Excel add-in is not compatible with these programs in the Microsoft Office System.
To install the add-in, complete the following steps:
Note To remove this add-in, repeat this procedure, but clear the XMLTools box..
To convert a range to an XML list, complete the following steps:.
This task displays the XPath, XSD DataType, Excel display format, and any namespaces for the XML map of the active cell. This is helpful because much of this information is only available from reading the schema file.
The Excel 2003 XML Tools Add-In version 1.1 helps you, the developer, make working with XML maps, cells, and ranges much easier. It facilitates the creation of XML lists, XSD files, and other tasks related to XSD and XML files.
The following articles can help you develop more custom XML solutions using Excel: | http://msdn.microsoft.com/en-us/library/aa203739%28office.11%29.aspx | crawl-002 | refinedweb | 214 | 61.16 |
I am having a really difficult time understanding the logic of how a function and a list interact. Take these examples:
def list_function(x): return x n = [3, 5, 7] print list_function(n)
n = "Hello" def string_function(s): return s + "world" print string_function(n)
How do n list and function interact? I knew the answer but don’t how it works I just have the syntax memorized but I feel I need to really get what’s happening instead of memorizing. If someone could give a for dummies explanation of the logic so I can wrap my head around it I would be greatly indebted.
Thanks! | https://discuss.codecademy.com/t/please-help-with-function-logic/293212 | CC-MAIN-2018-51 | refinedweb | 106 | 54.56 |
I use Python and Google as the primary examples in this article, although this idea could apply to other languages and commercial services. I picked Python because it is easy to read, powerful, and extensible. I picked Google because it has turned into a Bell Labs for software development and has hired many leading open source developers. Google could make an important contribution to software development, much as Sun did by promoting Java and Microsoft did by promoting Visual Basic.
I first wrote about this idea in Dr. Dobbs Journal in 1998. That article, entitled "Concept Oriented Programming," proposed extending object-oriented programming languages with a DNS-like system that would store reusable code, and that would enable developers to write tiny programs that load libraries as needed from the cloud. My original article is somewhat dated now, so I decided to revisit it in this O'Reilly piece, and to show some specific examples of how a hyperlinked version of Python would look. While this article is not a detailed technical specification, it clearly shows how this can be implemented. (Shortly before publication, I learned of UrlImport, a Python module that implements part of what I describe in this article.)
In plain English, you could write very lightweight programs that would load most of their underlying modules on the fly. Such a program might look like this:
import /widgets/foo.py as=foo
import as=popup crc=a6771234
x = foo.widget()
x.say("Hello World")
y = popup.widget()
y.say("Well Hello There")
What I've done in this imaginary program is simple. In the first import statement, I load a locally stored library, just like a normal import. In the second import statement, I load a library from a network repository. I instantiate objects from each of these libraries and tell them to print a "Hello World" message.
The details of how the networked import command works are less important than what it enables you to do. Properly implemented, it will mean that you can write tiny programs that will grab whatever underlying code they need at runtime. No more bloated distributable packages. There are no more install scripts. Just send your program and say "run mywidget.pyc, have fun!".
One of the goals of this manifesto, or whatever you want to call this, is to have a networked programming language baked into every box. The runtime environment will be built in, much as Python is preloaded on Mac OS X.
With most languages, the standard library becomes ever more bloated with each new release. With this technique, we can radically downsize the runtime environment. All we need is the interpreter (updated to recognize network imports and a couple of other functions). It can get everything else it needs from networked repositories.
The goal is to make the runtime environment so small that it can be a part of any computing device.
Python's "Batteries Included" philosophy enables developers to do quite a lot without venturing beyond the standard libraries. With a fully networked language, we no longer need to distribute a large standard library with the runtime environment or applications. Everything you need will be stored in the public network.
The distinction between the standard library and extras developed by other authors will also go away. With today's languages, it is usually best to stay with the standard libraries if at all possible, to avoid headaches when you share the application with other users, to install it on other machines, etc. Distribution and installation headaches can be a powerful disincentive to use third-party code.
With a networked language, there will be no build or install process. You'll just share an application and it will get what it needs on the fly.
While the networked import function could load from a simple HTTP file store or similar service (this will work fine), we could take this a step further to create a DNS namespace for code. This section is a bit of a sidebar to this article, so if you think this is too forward-looking and it's a distration to you, skip forward to the next section.
import
We could create a .code (or .turing) top-level domain. From there, we could create a DNS namespace for objects that works much like the namespace for Internet hosts. The second-level domains would be reserved for major language branches, for example, *.py.turing. Tertiary domains would go to anyone who wanted to host a code repository, while a std subdomain would be reserved for official releases and libraries. (For example, the official standard Python libraries would live in std.py.turing.)
Using this system would be as easy as including an import statement in a program, and might read as:
import as=doodad crc=aa123456
The runtime engine, when it sees an import statement like this, will do a standard DNS lookup and go grab the file from the appropriate server, just as in the earlier example. The idea here is to create a persistent address space for reusable code.
This may or may not happen, and in any case, the import statement can pull modules from any domain. Commercial organizations will likely host early implementations of this, but it's good to know that we can move in this direction if the idea catches on.
Pages: 1, 2, 3, 4
Next Page
Sponsored by:
© 2014, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.linuxdevcenter.com/pub/a/python/2007/01/18/why-i-stopped-coding.html?page=2 | CC-MAIN-2014-15 | refinedweb | 928 | 63.09 |
2,MapReduce
2.1. Introduction to MapReduce
The core idea of MapReduce is "divide and conquer", which is suitable for a large number of complex task processing scenarios (large-scale data processing scenarios).
Map is responsible for "dividing", that is, dividing complex tasks into several "simple tasks" for parallel processing. The premise of splitting is that these small tasks can be calculated in parallel and have little dependency on each other.
Reduce is responsible for "closing", that is, summarizing the results of the map phase globally.
Figure: MapReduce thought model
2.2. Can write Wordcount
- Define a mapper class
//First define the types of four generics //keyin: LongWritable valuein: Text //keyout: Text valueout:IntWritable public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{ //Life cycle of map method: the framework is called every time it passes a row of data //key: the offset of the starting point of this line in the file //value: the content of this line @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { //Get a row of data and convert it into string String line = value.toString(); //Cut this line out the words String[] words = line.split(" "); //Traverse the array and output < word, 1 > for(String word:words){ context.write(new Text(word), new IntWritable(1)); } } }
- Define a reducer class
//Life cycle: the reduce method is called once every kv group passed in by the framework @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { //Define a counter int count = 0; //Traverse all v of this set of kv and add it to count for(IntWritable value:values){ count += value.get(); } context.write(key, new IntWritable(count)); } }
- Define a main class to describe a job and submit it
public class WordCountRunner { //Describe the information related to business logic (which is mapper, which is reducer, where is the data to be processed, where is the output result...) as a job object //Submit the described job to the cluster to run public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job wcjob = Job.getInstance(conf); //Specify the jar package where this job is located // wcjob.setJar("/home/hadoop/wordcount.jar"); wcjob.setJarByClass(WordCountRunner.class); wcjob.setMapperClass(WordCountMapper.class); wcjob.setReducerClass(WordCountReducer.class); //Set the data types of the output key and value of our business logic Mapper class wcjob.setMapOutputKeyClass(Text.class); wcjob.setMapOutputValueClass(IntWritable.class); //Set the data types of the output key and value of our business logic Reducer class wcjob.setOutputKeyClass(Text.class); wcjob.setOutputValueClass(IntWritable.class); //Specify the location of the data to process FileInputFormat.setInputPaths(wcjob, "hdfs://hdp-server01:9000/wordcount/data/big.txt"); //Specifies the location where the results after processing are saved FileOutputFormat.setOutputPath(wcjob, new Path("hdfs://hdp-server01:9000/wordcount/output/")); //Submit this job to the yarn cluster boolean res = wcjob.waitForCompletion(true); System.exit(res?0:1); }
2.3,Combiner
Each map may produce a large number of local outputs. The function of Combiner is to merge the outputs at the map end first, so as to reduce the amount of data transmission between the map and reduce nodes and improve the network IO performance.
For example, for the wordcount provided with hadoop, value is a superimposed number,
Therefore, the value of reduce can be superimposed as soon as the map is completed, instead of waiting until all the maps are completed.
- Specific use
custom Combiner: public static class MyCombiner extends Reducer<Text, LongWritable, Text, LongWritable> { protected void reduce( Text key, Iterable<LongWritable> values,Context context)throws IOException, InterruptedException { long count = 0L; for (LongWritable value : values) { count += value.get(); } context.write(key, new LongWritable(count)); }; }
- Add in main class
Combiner set up // Set Map protocol Combiner job.setCombinerClass(MyCombiner.class); See after execution map Output and combine The input statistics are consistent, while combine Output and reduce The input statistics are the same.
2.4,partitioner
During MapReduce calculation, sometimes the final output data needs to be divided into different files. For example, if it is divided according to provinces, the data of the same province needs to be put into one file; According to gender, the data of the same gender need to be put into one file. The class responsible for partitioning data is called Partitioner.
- The source code of HashPartitioner is as follows
package org.apache.hadoop.mapreduce.lib.partition; import org.apache.hadoop.mapreduce.Partitioner; /** Partition keys by their {@link Object#hashCode()}. */ public class HashPartitioner<K, V> extends Partitioner<K, V> { /** Use {@link Object#hashCode()} to partition. */ public int getPartition(K key, V value, int numReduceTasks) { //By default, the hash value of key and the maximum value of int on are used to avoid data overflow return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks; } }
- key and value respectively refer to the output of Mapper task. numReduceTasks refers to the set number of Reducer tasks. The default value is 1. Then the remainder of any integer divided by 1 must be 0. That is, the return value of the getPartition(...) method is always 0. That is, the output of Mapper task is always sent to a Reducer task, and can only be output to one file in the end.
Specific implementation:
import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Partitioner; public class FivePartitioner extends Partitioner<IntWritable, IntWritable>{ /** * Our demand: partition according to whether it can be divided by 5 * * 1,If the remainder of dividing by 5 is 0, put it in partition 0 * 2,If the remainder of dividing by 5 is not 0, put it in the 1 partition */ @Override public int getPartition(IntWritable key, IntWritable value, int numPartitions) { int intValue = key.get(); if(intValue % 5 == 0){ return 0; }else{ return 1; } } }
- Add the following two lines of code to the main function:
job.setPartitionerClass(FivePartitioner.class); job.setNumReduceTasks(2);//Set to 2
2.5 execution process of MapReduce
Detailed process
Map phase
l the first stage is to logically slice the files in the input directory one by one according to certain standards to form a slice planning. By default, Split size = Block size. Each slice is processed by a MapTask. (getSplits)
l the second stage is to parse the data in the slice into < key, value > pairs according to certain rules. The default rule is to parse each line of text content into key value pairs. Key is the starting position of each line (in bytes), and value is the text content of the line. (TextInputFormat)
l the third stage is to call the map method in the Mapper class. For each < K, V > parsed in the previous stage, the map method is called once. Zero or more key value pairs are output each time the map method is called.
l the fourth stage is to partition the key value pairs output in the third stage according to certain rules. By default, there is only one zone. The number of partitions is the number of Reducer tasks running. By default, there is only one Reducer task.
l the fifth stage is to sort the key value pairs in each partition. First, sort by key. For key value pairs with the same key, sort by value. For example, for three key value pairs < 2,2 >, < 1,3 >, < 2,1 >, the key and value are integers respectively. Then the sorted results are < 1,3 >, < 2,1 >, < 2,2 >. If there is a sixth stage, enter the sixth stage; If not, output directly to a file.
l the sixth stage is the local aggregation processing of data, that is, combiner processing. Key value pairs with equal keys call the reduce method once. After this stage, the amount of data will be reduced. It is not available by default at this stage.
reduce phase
l in the first stage, the Reducer task will actively copy its output key value pairs from the Mapper task. There may be many Mapper tasks, so Reducer will copy the output of multiple mappers.
l the second stage is to merge all the local data copied to Reducer, that is, merge the scattered data into one large data. Then sort the merged data.
l the third stage is to call the reduce method for the sorted key value pairs. The reduce method is called once for key value pairs with equal keys, and each call will produce zero or more key value pairs. Finally, these output key value pairs are written to the HDFS file.
2.6 shuffle phase of MapReduce
shuffle is called the heart of MapReduce and is the core of MapReduce.
As can be seen from the above figure, each data slice is processed by a Mapper process, that is, Mapper is only a part of the processing file.
Each Mapper process has a ring memory buffer to store the output data of the map. The default size of the memory buffer is 100MB. When the data reaches the threshold of 0.8, that is, 80MB, a background program will overflow the data to the disk. In the process of overflowing data to disk, it needs to go through a complex process. First, the data should be sorted by partition (according to partition number, such as 0, 1, 2). After partition, in order to avoid memory overflow of map output data, the map output data can be divided into small files and then partitioned, In this way, the output data of the map will be divided into sorted data of partitions with multiple small files. Then merge the partition data of each small file into a large file (merge those with the same partition number in each small file).
At this time, reducer starts three, which are 0, 1 and 2 respectively. Reducer 0 will get the data of partition 0; Reducer 1 will obtain the data of partition 1; Reducer 2 will get the data of partition 2.
2.7 MapReduce optimization
2.7.1 resource related parameters
//The following parameters are configured in the user's own MapReduce application to take effect
(1) mapreduce.map.memory.mb: the maximum memory available for a Map Task (unit: MB). The default is 1024. If the amount of resources actually used by the Map Task exceeds this value, it will be forcibly killed.
(2) mapreduce.reduce.memory.mb: the maximum number of resources that can be used by a Reduce Task (unit: MB). The default is 1024. If the amount of resources actually used by the Reduce Task exceeds this value, it will be forcibly killed.
(3) mapreduce.map.cpu.vcores: the maximum number of CPU cores available for each Maptask. Default: 1
(4) mapreduce.reduce.cpu.vcores: the maximum number of CPU cores available per Reducetask. Default: 1
(5) Mapreduce.map.java.opts: JVM parameter of map task. You can configure the default java heap here
size and other parameters, for example: "- xmx1024m - verbose: GC - xloggc: / tmp"/@ taskid@.gc ”
(@ taskid @ will be automatically changed to the corresponding taskid by the Hadoop framework). The default value is: ""
(6) Mapreduce.reduce.java.opts: JVM parameter of reduce task. You can configure default Java here
Parameters such as heap size, for example: "- xmx1024m - verbose: GC - xloggc: / tmp"/@ taskid@.gc ”, default: ''
//It should be configured in the server's configuration file before yarn starts to take effect
(1) Yarn.scheduler.minimum-allocation-mb the minimum configuration requested by each container in RM, in MB. The default is 1024.
(2) Yarn.scheduler.maximum-allocation-mb the maximum allocation requested by each container in RM, in MB. The default is 8192.
(3) yarn.scheduler.minimum-allocation-vcores 1
(4)yarn.scheduler.maximum-allocation-vcores 32
(5) yarn.nodemanager.resource.memory-mb indicates the total amount of physical memory available to YARN on the node. The default is 8192 (MB). Note that if your node's memory resources are less than 8GB, you need to reduce this value, and YARN will not intelligently detect the total amount of physical memory of the node.
//The key parameters of shuffle performance optimization should be configured before yarn starts
(1) Mapreduce.task.io.sort.mb is the ring buffer size of 100 shuffle, which is 100m by default
(2) Mapreduce.map.sort.spin.percent 0.8 threshold of ring buffer overflow, 80% by default
2.7.2 fault tolerance related parameters
(1) mapreduce.map.maxattempts: the maximum number of retries per Map Task. Once the retry parameter exceeds this value, it is considered that the Map Task fails to run. The default value is 4.
(2) mapreduce.reduce.maxattempts: the maximum number of retries per Reduce Task. Once the retry parameter exceeds this value, it is considered that the Map Task fails to run. The default value is 4.
(3) mapreduce.map.failures.maxpercent: when the failure ratio of failed map tasks exceeds this value, the whole job will fail. The default value is 0. If your application allows to discard some input data, this value is set to a value greater than 0, such as 5, which means that if less than 5% of map tasks fail (if a Map Task is retried more than mapreduce.map.maxattempts, it is considered that the Map Task fails, and its corresponding input data will not produce any results). The whole job is considered successful.
(4) mapreduce.reduce.failures.maxpercent: when the proportion of failed reduce tasks exceeds this value, the whole job fails. The default value is 0
(5) mapreduce.task.timeout: if a task does not enter for a certain period of time, that is, it will not read new data or output data, it is considered that the task is in block state, which may be temporarily stuck or may be stuck forever. In order to prevent the user program from exiting forever, a timeout (unit: ms) is forcibly set , the default is 600000, and a value of 0 disables timeout.
2.7.3 efficiency and stability parameters
(1) Mapreduce.Map.specific: whether to open the speculative execution mechanism for Map tasks. The default is true. If true, multiple instances of some Map tasks can be executed in parallel.
(2) mapreduce.reduce.speculative: whether to open speculative execution mechanism for Reduce Task. The default value is true
(3)mapreduce.input.fileinputformat.split.minsize: FileInputFormat is the minimum slice size when slicing. The default is 1.
(5)mapreduce.input.fileinputformat.split.maxsize: FileInputFormat maximum slice size when slicing
2.8 execution process of mapreduce program on yarn
Hadoop jar xxx.jar
Detailed process:
- 1: The client submits a task to the cluster. The task first goes to the application manager in the resource manager;
- 2: After receiving the task, the application manager will find a NodeManager in the cluster and start an AppMaster process on the DataNode where the NodeManager is located, which is used for task division and task monitoring;
- 3: After the AppMaster is started, it will register its information with the application manager in the resource manager (for communication);
- 4: AppMaster applies to the ResourceScheduler under ResourceManager for the resources required by the calculation task;
- 5: After applying for resources, the AppMaster will communicate with all nodemanagers and ask them to start the tasks required for computing tasks (Map and Reduce);
- 6: Each NodeManager starts the corresponding container to execute Map and Reduce tasks;
- 7: Each task will report its execution progress and execution status to the AppMaster, so that the AppMaster can master the operation status of each task at any time, and restart the execution of a task after it has a problem;
- 8: After the task is executed, the AppMaster reports to the application manager so that the application manager can log off and close itself, so that the resources can be recycled;
2.9 common problems in MapReduce implementation
- The client does not have permission to operate HDFS in the cluster
In the cluster configuration file hdfs-site.xml property> <name>dfs.permissions</name> <value>false</value> </property> Then restart
The output path of mapreduce already exists. You must delete that path first
The cluster operation was submitted and failed
job.setJar("/home/hadoop/wordcount.jar");
If the log cannot be typed, a warning message will be reported
log4j:WARN No appenders could be found for logger (org.apache.hadoop.metrics2.lib.MutableMetricsFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See for more info.
You need to create a new file named log4j.properties under the src of the project | https://programmer.group/review-of-big-data-development-mapreduce.html | CC-MAIN-2021-49 | refinedweb | 2,737 | 54.93 |
hey guys,
i don't have too much experience of using MS Visual Studio, therefore i need some help. i am trying to write a program using WinSock in Visual C++, so could someone tell be what i need to do to include the "winsock.h" header file, in MS Visual Studio. Beyond the following.
Code:
#include <winsock.h>
i've tried a number of solutions that i have found on the net, but non of them have completely worked. therefore could anyone help me?
thanks in advance,
- User0182
#include <winsock.h>
That is actually all you need to do. If that's not working, then you have problems somewhere else. What problems are you having with it, exactly?
when i try to use WSAStartup(), then i get a build error. that says:
error LNK2019: unresolved external symbol _WSAStartup@8 referenced in function _main
which is why i think that the "winsock.h" library has not been included in the build. what do you think?
I haven't opened Visual Studio in years and I never used it for anything but Visual Basic, but as I recall there was a setting where you had to import a whole package that contained each library that you intend to reference. It's been too many years for me to tell you where to look and I have no idea how much the program has changed in that time.
I had to do such an import myself just to reference the scripting.filesystem object.
that's what i was thinking, that i may have to import the header file into my project.
but, im not sure how to do that. all the attempts that i have made have been unsuccessful ;-(.
although, i could easily be mistaken! anyone, that has any ideas how i could resolve this problem, please let me know.
Last edited by user0182; April 24th, 2008 at 12:54 AM.
thanks for your help guys, but i've worked out the answer to my own question! what i needed to do was, on the menus, go to:
project -> properties -> "configuration properties" -> linker -> input -> "additional dependancies"
and add "WS2_32.lib".
- user0182
I'm glad you found it, I was about to tell you that the solution is not coding, but rather part of the menu interface. Anyway you solved it. Congrats!
It's actually a linker error. By adding the additional dependencies you're telling the linker to link the ws2_32.lib to your executable making it's functions available.
Oliver's Law:
Experience is something you don't get until just after you need it.
Don't know if this'll help you at all, but generally if the problem was that VS couldn't find the header file you would get an error along the lines of:
"Warning C4013: 'my_func' undefined; assuming extern, returning int"
Another way that you can get an idea of whether the issue is a compiler or a linker problem is by looking at the error codes. Compiler problems start with Cxxxx whereas linker problems start with LNKxxxx.
A good way to get help on these problems is to search by that error code.
Cheers,
ac
Forum Rules | http://www.antionline.com/showthread.php?276954-Visual-Studio-include&p=938142&viewfull=1 | CC-MAIN-2013-20 | refinedweb | 532 | 74.08 |
Wikiversity:Candidates for Custodianship/Abd
Contents
- 1 Abd (talk • email • contribs • stats • logs • global account)
- 1.1 Questions for the Candidate
- 1.2 Custodians willing to mentor
- 1.3 Mentor's recommendation for extended probationary custodian status
- 1.4 Feedback and questions
- 1.5 End of Probation - Mentor's statement
- 1.6 Review of specific actions, Abd's statement
- 1.7 Full Custodian Vote
- 1.8 Closure
Abd (talk • email • contribs • stats • logs • global account)[edit source]
I was doing recent changes patrol here and saw some multiple vandalism on a number of different pages by an IP editor and missed having rollback, as I do on en.wiki. So I asked about getting the privilege here, then noticed that it doesn't seem to be a separate privilege here from admin status. Ottava Rima suggested I request adminship. I was nominated for adminship on Wikipedia, twice (by the same person, actually), second time made it to about 50% with most opposition being based on what was at that time about 1400 edits, low for en.wiki adminship, and I was told to apply later with more edits, I'd be approved. (I now have about 14,000 en.wiki edits, but I doubt I'd be approved now because I've been involved in controversy there, but I never needed admin tools for most of the work I was doing at en.wiki. The problems I had at en.wiki can be anticipated by reading the linked RfA.)
I understand (and have actively supported and promoted on en.wiki) the concept and practice of administrative recusal when involved; I highly doubt that I would be likely to abuse admin tools here. I cannot promise to put in a lot of effort here, but I have already started to try to help keep the place clean, and am very interested in Wikiversity possibilities for collaborative learning -- but I don't need tools for that!. I consider administrators to be, properly, servants of community consensus, not of their own positions and views, and I would use admin tools in that way. If I disagree with community consensus, which can happen, I will not use the tools in service of my own opinion, but only seeking and serving consensus. --Abd 17:37, 24 May 2010 (UTC)
Questions for the Candidate[edit source]
- In your response to Ottava below, timestamped 16:04, 28 May 2010, you give administrators who support your Custodianship more power over you than other administrators. Could you explain your motivation behind this? What will you do if an admin who neither supported nor opposed asks you to suspend usage of administrative tools?
While I don't doubt that the contents of this page are accurate, and I think you can offer a lot to the development of this topic on Wikiversity and elsewhere, I am concerned about the creation of a list of experts on Cold fusion that currently includes only yourself. The contents of that page do not, IMO, adequately meet the definition of an expert. Have you published in the field, are you often invited to speak at conferences, or do you have what would be considered extensive experience that has been recognised by others in the field?
John Vandenberg (chat) 08:16, 29 May 2010 (UTC)
- Thanks for asking. It's just an idea and a promise. No prejudice is implied or anticipated against someone who does *not* support or even who opposes. If I were asked to suspend usage by an administrator, I'd probably comply pending formation of consensus, and, in fact, I'd consider doing that for any user unless protecting the wiki required action and no other administrator was available. But with those who have supported, I become obligated to comply, that's all. That, of course, includes my mentor(s). I have, just for myself, tightened up the mentorship rules, only on myself, just a little, in what seems like a harmless way. I find the concept of probationary adminship here quite interesting, and, in effect, I'm trying out a way that might become practical on Wikipedia. Effectively, immediate suspension by those who supported. It doesn't make sense to suspend on the request of someone who was opposed!
- The "expert" page cited is a subpage of Cold fusion/Experts which explains what it's about. The question is not relevant to this discussion, but I do have a conflict of interest on that topic and would not use tools for anything controversial relating to it. Any discussion of experts or my expertise -- please read the parent page! -- should be in Talk there or otherwise as relevant and appropriate. --Abd 02:50, 30 May 2010 (UTC)
- Thanks for clarifying. I also use 'have supported' in my en.wp recall pledge, but that was made after obtaining the support of these people, and I ask that five supporters agree. As your promise is only in effect during the probation period, and Wikiversity is a quieter woods, I see this promise as beneficial to lower the "risk" of supporting you.
- In regards to the expert page, my concern is not with your ability to avoid the conflict of interest, but with the way you are characterising yourself (in mainspace) as an expert. Wikiversity does not need it's own version of the w:Essjay controversy. If you are not using the term "expert" in the appropriate way, now would be a good time to rectify this. John Vandenberg (chat) 07:12, 30 May 2010 (UTC)
- Yes, lowering the risk was a goal. One of the problems with WP adminship is that removing it can be horrifically difficult, and this, then, makes it seem advisable to require supermajority approval, even though it's likely that this simply "elects" administrators who haven't offended yet. Most will be fine, but the exceptions can cause serious long-term difficulties. If an admin is popular even though divisive, perhaps supporting a large faction, the admin can be grossly abusive and still difficult to touch. WP should back up and reconsider the whole process. I like Wikiversity for its use of probationary adminship, and exploring ways to deal with possible abusive adminship efficiently is of interest to me. So I tried putting something in this application about that. It could seem politically conniving, i.e., that I'm doing this to get more approvals, but, then, I'd suggest, this kind of "conniving" is handing power to those who might otherwise disapprove or abstain. If I did not think that this trade-off could benefit the project, I'd not have done it. It is highly unlikely to be of real consequence for me, as I believe is plain from my RfA 2 at Wikipedia. I've been very involved in controversy there, and that wouldn't have changed had I become an admin, because I would not have touched my active admin tools when involved. If I can't get consensus with requests and discussion, I'd simply be manufacturing unnecessary and divisive controversy. I'm much more likely to err toward too much discussion, and that's why I was sanctioned on WP, as far as I can tell.
- I did not, however, apply for adminship to make some kind of point, and this promise was added as an afterthought when Ottava agreed to mentor, below. I applied because I was doing RCP and realized I needed rollback. In addition, I'd have speedied a couple of pages, and this would have been more efficient than putting up a speedy template, which I did instead. All of these pages were immediately deleted without controversy. This, for a probationary admin system, should be evidence in favor of approval, and I'm just suggesting, now, by my promise, that we might make this even easier and safer, with approval here merely meaning, "Okay, I'm willing to let you try, knowing that I can stop this immediately if I see a problem." I thought of extending this to any editor, not just admins, but am unclear about the consequences of that, which is why I held back. Your recall process is general, it seems. And I like it from what you've said here, I'll read it. I might make it a little more complex but both easier and safer, first thoughts. I declined to accept admin recall in my RfA 2 because of what I saw as severe process problems; yours is better and I might have accepted that, or modified it.
- As to the expert issue, perhaps "expert" is the wrong word? I suggest discussing it there. I am, in fact, trying to set this up as a model that might be imitated, and "expert" could mean anything from a Nobel prize winner (I might be able to solicit one for the cold fusion topic, he's been active) to some fringe nut case, and with the latter, we'd decide whether or not it was worth the space and time. (This "expert" is expert on his fringe theories.) Our consensus is the leader of the seminar. If the "nut case" is reasonably notable, even informally, as in internet discussion, I'd support it, but would also want to see a neutral sponsor who would regulate it and keep it worth reading. I'm merely an advanced student, so to speak, who is also commercially involved. I'm now well known among many of the scientists in the field, and was just admitted to the private Condensed Matter Nuclear Science list on the nomination of a very prominent cold fusion scientist (a true expert in every sense). Because of my obvious COI, I certainly will avoid any revert warring or the like to preserve my own page there. Admins on small wikis sometimes don't follow this practice and revert war to preserve their own point of view, or even use tools, knowing that there are usually few consequences for an admin. But there is a consequence that can't be avoided: it drives away users, one or a few at a time. And here I go discussing too much.... but I won't delete it unless someone asks me to. WYSIWYG. --Abd 15:04, 30 May 2010 (UTC)
Custodians willing to mentor[edit source]
- As I said on my talk page, I would be willing to mentor. Ottava Rima (talk) 13:46, 27 May 2010 (UTC)
- During my probation, I consent in advance to any reversal of my administrative actions, by Ottava Rima, and by any other administrator who has supported this nomination.. (However, this promise will not survive removal of the admin flag from a supporting administrator.) Thanks, Ottava, your support is appreciated. I look forward to serving the community and the project, and appreciate the collegial atmosphere here. --Abd 16:04, 28 May 2010 (UTC)
Y Done The probationary period has started. -- Jtneill - Talk - c 12:58, 9 June 2010 (UTC)
- As Ottava has gone to meta and requested termination of my custodianship, I request that another custodian agree to mentor me, pending a possible request for permanent custodianship, and I'm open to discussing that here or on my Talk page or wherever desired by an interested custodian. The above consent is, of course, now revoked as to Ottava. I did not violate the promise, I did not fail to abstain after request. And I still thank Ottava for his prior support, it's unfortunate that it came to this, but duty is duty. My duty was to Wikiversity, not to my mentor. --Abd 03:30, 29 July 2010 (UTC)
- You are given one thirty day period of mentorship. There isn't anything in the process to start a new mentorship with a new mentor. The proposal below was to give an extension, which is unique. As I said, wait a week and then, if you are up for it, apply for full adminship. Ottava Rima (talk) 03:35, 29 July 2010 (UTC)
Ottava Rima was quite incorrect in his comment about there being nothing "in the process to start a new mentorship with a new mentor. On the contrary, it is explicit:
-.
I was never provided the 48-hour period after notice of withdrawal, and because Ottava argued as above, and I hadn't read that section of the policy, I did not actively seek another mentor immediately. Rather than asking Jtneill to reinstate my custodianship because of the violation, I consider this application suspended, until process deficiencies are corrected. Jtneill could either reverse Ottava's decision, by resysopping, leaving me 48 hours to find a mentor, or simply leave this alone until I find a mentor, there should be no emergency, and then resysop when a qualified mentor appears. Jtneill, if he decides to simply reinstate, could, even without becoming a mentor, set any conditions he finds appropriate for the protection of the community from disruption.
Meanwhile, this request for Custodianship remains open for questions and comments by the community. I have been honest and open in my dealings with the community. Had I been a permanent custodian, I would have blocked Ottava as I did, so to refrain from blocking -- or at least requesting Custodian action, which I considered inappropriate alone because I saw an emergency character to the situation -- would have been, in a way, deceptive. Should I, as a probationary custodian, be on my "best behavior" -- i.e., avoiding all controversy, as clearly happens with those who want to be Wikipedia administrators, and the mask only falls off when they are approved)? No, what you see is what you get. I am standing strongly for improved and more efficient community process, which includes stricter (but gentler!) enforcement of civility policy, as well as establishing clear guidelines for recusal requirements, and better dispute resolution process, particularly when sysops become involved in a dispute. During my active probation, I demonstrated tools for attempting to actually resolve long-term disputes, instead of merely having some kind of weak decision on one side and then having a few sysops enforce it with others opposed, leaving the project, etc. I also did, by the way, substantial routine custodial work, but my long-term wiki interest, beginning on Wikipedia, has been improved wiki process, because dysfunctional process wastes huge amounts of time with little resulting value. To get there will take, however, lots of discussion, and some aren't willing to participate in that, which is fine. But some try to stop it, which is not fine.
I do not need custodial tools for my major work here, however. It's up to the community to decide if Wikiversity is better one way or another. --Abd 19:50, 1 August 2010 (UTC)
- 1. You agreed to be terminated at any time per request. 2. Your mentorship period is 30 days as per policy: "During your mentorship period of four weeks". Selectively reading things like that is unbecoming. Ottava Rima (talk) 20:39, 1 August 2010 (UTC)
Request for new mentor[edit source]
Per Custodianship policy, I am requesting a new mentor to replace the resigned Ottava Rima. Any custodian considering mentorship may request that I agree to any restriction, or may ask questions prior to agreeing, here or on my Talk page or by email; if I don't like the restriction, I may decline the invitation, but I will appreciate all offers. Thanks. --Abd 19:55, 1 August 2010 (UTC)
- Sorry, but your mentorship period is only 30 days and ended over 2 weeks ago. There is no new mentor. "During your mentorship period of four weeks" is bolded in the policy for a reason. No one else in the community thought you were fit enough to extend the mentorship, which is not allowed within policy regardless. Ottava Rima (talk) 20:39, 1 August 2010 (UTC)
- This is nuts. "Four weeks" is a rough positive statement. My mentorship was extended because Ottava requested it and nobody opposed. That's standard. Why, Ottava, are you attempting to prohibit a new mentor from appearing, when the policy is extremely clear otherwise? I don't have tools now, because Ottava prematurely yanked them, misrepresenting WV policy to the stewards at meta. Policy would have provided for a 48 hour period for me to find another mentor, before tools are lifted. The process for removal is explicit: Your mentor may request removal of your custodianship at the end of the 48 hour period if you are unable to find a new mentor, without any further notice or discussion by the community. This is really moot unless I find a mentor, but the point here, for me, is Ottava's willingness to tendentiously argue self-serving interpretations of policy and conditions, just as he did to justify his revision deletion of the block record, and his desysop request without providing opportunity for a replacement mentor. It looks to me like those who wrote that policy did, in fact, anticipate that some problem could arise between a mentor and the mentored custodian, so they provided a fair remedy to cover that. Further, there was no risk of continued (alleged) "abuse" of tools, because my personal agreement did provide for immediate emergency desysopping upon a showing of continued use of tools in spite of a request to stop from my mentor. Ottava could have shown that to any steward. But he did not, because the steward would have seen no continued action after a request to stop, hence Ottava, instead, relied upon the alleged 30 day limit. Wikiversity has a custodian who is dangerously ready to pursue his personal gain and opinions over following policy and serving the community, and he has not acknowledged the error, so it is almost certain to repeat. --Abd 00:54, 2 August 2010 (UTC)
- "Ottava requested it and nobody opposed. " That isn't how things work. You need consensus, not lack of opposition. You are getting to the point that the only thing that would stop your endless nonsense is a ban. Ottava Rima (talk) 02:46, 2 August 2010 (UTC)
Mentor's recommendation for extended probationary custodian status[edit source]
I believe that Abd's probationary period should be extended in a manner similar to Diego Grez as proposed by Jtneill.
As per Jtneill's statements about Diego Grez, it would be good if other editors sharde feedback or questions here about Abd's probationary custodianship. Ottava Rima (talk) 01:44, 14 July 2010 (UTC)
- Thanks, Ottava. My Talk page has always been open to questions about my actions as a custodian, but I don't actually recall any custodial actions of mine that have been questioned except for a few clumsy errors at the beginning. Conflict that has arisen has been shallow, except for one obvious case, where I haven't used tools at all. I assume that before permanent custodianship is considered, all objections will be considered and will have received due response from me. Thanks for the extension of time, I believe that it has been useful for me to have tools and learn to use them, and I remain open to recall or suspension of my tool use as provided in my candidacy, or otherwise. --Abd 00:27, 15 July 2010 (UTC)
- Today, Ottava requested termination of my access to tools, and it was routinely granted. This was in contradiction to the above recommendation, and the reason is obvious. I blocked Ottava for incivility, which, I assume, will be subject to review. Ottava had the right, I assume, to so terminate my mentorship, he is not required to give a reason, but his citing of routine expiration was a bit disengenuous, given the above suggestion. If another custodian wants to offer mentorship, that's okay with me, the promise I made with my candidacy would be the same. It was rather awkward, to say the least, to discover a necessity to block my mentor! It was not a hasty action. He'd have done better by honoring it, he had only a few minutes to wait before it expired when he unblocked himself. The real shame is that no other custodian intervened, a sign of how understaffed this place is. --Abd 02:43, 29 July 2010 (UTC)
- If you read, the above was a proposal. No one agreed to it. Instead, you had two people question your access. You only kept it for those 15 more days because I turned my back and didn't post anything more about it. You could have used the time to help your case but instead you acted inappropriately, blocked to make a point, and made a claim about civility which was completely blown out of portion. That isn't good. Ottava Rima (talk) 03:27, 29 July 2010 (UTC)
- This is moot, Ottava. Eh, who questioned my access besides JWSchmidt, who is questioning every custodian -- and who had previously threatened to oppose my custodianship if I dared to criticize him? I could say more, but I'm not about to get into an extended debate about this. If it's important, someone else will chime in. I'm quite willing to answer questions from others. --Abd 04:01, 29 July 2010 (UTC)
Regardless of whether there are any custodians that would be prepared to act as mentor to Abd, I would suggest it would be better to not reinstate Abd's custodian rights at this time. I think we need to take time to calm the situation down and mop up any mess that has recently been created. I suppose that since Abd had had longer than the specified probationary custodianship period we might have to consider whether it would be necessary to start another probationary period before discussing whether or not to grant permanent custodianship. However, even in that case, I still think it would be better to leave the idea of custodianship for Abd for a while. Rightly or wrongly, it is my impression that Abd and to some degree Diego, have reopened old wounds, albeit with good intentions, and I think we need a period of time now to reflect on what has gone on and deal with any remaining issues. Adambro 10:08, 29 July 2010 (UTC)
- It's merely a possibility. There is no emergency now. I used the tools because I had them, and any custodian, including Ottava, could have asked me to refrain, or could have reversed the action, that was openly allowed. It was just a bad idea for Ottava to do it himself, for all the classic reasons. As to old wounds, they were festering, badly, regardless of actions of mine. I attempted to lance the boil, and for all I know, there has been some success. There has been progress: what was easily seen as intervention from meta or Jimbo is now firmly established as local action, taken by two responsible custodians, thus reversible locally, by as little as a single custodian deciding to act, and all the way up to a formation of a community consensus. That's progress. Other benefits have been established, as I intend to show in the coming period. It doesn't involve or require my use of ops. There is no sign of impending doom from thunderbolts from on high. This community is responsible for its own affairs. But if it does not develop means of responding efficiently and effectively to crisis, it's possible that outside intervention could resume. I understand that the Taliban debated the wisdom of allowing Osama bin Laden to operate in Afghanistan. But they could not find consensus.... --Abd 20:22, 29 July 2010 (UTC)
Feedback and questions[edit source]
From JWSchmidt[edit source]
I've long believed that Custodians qualify for Custodianship by their constructive activity in main namespace learning projects. Is this candidate more interested in wiki drama or learning? Speedy deletion is for vandalism. Can either Ottava Rima or Abd describe how Abd has been mentored? I get the feeling that Abd wants to apply Wikipedia policy to Wikiversity. --JWSchmidt 20:37, 14 July 2010 (UTC)
- [1], [2], [3], etc are the sources for the copy and paste found in the School of Extended Studies at Portland State University. The Wikiversity page is a compilation of about 20 different pages on their website. At least 50% of the page is direct copy and paste. It has been deleted as such. Ottava Rima (talk) 20:48, 14 July 2010 (UTC)
- Thanks, JWS, for the opportunity to respond to your concerns. This, however, was not an action involving use of tools, what I did could have been done by any editor. It was not a "speedy deletion," and when I placed the deletion tag, the edit summary was (tag for deletion, not a learning resource, not useful here.)
- Strange, but I thought I saw "speedy deletion" on the deletion template, similar to what is shown in this image:
Does this show that you support the speedy deletion of non-vandalism pages? --JWSchmidt 07:07, 15 July 2010 (UTC)
- As a custodian, I started patrolling relevant pages to assist in normal custodial cleanup. However, the particular page mentioned I did not find that way. There was a report on the Colloquium asking about School spam. I looked at a page cited there and agreed that there was a problem with the page. So, to begin the process, I placed a deletion tag on the page. The reason given was this page is not a learning resource, but a general description of a school, not useful here. I also placed a notice on the talk page of the editor, which I'd prefer be read.
- The page itself was deleted by Ottava two weeks later, today, and Ottava notified the author of that. Later, the author asked for advice, and if someone doesn't beat me to it, I will undelete and userfy the page so that this user may access it to work on the Wikipedia article apparently intended.
- I'll admit to being proud of how I handled this, and it was, until now, completely drama-free. The claim that deletion tags are only for vandalism is simply not true. They are used, here, for any proposed deletion that does not seem to require a Wikiversity:Requests for Deletion discussion, which would needlessly distract editors. This was a non-oppositional and cooperative process, and doesn't resemble Wikipedia speedy deletion, which is complicated, abrupt, and often inconsiderate. It's more like Wikipedia PROD. There were no charges at all of vandalism. Is there some policy or guideline I've overlooked? --Abd 00:54, 15 July 2010 (UTC)
- "The claim that deletion tags are only for vandalism is simply not true." <-- Who made that claim? Do you agree with this: "Deletion of pages that are obvious vandalism, obvious copyright violations, or have other content that is obviously harming Wikiversity and where the reason is self-explanatory can be deleted by custodians at any time without discussion (speedy deletion). Any non-obvious cases or cases that may require further explanation should be discussed at Requests for Deletion."? --JWSchmidt 07:13, 15 July 2010 (UTC)
- Weird. Who made the claim? Basically, you, JWS, above. True, you did not write "only," but the context of your question implied it. What JWS then quotes allows deletion of vandalism, etc., immediately, with no delay. That is true "speedy deletion," but the use of a tag asking for review for consideration of deletion isn't necessarily "speedy," it is just an ad hoc process for efficiency, for deletions which may not need to be discussed at length. Such deletions should always be readily reversible unless they were done for strong reasons. In the case cited, I came across a page where another editor had mentioned it as improper for Wikiversity. I judged that to be correct, but instead of immediately deleting it myself (true "speedy"), I placed a deletion tag, and also notified the author, something which I found was often overlooked with other deletion tags I'd been reviewing. I considered the case obvious, thus it fell into the cracks between the two cases cited in the policy. I followed an intermediate process between true speedy deletion (simple administrative decision, whether direct or upon some request), and RfD, which was simply to tag it and wait for a second opinion, as well as response by the author. As noted, this worked perfectly, apparently. As to whether or not I 'agree' with the guideline cited, I largely agree with it, and also consider that it can be improved. It can be read as requiring a deletion discussion for other than "obvious vandalism, copyright violations, or obvious harm." That is, quite simply, overkill and highly inefficient. Rather, the process I used is easily reversible if an error is made, and the notification of the author ensured that it would not simply pass without notice. JWS, the key principle of wiki effective process is efficient cooperation, which includes and requires trust that errors can be fixed. Please get that straight. --Abd 20:38, 15 July 2010 (UTC)
- "the context of your question implied it" <-- The context of my comment implied that speedy deletion had been used for the wrong purpose, which has been a problem since the hostile takeover of Wikiversity in 2008. We now have sysops that specialize in destroying Wikiversity content rather than collaboratively improving Wikiversity. "It can be read as requiring a deletion discussion for other than "obvious vandalism, copyright violations, or obvious harm." That is, quite simply, overkill and highly inefficient." <-- Not by the standards of Wikiversity, where we welcome every participant and help them improve the pages they create. If you don't have the time or the temperament to welcome and help Wikiversity participants then you should not be a Custodian. If you want to apply the standards of Wikipedia, go become a sysop at that project. "Please get that straight" <-- The Wikiversity standard of cooperation is to allow community discussion at Wikiversity:Requests for Deletion. I still don't understand why you voiced support for speedy deletion here, but I can't see what was on the page. It seems to me that if you had doubts about the page then it was not a candidate for speedy deletion and the community should have discussed it. --JWSchmidt 21:57, 15 July 2010 (UTC)
- I'm asking others to stop fruitless debate with JWS <-- In this case, Adambro created a mysterious thread at Wikiversity:Request custodian action#User:Beetlebaum where Abd complained about my "reprehensible" behavior then walked away complaining about "fruitless debate". Is it constructive for a Custodian to label as "fruitless debate" a discussion where he does not hear unanimous agreement with his point of view? Abd wrote: "I have plenty else to do!". Maybe Abd is too busy to be a Custodian. --JWSchmidt 00:12, 15 July 2010 (UTC)
- My comments were as a user, I did not use or threaten the use of custodian tools there. I do think that my views there do or will enjoy consensus, but not necessarily unanimous agreement, apparently. The edit involved was one reverting myself, JWS perhaps has overlooked that? Here was the full edit summary; JWS incompletely quoted it: (Undo revision 583695 by Abd (talk)I'm asking others to stop fruitless debate with JWS, so I'm undoing my own comment.) Thanks for the opportunity to clarify this, apparently, JWS, you misunderstood what was written. --Abd 01:12, 15 July 2010 (UTC)
- "apparently, JWS, you misunderstood what was written" <-- How is that apparent? This is an example (one of many) where you have tried to apply rules from another community to Wikiversity and in so doing you felt justified to condemn my actions. A Custodian should not disrupt Wikiversity by imposing rules from other websites. A probationary Custodian should be happy to discuss their failure to appreciate how things are done at Wikiversity, not rudely dismiss the views of long-time Wikiversity participants. Once again you have demonstrated that you should not be a Custodian. --JWSchmidt 06:52, 15 July 2010 (UTC)
- Second try. Abd, what do you think qualifies someone to be a Custodian? When you come to Wikiversity are you more interested in participating in generating Wikipedia-style wiki drama or learning? Can either Ottava Rima or Abd describe how Abd has been mentored? --JWSchmidt 07:18, 15 July 2010 (UTC)
- JWS - I proposed that his mentorship period is extended. You have enough time to worry about such an examination later. :) But to answer your question - I showed both Diego and Abd how to use the various tools to help them with mechanical aspects. I have also talked to them personally about various issues on site and off site (emal, IRC, messageboard, etc). Ottava Rima (talk) 21:05, 15 July 2010 (UTC)
- Qualification. On Wikiversity, the consent of the community is required to a trial with the tools, providing a mentor custodian or bureaucrat exists who is willing to train and restrain the new custodian (and request a steward desysop if necessary). No special qualification other than that is needed, because the custodian can learn on the job. The person should have sufficient good sense and wiki experience to not knock the pillars out from under the roof, but even that could be fixed. It is a wiki. If I went too far astray, Ottava would quickly stop me and if I didn't "learn my lesson," my tools would be yanked with no further ado.
- My interest. I stopped beating my wife years ago. I simply wanted to have rollback so I could deal with vandalism in Recent Changes patrol. Turned out that wasn't separable on Wikiversity from the rest of the custodial tools, so Ottava suggested I request custodianship and offered to mentor me. He had quite a bit of experience with observing me on Wikipedia and elsewhere; interestingly, I'd been a fairly severe critic of some of his actions elsewhere, and his support and suggestion here shows how this community can sometimes allow users to set aside conflicts elsewhere. I have found the active custodians here to be highly collaborative, and tolerant of some possibly controversial actions, such as attempts I've made to begin reversing, where possible, some of the damage from the past. Funny that none of those attempts are mentioned by JWS....
- How mentored? This is a wiki. Every action is visible. Everyone has helped me, when I needed help. And so far, I don't seem to have knocked over any pillars, there is only one user here who has been complaining, about anything and everything, and he's been complaining for two years. Is there a problem with how I've used tools? Have I used them outside of community norms? Where? When I requested custodianship, I specifically stated that I'd stop using tools on the request of anyone who supported the request. There are teeth behind that. But I've received no request to stop, no request to recuse from anyone, much less one of those specially qualified (as my mentor, for example.) I'm aware that I'm involved in some controversy now, but I'm extremely sensitive to community consensus and would stop at any hint that there is more than isolated complaint. Even one complaint will cause me to become very careful. But right now we have extensive IP disruption going on and a shortage of administrators, which creates extraordinary conditions. --Abd 21:28, 15 July 2010 (UTC)
- "No special qualification other than that is needed, because the custodian can learn on the job." <-- I don't agree. Some people are not suited for Custodianship. For example, a sysop must be a trusted member of the community. Does someone demonstrate that they can be trusted to help the Wikiversity project if they erroneously try to apply the rules of Wikipedia to the needs of Wikiversity, as you frequently do? "attempts I've made" <-- please describe these "attempts". "Is there a problem with how I've used tools?" <-- Just off hand, there are two examples under community review of how you falsified log entries. Also under community review. Why do you think this is an acceptable way to participate in a community review? "wasted way too much time" <-- Abd if you don't respond to a review of your Probationary Custodianship actions at community review then you should not be a Custodian. --JWSchmidt 22:22, 15 July 2010 (UTC)
- JWS, I will respond to a specific review of my actions, and one question at a time, but, see below, only if two Wikiversitans agree I should. But I'll now answer two points picked from the above, starting with an allegation that I'm applying "the rules of Wikipedia to the needs of Wikiversity." Nothing could be further from the truth. The "rules of Wikipedia" are largely derived from the natural needs of all wikis, including this one, which is not as unique as some might think. There are indeed unique policies here, compared to Wikipedia, such as the allowance of original research, but issues around civility and consensus, important to both projects, are not so different, it is merely that matters can become both easier and more difficult due to the small scale of Wikiversity. So sometimes what I assert as "policy" is what I more carefully call "common-law policy," being how wikis have almost all been administered since the beginning. Beyond that, we'd have to get very specific. And one other serious allegation:
- falsified log entries. Frequently JWS makes it difficult to track down his allegations. Here, instead of simply linking to a relevant log, and as he's done many times, he uses a huge, visually disruptive image file. But what is behind this? What were the alleged "falsified log entries?" "Falsified" implies not merely something erroneous, but which is deliberately concealing the truth. It is a clear allegation of bad faith, not merely of error or inappropriate action.
- log for Wikiversity:Request custodian action, page history. Log summary: (IP revert warring, blocked user). What was incorrect about this, let alone "falsified"? There was IP revert warring, that is, we had these edits: [4], [5], [6], [7]. Note that in the last diff, Moulton claims that the edits were constructive. I could agree. I did not call these edits "vandalism," only that there was revert warring, defined as repeated insertion of content. It could be argued that Adambro was also revert warring; however, Adambro had a proper reason, on the face, for removal of the content, which I mentioned: the user was blocked (at that time). Many times, I pointed out to JWS that, if he was willing to take responsibility for the edits, he could revert them back in, and then Adambro would have had no basis for reverting, it would have been revert warring itself, without the simple justification of block enforcement. But, until recently, JWS did not do this, from which I draw my own conclusions. It is utterly beyond me to guess what JWS considers "falsified," here, and, I'd suggest, he really should apologize for making such a blatantly incorrect charge.
- There are not two examples of my behavior in the section cited.
- Now, there went a perfectly good two hours, writing this. The charge to which I responded was utterly false, and caution and care by JWS could easily have avoided this. JWS, however, demands that all questions be answered. See Candidates_for_Custodianship/Adambro, where JWS also asked a long series of questions at once, Adambro did not refuse to answer the questions, but only such a long list asked at once, and he requested that JWS pick out, perhaps, a few of the most important questions. JWS did not do this, but then added the sole opposition expressed to adminship for Adambro, based explicitly on "failure to answer questions." So this practice of throwing up many questions, often tinged with an appearance, at least, of hostility (it is not civil to accuse someone of "falsification," it is quite the same as accusing someone of "lying"), and then faulting the person for not answering them, when classic wiki advice is to ignore hostility, is an old tactic of his. Accordingly, I will not answer further questions from JWS unless I personally consider the work involved to be of value for the community, yet I will make an important exception, that uses a device from standard deliberative process:
- As a candidate for custodianship, I have a special responsibility to answer questions from the community, but to some extent, this responsibility exists for all custodians. When it has become apparent to me, now or as a custodian, that the effort involved in responding to questions damages my ability to contribute to Wikiversity, I will respond, but only with a requirement that a specific question be seconded as needing an answer, by another Wikiversitan. While circumstances could exist where I'd need more (such as a second by a custodian), I consider it relatively unlikely, and will detail further conditions if they become necessary. Otherwise my responses simply compound the disruption being created by JWS, with far too little benefit.
- And I hope that JWS can return to being a net positive contributor to this community. The paradox about his questions of Adambro is that some of them probably deserved answer, and some participants voiced general support for that (Jtneill, SBJohnny) but did not, themselves, pick out specific questions for answer. It is not impossible that a more collaborative and less confrontational approach to asking questions would have resulted in a better decision! Or the decision would be the same, I have not studied the situation at that time to adequately predict the result. --Abd 21:06, 1 August 2010 (UTC)
From SB_Johnny[edit source]
Abd, my questions are from the perspective of a "retired" Wikiversitan (I don't even have my watchlist bookmarked anymore, but I do follow links from WR), so YMMV.
- You seem to me to be a very well-meaning and earnest person. If you become a Custodian, do you think you can really make a difference here?
- Rumor has it that Erik Moeller (WMF guy) said that Wikiversity has no future because it is run by trolls (or something to that effect). Do you agree? If you do, do you think you can out-shout the trolls? If not, what will you do to help improve Wikiversity's reputation?
- There's a delicate balance that needs to be kept between what the "foundation" wants Wikiversity to be, and what the "native WV people" want it to be. I don't think that balance has been found. What are your thoughts on that?
--SB_Johnny talk 23:02, 15 July 2010 (UTC)
- do you think you can really make a difference here? It's not clear that custodial tools would make a big difference in what I can do here. I've recently been involved in controversy and Ottava has, by email, yanked my probationary custodianship, but the controversy was not generally over use of tools, but simply over expressed opinions. (With one notable exception, I blocked my mentor for gross and blatant incivility, requesting immediate review by other custodians.) I don't need tools to express my opinions and plans and suggestions, and I do have lots of suggestions, based on over twenty years experience with on-line cooperative activity, including three years of heavy involvement with administrative issues on Wikipedia. What is not terribly clear is if anything can make a difference here, if the damage is not already too deep. I won't know if I don't try.
- Erik Moeller (rumored): Wikiversity has no future because it is run by trolls. Do you agree? There are two statements there, I'll answer them separately. Run by trolls? Maybe, but I haven't concluded that. "Trolling" would be deliberate provocation. Never ascribe to deliberate provocation what may simply be inattention or lack of care or, even, some necessity. Moulton trolls, for sure, as part of his "educational program." I made one trolling edit on Wikipedia. It got a sysop desysopped because of his response. It was also a necessity, because that's what it took to get ArbComm to take the situation seriously. And the edit itself was legitimate, it was simply what I'd have done without the threat from the sysop. And then, does Wikiversity have no future as a result? I can't tell, my crystal ball is broken. I certainly see some serious danger, and I'm currently holding off bringing in new users because of the apparent inability of this community to deal with crises as they arise. Even the most blatant disruption simply leads to discussion and more discussion and discussion about the discussion and objection to the discussion and generally no action. And then action is taken that was not discussed nor based on discussion, leading to more protest and discussion ad nauseum. There are fixes. Do I need admin tools to demonstrate them? Well, maybe I can help. I provided some examples as a probationary custodian, which I'll present for review.
- The balance between what the WMF wants WV to be and what the "natives" want it to be. My thoughts? WV will be what those who edit it want it to be, as long as this doesn't stray outside of what the WMF requires. In fact, if the volunteers here want it to be something that the WMF doesn't want to permit, the volunteers can simply move that activity elsewhere. As, you know, some are doing this already, perhaps they will be successful, there are now some heavy hitters behind that effort. But I think what the WMF requires hasn't been well-understood here, nor has it been well-articulated by the WMF or its representatives. There are solutions to possible conflicts between the WMF and the WV community, and they mostly involve WV becoming, itself, coherent. Right now it is incoherent, so dealing with WV, from a WMF point of view, is a bit like trying to negotiate with a schizophrenic who is incapable of making efficient decisions that will stick and can be relied upon. There are classic solutions to this problem and there are innovative solutions which I know about, and right now, neither are operative. I can say this: the status quo on Wikiversity will continue to function at a low level, being ineffective when there is conflict and controversy, thus risking interference and serious disruption and further loss of participation.
Thanks for asking. --Abd 02:31, 29 July 2010 (UTC)
End of Probation - Mentor's statement[edit source]
Per policy, probation ends at 30 days. Then per policy: "If your mentor evaluates you fit for permanent custodianship, a request for comments will be submitted at Candidates for Custodianship for a period of five days.".
Ottava Rima, mentor of Abd, does not find him fit. As such, this process is now terminated. Abd's tendentious actions regarding other custodians in the past 48 hours plus his selective reading above suggests that his actions are not inline with our standards. He was granted mentorship with little community support and had little history at this community. During his limited stay, he nearly non-stop argued with multiple members of the community, ignored mentor advice provided to him in multiple emails, and repeatedly stated what our standards and policies are (or "should be" according to him) without having a basis or experience to justify such statements.
His temporary sysops were revoked as extending beyond his 30 day period, but his abuse of ops included multiple uses of the block button inappropriately - ignoring consensus, not seeking consensus, unblocking banned individuals without any discussion with full administrators, and other such actions that are clear violations of our community norms and standards. He was told to take some time off, and instead spent even more time arguing and bickering. His statements about other's "civility" are hypocritical in that he has made far greater disruptive statements in far wordier terms and far more often than most people who are in good standing in this community.
Only those recommended for full custodianship but fail through community vote are allowed to request a new mentorship. There is no provision within policy for a new mentorship when one is not recommended for a vote. Ottava Rima (talk) 20:46, 1 August 2010 (UTC). The "during your probationary period" was clearly not intended to reverse the allowance of 48 hours, nor does it prevent reapplication if a new mentor is found. Controlling policy is not as represented by Ottava. --Abd 22:12, 1 August 2010 (UTC)
- There is nothing in policy stating you have the right to even edit this page anymore. There is no multiple mentorships unless you failed the vote. You are not given the right to a vote. That is policy. Your claims of "wikilawyering" are exactly wikilawyering. The fact that you think that "during" would apply to over 14 days after the maximum period of time for mentorship is just pure disruption and you -know- it is disruption. Your actions for the past month have been disruptive and tendentious. Stop. Ottava Rima (talk) 22:14, 1 August 2010 (UTC)
- Eh? All unblocked users have the right to edit this page, at this point. Ottava's arguments are getting more and more bizarre. "Vote"? Who talked about voting? Ottava is claiming that comment showing how preposterous his interpretations are is "disruptive." Okay, there is a user who has been making allegedly disruptive criticisms for two years now, filling process pages with tendentious argument, and he's currently unblocked. Who unblocked him? Ottava. Obviously, it depends on whose ox is being gored. Enough. Policy provides for a basically unlimited number of mentorships and candidacies, though certainly if multiple requests became a problem, that would be addressed. Ottava extended the probationary period by asking for it, which enjoyed the implicit consensus of no opposition (and consistency with Candidates for Custodianship/Diego Grez), now he claims that the probationary period expired at 30 days, allowing him to do what he could not do during the period. It will come out in the wash. Watch.
- Any uninvolved custodian who considers my comments disruptive may warn me against it, on my Talk page. That has not happened yet. If even an involved custodian provides such a warning, I will respect it, while possibly appealing it according to due process. No longer my mentor, Ottava has no special authority any more. --Abd 01:09, 2 August 2010 (UTC)
- From what I can see, Abd was not provided with a 48 hour period to find a new mentor before removal of custodian rights. I think such an opportunity should have been provided, as per Wikiversity:Custodianship. I also think that it should be allowable for a Wikiversity user to undergo another period of probationary custodianship if a mentor doesn't recommend for custodianship. What do others think? -- Jtneill - Talk - c 08:23, 2 August 2010 (UTC)
- Thanks. This is what I've been saying. I have filed Wikiversity:Custodian_feedback#Ottava_Rima regarding this sequence. Wikiversity already has excellent and clear policy on obtaining custodianship. I'm not rushing about to find a mentor at this point, so there is a good chance that the 48 hours will expire without my finding a new mentor. Policy provides that I may reapply. While I could request that you resysop, because of improper removal, there is no need for that, it could waste Ottava and the steward's time if I don't find a mentor promptly, and less than two day's custodianship isn't worth the trouble.
- I support the requirement that there be an approving custodian mentor, it is unfortunate that the present candidacy turned out as it did, but it may have been unavoidable, that is, a conflict appeared between what I saw as my duty as a custodian, to the community, and Ottava's position. As mentor, Ottava, I will again affirm, had the right to withdraw his support, unconditionally. He also had, per my prior agreement, the right to immediately request desysopping, but only if I disregarded his request to stop using tools, which he did not request. (I would have complied, it was a clear obligation.) That could become part of policy, a mentor should be able to restrain the probationary custodian by definitive action during the probationary period -- which lasts until the probationary custodian is promoted, or the tools are removed as described in the policy. "Four weeks" is the minimum period, not an arbitrary cutoff when probationary custodianship expires like some kind of pocket veto. I'll address this on the policy page. --Abd 13:17, 2 August 2010 (UTC)
- Minimum? You can' just make up words like that. "During your mentorship period of four weeks" It says "of". Not "of at least". There is no "minimum". It is a final amount. Ottava Rima (talk) 13:42, 2 August 2010 (UTC)
- Please show an example of a probationary period that was not more than exactly four weeks ("final amount"), from provision of tools to either confirmation or removal. Until removal, a probationary custodian is a custodian, with all custodial privileges, per policy. The idea that at the end of precisely four weeks the "probationary period" ends leads to the preposterous situation that we have a probationary custodian, with the tools, who is not "in the probationary period." There is a anomalous period provided in the policy, where a probationary custodian is still probationary, not permanent and not desysopped, but without a mentor, until the original mentor requests desysopping (after 48 hours if no new mentor has appeared). It's clear, crystal clear, in fact. This is currently under discussion at Wikiversity talk:Custodianship, and there is no support for Ottava's position, except possibly from JWS, who hasn't made it clear exactly what he thinks the policy is, in practical terms, he's just sure that it's not being followed. As usual. --Abd 16:08, 2 August 2010 (UTC)
- My mentorship period started 14 September 2008 and I was nominated 11 October 2008. 27 days and a few hours shy of 28 days. The voting started on the "one month" time exactly, 14 October 2008, but could have started from my acceptance. My mentor, midway through my mentorship, had to be switched. I also had at least 4 other admin offer to be my mentor without my asking. Ottava Rima (talk) 16:17, 2 August 2010 (UTC)
- Thanks, Ottava, for the example, which shows a number of things. First of all, your probationary custodianship was more than the "four weeks" that you have been insisting on. Your probationary period began from 10:23, 14 September 2008 until an unspecified date, since there was no 'crat close, but we can take the 'crat archiving of the discussion as adequate: 23:46, 21 October 2008. !voting was apparently opened 14:30, 11 October 2008, which was, as SBJohnny wrote, early from 30 days, it was actually a day early from four weeks, the actual period established by policy. (policy as it stood then requires a five day period after 4 weeks, which would then terminate on 17 October.) And this shows how rigid adherence to the literal deadlines in policy is not necessarily followed, if there seems to be no clear reason for waiting. That was a technical error, because the "probationary period" is an important aspect of the process, and opening !voting early could prejudice the !vote. But it didn't matter then, you had no opposition and six support !votes plus the replaced mentorship approval of SBJohnny, I wonder what he'd think now! I see now that you were originally mentored by JWSSchmidt. Did that end because he lost his tools, or because he set a condition that you did not want to accept? And you were also supported by Salmon of Doubt, that's an odd couple, though support for the start of mentored probationary custodianship is actually moot. It's not required, the discussion and question page beginning mentorship is an opportunity for the community to oppose and try to convince the mentor not to mentor, but creating a probationary custodian is a privilege, I presume, of a full custodian.
- !voting from acceptance would be contrary to policy, my opinion. Certainly that's not what the policy provides for. People may comment during the period, though. Voting isn't opened until the time has elapsed.
- The discussion doesn't show a 'crat close, a technical oversight. Mu301, who I think was a 'crat at that time, archived the discussion, though, on October 21, which suffices. The approval was obvious. Now, I can show many examples of probationary custodianships where the period was longer than four weeks, until removal or confirmation. But let's see what the community says.
- Ottava, you were a probationary custodian from sysopping at 10:23, 14 September 2008 to close, 23:46, 21 October 2008, that's 37 days. Are you claiming that you were not a probationary custodian, subject to mentorship, between the ending of the four week period and the close? --Abd 17:00, 2 August 2010 (UTC) this section was put up and then edited to correct errors; the edit collided with the edit of Ottava below, so Ottava is responding to the previous version. --Abd 17:12, 2 August 2010 (UTC)
- The vote is not part of the probationary period nor is there any way to construe it as such. Furthermore, the mentor statement was put up while SB Johnny was only one a of a handful of my mentors at the time. Yes, I had multiple ones because of the situation and none of the admin wanted me to go without having a mentor or not meet the full custodian status. Ottava Rima (talk) 17:08, 2 August 2010 (UTC)
- And this matters because? As to "any way," Prior to the close, Ottava was not confirmed as a permanent custodian. If he is not, as he's claiming, a probationary custodian ("a custodian in the probationary period, where tools are held prior to permanent custodianship"), then what kind of custodian is he? It matters. If he is a probationary custodian, he's still under mentorship (or in the anomalous period of 48 hours after withdrawal or rejection by a mentor), and even if the mentor has approved, the mentor could withdraw that approval, and, as I interpret the policy, such a withdrawal would require a mentor substitution, and if there was no substitution, a confirming close would be contrary to policy (but, note, a 'crat could satisfy policy simply by substituting himself or herself as mentor), but, even more to the point, the original mentor could go to meta and request desysop if 48 hours have lapsed, thus terminating the probationary custodianship. That's moot in Ottava's case because he had a mentor who stuck with him through the !voting period. I do think I know why it's so hard for Ottava to understand this. --Abd 17:19, 2 August 2010 (UTC)
Review of specific actions, Abd's statement[edit source]
I have prepared a page with a list of every sysop action I took, and an explanation of what I was doing, my intention. Comments may be added to the page, at User talk:Abd/Custodian actions. --Abd 01:12, 3 August 2010 (UTC)
Full Custodian Vote[edit source]
Lets stop cutting hairs and move on. Please share your thoughts below and express your support or opposition to making Abd a full custodian. -- darklama 17:20, 2 August 2010 (UTC)
- Where is the nominating statement from the mentor? --JWSchmidt 17:48, 2 August 2010 (UTC)
- There isn't one, JWS. Darklama, if you want to proceed with this, you could volunteer to mentor me, immediately, I accept in advance, it would be within the formal 48 hour period, which would give you the mentor rights I accorded to Ottava. My understanding is that you could then relist this on the Candidates for Custodianship page, where it was prematurely removed. However, the procedure requires an approval from a mentor, before proceeding to vote. If you do not approve of my candidacy, you should remove or close (suspend) this section, it is otherwise premature. Personally, I'd rather take some time, my probationary custodianship period was complex, but I'm open to going ahead if people want to. --Abd 18:27, 2 August 2010 (UTC)
- Abd, does this agreement that you made with your mentor mean that he was able to terminate your Custodianship at any time during your probation? "I will suspend usage of administrative tools in any area" <-- It seems that Ottava suspended your usage of tools in all areas. --JWSchmidt 18:37, 2 August 2010 (UTC)
- No, the agreement did not mean that. It meant what it said, I'd highly recommend reading it. In summary, it allowed Ottava -- or any "supporting administrator," to reverse any of my admin actions (which means that it would not be wheel-warring), and also to require me to suspend tool usage immediately upon specific request, and it provided that such a supporting admin could also request desysop immediately, with my prior consent, if I violated the requirement. I.e., didn't stop. Ottava never issued the prohibition specified, but went directly to a desysop request based on lapse of time, contrary to policy and procedure and not based on the agreement at all. Ottava did not suspend my use of tools, rather Ottava misled the steward as to our policy, which gives me 48 hours before the withdrawing mentor may request desysop, to find a new mentor, thus inducing the steward to remove the tools. You ought to be familiar with that one.... I have not contested it because it would only gain two days, per our policy, unless a new mentor shows up. Not worth the trouble. Just like I didn't revert war to insist upon keeping this listed on the page above, though, by policy, this page is still open today. --Abd 18:56, 2 August 2010 (UTC)
- Ottava seems indecisive in whether he still supports you as a custodian and is your custodian mentor, or not. I think putting the decision to a vote is within policy because of that, and should be done instead of nitpicking on the details of the policy. However if that does not satisfy you I am willing to counter Ottava's indecisiveness with some indecisiveness of my own. I'll be your mentor if there is community support to make you a full custodian. How does that sound? -- darklama 19:01, 2 August 2010 (UTC)
- I don't think he's actually indecisive, he's clearly concluded that I should not be a sysop, though I suppose he could change his mind (greater miracles have occurred), and he's making noises about blocking me or banning me. He's made apparently indecisive statements about whether he is still my mentor or not, but only because, I assume, he thinks that he might be better able to block my candidacy as my mentor. In fact, he's gone too far, he's rejected the candidacy, and if he sticks with that, policy would suggest that this is over in 48 hours. However, you have opened up !voting, Darklama, but nobody has !voted yet, so it's not too late to close this. Once !voting has actually started, my sense of tradition, if not policy, is that it continues. Ragged about the edges, but, after all, this is a wiki. It takes some time to get used to this, some people don't understand it even after years. --Abd 22:08, 2 August 2010 (UTC)
- It sounds circular to me, since determining that condition requires the precedent condition. My interpretation of policy is that this vote cannot proceed without the actual approval of a mentor. My suggestion is that if you actually are willing to approve, provided others approve, that you go ahead and provisionally approve, which you could withdraw for whatever reason. My interpretation is that a 'crat cannot close one of these votes finding for sysopping, without the approval of a mentor, and that approval could be withdrawn. Note that if the community really does support the candidate, and a mentor withdraws, it should be easy to get another mentor. I could seek another mentor, but this is likely to be over soon anyway, if you want to take this through a vote. It's just that the approval of a mentor is clearly required for a vote. Ottava ain't gonna do that, my crystal ball tells me. Your provisional approval would put me under your supervision. Trouble with Ottava didn't arise because he withdrew his support, it was because he did not follow policy about it, in numerous ways, as others have now agreed. It was all set up to be very easy, and it only became disruptive because the obvious intention and language of policy wasn't followed. --Abd 19:30, 2 August 2010 (UTC)
- You have already been through a mentoring process, and there may be no need to go through it again. A vote can proceed, but it may not count without approval of a mentor. If the community approves you as a full custodian, than I'll be your mentor and approve you as a full custodian too, and jtneill can than proceed with things according to policy. You may consider those my terms and voice whether you accept the terms or not. Consensus can overrule any policy as well, so if people support below than it doesn't really matter what the policy says. -- darklama 19:42, 2 August 2010 (UTC)
- That's okay with me, I've merely been suggesting that policy is sound here, but, obviously, the community can create policy, so it can overrule it as well. On the other hand, there is supposed to be a decent !voting period, and right now this Candidacy isn't listed on Wikiversity:Candidates for Custodianship page. At the least, Ottava's premature removal should be reverted. I tried. He reverted me and threatened to block me for it. He didn't need to, I don't revert war unless I have a Damn Good Reason. Better be really good. It wasn't, since, by policy, without a mentor, it was almost moot. If you have opened voting, it's not moot any more, but I think I shouldn't be the one to change it back. In any case, the procedure you want to follow does concord with the spirit of the policy. If successful the 'crat would be closing a supported candidacy, with a declared mentor at the end, which is what counts. If unsuccessful, that's fine, too, this can just be closed, period, nothing to do. It is not important that I gain tools immediately, if ever, that would be the only difference. --Abd 19:59, 2 August 2010 (UTC)
I think this is problematic to be having a vote without a mentor nominating for full custodianship. Clearly Ottava Rima terminated the mentor-mentee relationship and had Abd's sysop rights removed. There is some doubt about the procedure that took place here (i.e., not allowing 48 hours to find a new mentor during an extended probationary period). However, I am concerned that a premature vote here risks convoluting the knot even further. Personally, I'd prefer to see us take a couple of steps back and for Abd and any willing mentor to start fresh with a new nomination, probationary period, and nomination for full custodianship if/when the mentor and mentee decide to take that step. -- Jtneill - Talk - c 06:26, 3 August 2010 (UTC)
- Jtneill, it seems to me that the WV custodians and others participating in discussions are thinking and speaking of collaborative learning, in principle, whereas, to the contrary, hopelessly suspicious of disruptive self-righteous behavior, in practice. Put otherwise, they look like having no intention from the beginning of collaboration for problem-solving and trouble-shooting, hence a deadlock with no breakthrough in sight. That is why Wikiversity:Colloquium#Proposal to create a Cite namespace of my initiative has been practically dead, not to mention almost all the other issues at hand.
- Take this agenda for example. Your previous comment, which should have been taken very seriously to collaborate anyway, was "Abd was not provided with a 48 hour period to find a new mentor before removal of custodian rights. ... What do others think? -- Jtneill - Talk - c 08:23, 2 August 2010 (UTC)" [my bold face]
- What was the result? Practically no one has responded to you. Your bureaucratic moderating gesture had been entirely ignored to no effect, I note seriously! Indeed, no one else than Abd and Ottava in question, only lacking in neutrality, has responded. Ottava should have responded to you rather than Abd. So should others, before they did anything else. For this would be the very right way of being colloaborative without being disruptive, as I understand. To me it is the moment the prestigeous burearcrats should show up!
- BTW, I have only one moral principle, moral reciprocity, such that I do good or evil as you do! Fair enough?
- -- KYPark [T] 10:40, 3 August 2010 (UTC)
- In response to Jtneill's comments, I oppose the idea of another probationary period. Abd has already had custodian rights for about seven weeks rather than the usual four and so it is unclear what would be gained. I haven't seen much to suggest that Abd would have acted any differently had he been mentored by someone else. The community should be able to adequately judge Abd's use of custodian rights from that period since it isn't like he hasn't been active and we usually feel able to assess a candidate for custodianship after four weeks with the tools. We are in uncharted territory here but I think a bureaucrat should respect the outcome of the vote below since the community can decide to do things differently as they choose and anyone who doesn't think we should do things differently can oppose as JWSchmidt has done. Adambro 10:43, 3 August 2010 (UTC)
- My doubts are two fold. a) Ottava seems not to have been clear in his intent to terminate Abd's custodianship before doing so and give him a chance to find a new mentor, and b) Ottava says he is still Abd's mentor. Both things put together suggest Ottava is indecisive. If Ottava is still Abd's mentor than the time has come to seek if the community is willing to make Abd a full custodian. If Ottava is indecisive, the community should of been deciding whether Abd should be a full custodian as well. The Wikiversity Community may also not feel that Abd needs to go through the probationary period again. In my opinion this vote is a good way to establish where the community stands, and what if anything should happen next. Jtneill, you wanted to know what others think too, surely this is a good way to find that out? -- darklama 11:33, 3 August 2010 (UTC)
- No, Darklama! Prior to voting, you and others should have responded first to Jtneill's critical question of watershed, What do others think? Procedurally, all of you are duly expected to say anything, whether negative, affirmative, or whatever, but not so expected to say anything anywhere else! Otherwise, all of you are simply helpless and hopeless, I fear indeed.
- I myself was foolish to take it easy enough to support Abd's full custodianship, as easily misguided by your good will such that "If the community approves you as a full custodian, than I'll be your mentor and approve you as a full custodian too, and jtneill can than proceed with things according to policy." Thus, I seriously ask all the others here to admit as much fault as I admit myself.
- -- KYPark [T] 13:06, 3 August 2010 (UTC)
Support full custodian[edit source]
- Support. Give the guy a chance. I have seen no evidence that would indicate he would abuse the tools. Tisane 01:32, 3 August 2010 (UTC)
- Support. Throughout my virtual reality in WV though no more than the last two months, Abd has impressed me more than any other custodians, apparently remaining wiser, busier, kinder, bolder, sincerer, more constructive, consistent, moderate and persuasive. I am quite sure of his large capacity of problem-consciousness and problem-solving. I would support even Abd's Bureaucratship. Believe me. :) -- KYPark [T] 03:57, 3 August 2010 (UTC)
Oppose full custodian[edit source]
- Oppose - The most important thing to oppose over is that he hasn't shown edits in any of Wikiversity's learning spaces nor has he shown a committment to the project. His level of interaction is related to the same topics of those at Wikipedia Review and are more connected to drama than learning. He has abused the tools on multiple occasions. He stated he wanted adminship for rollbacks. He did not do any of the work he promised to do, and instead got into long fights with members of our community about various issues, such as making claims about policy that he lacked the experience to back up. Furthermore, with arbitrary acts such as unblocking Thekohser without discussion showed a lack of actually relying on community input before using the block feature. He was repeatedly told to stop fighting with JWS and stop being incivil to him through multiple emails and refused to follow through with that. There is plenty more, but I'm not going to make a multi-paragraphed statement. Ottava Rima (talk) 02:09, 3 August 2010 (UTC)
- Oppose - The candidate was not nominated for full custodianship by his mentor. This vote for full custodianship was called for in violation of Wikiversity policy. If any bureaucrat is tempted to give the candidate custodial tools on the basis of this illegitimate vote, I want a chance to more fully express my objections to this candidate. A bureaucrat should terminate this illegitimate voting for a candidate who was not nominated by his mentor. --JWSchmidt 04:49, 3 August 2010 (UTC)
Oppose - I'm agree with Ottava Rima... --Bermanya 22:30, 3 August 2010 (UTC)
Oppose Reluctantly I must oppose this candidacy. Abd has lost a lot of my respect through actions that indicate to me that he is not qualified to wield the mop at this time. Ultimately, the fact that he did not honor his mentor shows me that we cannot find him worthy of the honor of custodian at this time. This opinion is final and irrevocable. Geoff Plourde 18:17, 4 August 2010 (UTC)
Oppose This conversation has been rolling down hill for a while. Based on it I do not think he is ready. Thenub314 19:44, 4 August 2010 (UTC)
Oppose I am opposed to full custodianship primarily on procedural grounds i.e., the mentor didn't recommend for full custodianship and a new mentor wasn't found before a discussion and vote about full custodianship was conducted. However, I have been encouraged by Abd's willing engagement and good faith efforts to help and contribute to Wikiversity, his civility, and his transparency in discussing his ideas and actions. -- Jtneill - Talk - c 15:21, 6 August 2010 (UTC)
- Concur. I thank Jtneill for his help and support, and I look forward to future cooperation. I am unopposed to closing this, and considered summarily archiving it, but the arguments for allowing the community to continue comment to the end of the normal period prevailed for me. This has all been useful, in my opinion, and I thank all who commented, either here or on User talk:Abd/Custodian actions or elsewhere on what I have done. All. No exceptions. --Abd 15:31, 6 August 2010 (UTC)
Discussion full custodian[edit source]
- Question Could you clarify the status of your relationship with Moulton? Have you met with him in real life or arranged to do so? Adambro 17:38, 2 August 2010 (UTC)
- I attempted to meet with him once when I was in Boston for a colloquium, it fell through. There is no current arrangement to meet, but I do hope to meet with him relatively soon. My goal is to negotiate some settlement with him that would be acceptable both to him and to the Wikiversity community. I don't know if that's possible, but we will never know if we don't try, and I'm willing to put personal time into it. The result could save a whole boatload of disruption. If it fails, things won't be worse! Thanks for asking. --Abd 18:29, 2 August 2010 (UTC)
- Thanks for the clarification. I know you feel strongly about avoiding conflict of interests and so it seemed relevent since you've been involved to some degree with dealing with Moulton on-wiki and I became aware of a suggestion that you two might have arranged to meet. Regarding Moulton, my view is that he has shown he isn't really interested in negotiating and so I don't think we should keep trying, I don't think it is necessarily true that more failed attempts won't make things worse. As far as I am aware, Diego was mostly responsible for inviting Moulton to create the account Caprice and as far as I can tell, that effort provided a further demonstration of why his block is appropriate. However, it also seemed to reignite the Moulton situation and prompt him to make sustained attempts to evade his block and involve himself in community discussions. As I understand it, Moulton wasn't very active in evading his block recently before Diego's involvement. I'd suggest that Diego's failed attempts to negotiate with Moulton have caused disruption. I would therefore suggest that we shouldn't keep trying to negotiate if nothing seems to change and it would have been preferable to have had a proper community discussion about Moulton before these attempts to negotiate with Moulton were commenced. Adambro 18:54, 2 August 2010 (UTC)
- Question - This deleted page in your user space. Did you create that? Did Moulton or someone else create that? For what purpose was it created? Ottava Rima (talk) 18:55, 2 August 2010 (UTC)
- Like I'm supposed to remember? It's deleted, Ottava, I can't read it, courtesy of your premature desysop. However, I might have been testing the ability of a logged out editor to create a user subpage, since you were asking Thekohser to do this. How about undeleting it so I can see? If it's something else, I'll respond! --Abd 19:20, 2 August 2010 (UTC)
- Neutral I have seen many times Abd all around the wiki, but I can't support or oppose. He has done a good job, but I don't know what were the circumstances that Ottava Rima abandoned the mentoring of him. Diego Grez 02:15, 3 August 2010 (UTC)
- And @Adambro, I suggested Moulton to create that account with good intentions, I came here to help as a volunteer, just like the rest of you. Nobody is perfect and if I don't do something right, I won't get angry if someone changes it. {{sofixit}} :P Diego Grez 02:33, 3 August 2010 (UTC)
- Diego, your action was fine, as a test of the waters, and you did watch the account (Caprice) and you did reblock when there was an apparent problem. Recent matters have been brought to my attention that reveal more of the depth behind all this, confirming a little of what JWS has been noisily proclaiming, but now and here isn't the place to bring that out. We need a new and careful community review of the whole situation with Moulton, there are ways, I believe, to actually resolve this without damage, but it will take time, and I don't need custodial tools to do it. You tried to do something good, and that's all that is expected of custodians. You have my approval for full custodianship, precisely because you "won't get angry if someone changes it," which means that there is no risk from your mistakes, if they are mistakes, you'd have to be making lots of them for it to be a problem, and you don't. Weird, isn't it? Ottava went to meta to claim that routine practice would be to terminate custodianship because more than four weeks had elapsed, in order to induce a steward to yank the tools outside of actual process, but .... how long has it been with you? --Abd 17:00, 3 August 2010 (UTC)
- to JWS - Terra's RfA had a mentor who opposed. I have no problem with Darklama's calling for a vote, to be honest. Ottava Rima (talk) 13:14, 3 August 2010 (UTC)
- Nice to be able to agree on something again (it used to be common). In general once commenting has begun, even out of process, and with all processes, it is the norm to complete the comments. The closing bureaucrat can still review the whole thing and decide based on arguments and the presence or absence of any necessary elements, such as an approving or at least consenting mentor, and could even waive that if there was sufficient basis in community consensus and sound argument. Bureaucrats are servants of community consensus, and of policy only insofar as that reflects actual consensus. Where a contrary consensus is clear, and the arguments are sound, a bureaucrat is free to set aside the technical requirements of policy. --Abd 16:51, 3 August 2010 (UTC)
- What has been done can't or won't be undone.
-- KYPark [T] 06:11, 4 August 2010 (UTC)
- I have no problem with Darklama's calling for a vote" <-- It is clear that there are a few sysops who "have no problem" violating policy. --JWSchmidt 15:38, 4 August 2010 (UTC)
- See : Wikiversity:Community_Review/Problematic_actions#Darklama_and_Custodianship -- KYPark [T] 12:31, 5 August 2010 (UTC)
- Point of order. While the mentoring process was set up as a means to help us get enough custodians to run the site in the early phase of wikiversity, there wasn't any discussion of making it the only means. It is a good system, but community consensus is the actual requirement. The current system has its share of problems. In fact I have seen controversial candidates ushered in by unsuspecting and often well-meaning mentors, even against community objections. Hillgentleman | //\\ |Talk 10:04, 4 August 2010 (UTC)
- Indeed. I pointed out before that the WMF requires community consensus for someone to be an admin to ensure that crats do not just appoint whoever they want. Ottava Rima (talk) 13:37, 4 August 2010 (UTC)
- Community consensus is still community consensus even when established beforehand. Theoretically at least, there could be a community consensus that crats can appoint whoever they want as an admin, and that could last as long as no new community consensus isn't opposed to doing things that way. -- darklama 13:52, 4 August 2010 (UTC)
- The WMF requires -specific- community consensus on a -specific- individual. They require it to be done through a vote like system. There have been instances where a crat started randomly appointing people because they wanted to and they were removed. Small wikis are also denied a crat just for that reason. Ottava Rima (talk) 14:09, 4 August 2010 (UTC)
- Can you highlight where this policy is documented? I've had a quick look around Meta and couldn't find anything. Cheers. Adambro 15:26, 4 August 2010 (UTC)
- I don't know where it is off the top of my head, but things like "For permanent sysopship please provide a link to the local community approval. For temporary sysopship please state for how long and for which tasks you need it, and link to a local announcement." are part of long term consensus on the matter and how the WMF handles it. Otherwise, a local project could be taken over by a crat and a handful of friends who are all admin and they shut out everyone else. Problems like that happened at ru.wiki with meta being used to remove various people involved. Ottava Rima (talk) 16:40, 4 August 2010 (UTC)
- When Wikiversity launched, Cormaggio was given bureaucrat tools and he appointed a few sysops to deal with immediate tasks like protecting the wiki from vandals and doing page imports of existing Wikiversity pages. There were soon requests for sysop tools coming from people who Cormaggio did not know. As shown in this chat log, Cormaggio suggested that Wikiversity, "have some sort of nomination system and not voting system for choosing admins". Sebmol set up such a system and by the next day the first probationary custodian was created, see Wikiversity:History of Wikiversity/Custodianship. --JWSchmidt 15:19, 4 August 2010 (UTC)
- Thanks, JWS. There is good wikitheory behind the Wikiversity probationary custodianship system. I would not have suggested bypassing it, but there is also wikitheory behind keeping the vote open here, once some people voted. Bottom line, if the closing 'crat decides to promote, and there is a community discussion to point to showing adequate support from the community, it is highly likely that a steward will not nitpick the 'crat decision. Bureaucrats are specifically trusted to make the decisions in gray areas. Otherwise the 'crat would be superfluous. Because emergency desysop is always possible (this can be abused, but it requires a high-level functionary to sign on to it, which is a minor level of protection), local 'crats are given the ability to award but not to yank admin tools. If they could yank the tools, it would be like the 'crat was every custodian's mentor, and the WMF consensus is that it is dangerous to create such a dictator, making unilateral decisions. Our mentorship system allows this kind of supervision, by a single mentor for a single probationary custodian, and the mentor is responsible for errors of the mentored probationary custodian. So, basically, the more Ottava claims that I was being disruptive, the more he impeaches himself.... What he's done is to go back, now, and complain about actions that didn't receive a reprimand or reversal from him at the time, it's clear why he made his decision, and, shall we say, he was involved, it was personal. In fact, I wasn't disruptive with tools, unless blocking Ottava for incivility after an ignored warning was disruptive, which the community should decide, and the only prior complaints from Ottava (by email) were about discussion with JWS, which I could certainly continue regardless of tool status. He apparently thought I should just ignore JWS.
- Yet Ottava is supporting an indef block for JWS. The fact is that Ottava unblocked JWS with conditions, and has not enforced the conditions; Ottava could reblock at any time without warning, my judgment. Basic principle: any custodian can undo what the custodian has done. Always. I proposed a topic ban for JWS, to address the actual disruption, and providing for ways that JWS could still engage in criticism under restrictions designed to avoid the sprawling useless discussion we have seen for two years. Those who support the block did not support the ban, which makes no sense unless what is really desired is to get rid of the guy who has been criticizing them. Tangled mess. I did not create it. I've also, at the same time, only responded to a fraction of JWS's questions of me, and JWS is complaining about my lack of response.
- You can't please everyone, but it seems that if I aim for the middle, the extremes are pissed. Bad situation. If the middle doesn't show up and support moderate but effective action, this thing is sunk. Hint: this is how Wikipedia was largely taken over by extremists. They would show up to !vote, and the middle was disgusted by the whole process and all the flame wars, and stayed away. --Abd 16:05, 4 August 2010 (UTC)
- You were told that your unilateral unblock of Thekohser was problematic multiple times. In the above multi-paragraph statement, you pretend that you were not told it was problematic and an abuse. This is very problematic. Ottava Rima (talk) 16:27, 4 August 2010 (UTC)
- Summary: Ottava is an abusive sysop, and he realized that I was a threat to that, though, in fact, I would not again use tools touching him, it would be clear recusal failure. I don't do recusal failure. --Abd 18:07, 4 August 2010 (UTC)
- "It caused no harm" is exactly why you should not be granted the custodian tools. You attempted to unblock a globally locked user without consensus and claim that it would cause no harm. That is a severe lack of judgment. The rest is all dissimilation and distraction from your own faults. This is about you, not me. So far, you have taken no responsibility for any of your actions nor have you attempted to be part of the community. Ottava Rima (talk) 18:16, 4 August 2010 (UTC)
- I'll stick with the statement that it caused no harm. Ottava is speculating that it might have caused harm. No contradiction. Simple. Ottava can't read accurately, he sees what he expects to see. As to unblocking a globally locked user, there is no consensus here against doing that, and there was plenty of discussion about how to do it, with no strong opposition. This is some kind of "major abuse" that Ottava has made up out of his sense that if he doesn't valiantly keep Thekohser out of here, the gods will descend tossing thunderbolts around. They won't. They aren't out for revenge against Thekohser. The only discussed consensus at meta was that local wikis should make the decision. I'll note that Ottava offered to unblock Moulton, as Caprice, if Moulton would promise not to out users. If what I did was offensive and problematic, what Ottava did was clearly quite as offensive (promise something that he now considers abusive). No, it is quite obvious. When I blocked him, Ottava went back and regurgitated everything he hadn't liked but was not willing to oppose openly at the time. He had not complained that I was abusing tools, he only didn't like that I was "arguing with JWSchmidt." Which didn't involve use of tools. He could have asked me to stop using tools, in whole or in part, at any time. He didn't. But when I blocked him for blatant incivility, repeated after warning, which I understand to be completely within policy, it was minutes for him to go to meta and request a "routine" -- unprecedented and contrary to clear policy -- desysop. The block would not have been repeated, or I'd be making a mockery of everything I've written about recusal failure. Look, this process here is about me, but I don't really care about that. I do care very much about the ownership of this project by Ottava. A negative !vote just opposed because I didn't "respect" my mentor. I'd like people to think about what a probationary custodian should do if he discovers that his mentor is seriously damaging the project. Where should his loyalty be? To the mentor or to the project? The mentor had the unrestricted power to stop any custodial action of mine, but not to stop me from expressing my opinions. Demanding "respect" for a mentor may be some kind of good advice, for someone who desires to gain the mentor's recommendation, but it's not good advice for the welfare of the community, and that !vote calls my attention to a serious attitude problem. By process, I should not have been immediately desysopped unless I used tools against Ottava's permission (that was the due "respect," in fact), I should have had 48 hours to find a mentor, and if I didn't, then this process should have been close with immediate desysop. Simple. Ottava made it very complicated by his out-of-process actions, leading then, to other out-of-process actions, such as the opening of the vote by Darklama. Don't do that again!--Abd 22:05, 4 August 2010 (UTC)
Questions of KYPark[edit source]
This is some kind of "major abuse" that Ottava has made up out of his sense that if he doesn't valiantly keep Thekohser out of here, the gods will descend tossing thunderbolts around. They won't.
Did Ottava say that seriously or jokingly? -- KYPark [T] 13:59, 5 August 2010 (UTC)
- Ottava did not say that, it was not a quote. That is a slightly sarcastic summary (sarcasm can be effective for a brief summary) of what I know of Ottava's motivations from what he's written in many places, including off-wiki. He believes, I infer, that he is protecting the wiki from outside interference, up to and including a feared closing of Wikiversity. --Abd 17:47, 5 August 2010 (UTC)
Ottava offered to unblock Moulton ... if Moulton would promise not to out users.
Do you believe Ottava would keep his promise 100% to unblock Moulton if Moulton promises not to use Ottava's real name? -- KYPark [T] 13:59, 5 August 2010 (UTC)
- That was not the requested promise. It was not "out users," in general, though the specific example that Moulton then created was using Ottava's real name. Moulton's position is that this real name is well-known, it's not a secret, and has been used, openly, by Ottava off-wiki in promoting his association with Wikiversity. I believe that Ottava would have kept his promise, which was partly my point. Ottava promised to do what he later considered improper for me to do, that is, unblock without a prior community discussion. --Abd 17:53, 5 August 2010 (UTC)
... he only didn't like that I was "arguing with JWSchmidt."
What was the main reason why he didn't like you arguing with JWS? -- KYPark [T] 13:59, 5 August 2010 (UTC)
- Probably the same reason I don't like arguing with JWSchmidt. It usually goes nowhere, accomplishes nothing, so I've confined it to a few exceptional cases. I think there are others, particularly Darklama, but not limited to him, who also have "argued with" JWSchmidt. --Abd 18:14, 5 August 2010 (UTC)
- It sounds extremely funny that the the main reason for the main cause of the trouble, as you see, is unclear! Was Ottava such an authoritative mentor? Almost always? As if the owner of this project? -- KYPark [T] 00:35, 6 August 2010 (UTC)
I do care very much about the ownership of this project by Ottava.
This sounds a striking allegation. The community should know about his ownership. Could you let it do so? -- KYPark [T] 13:59, 5 August 2010 (UTC)
- Yes. I can substantiate it, but that is really, in the end, irrelevant here, beyond a suggestion as to why Ottava might be biased in his recommendation and arguments. I have started with Custodian feedback which is where a dispute with a custodian that can't be resolved by direct discussion should go. But that's a narrow report, the full issues would be considered in Community Review/Ottava, which would be premature, and I hope we don't have to go there. I'll note that if there is not substantial community comment on the Custodian feedback page, leading to a resolution of the issues, it is quite possible that a Community Review will be necessary. Only a Community Review, absent emergency, can desysop a permanent custodian. --Abd 18:14, 5 August 2010 (UTC)
- Are you sure that "Only a Community Review, absent emergency, can desysop a permanent custodian"? Adambro 18:19, 5 August 2010 (UTC)
- Strictly speaking, only a steward can desysop any custodian. If anyone can convince a steward, it will happen. Normally, though, the steward will want to see a community consensus, absent emergency. The steward may or may not be careful about following WV policy. What the policy requires is a new seven day community discussion, with a local close by a 'crat, and if the 'crat decides on desysopping, the 'crat requests it from the steward's noticeboard. While the policy doesn't exactly specify a Community Review, what else would it be? Under Wikiversity:Obscure discussions/Nothing to see here? Eh... seriously, wherever it is, there should be substantial notice of it in places likely to be seen, perhaps upon some kind of condition so that not just any Community Review gets widely noticed. Desysopping is a drastic measure. But without it available, there aren't any teeth behind policies restricting custodial actions. --Abd 19:05, 5 August 2010 (UTC)
... what a probationary custodian should do if he discovers that his mentor is seriously damaging the project.
How seriously did he damage the project? -- KYPark [T] 13:59, 5 August 2010 (UTC)
- That is as yet unclear; the incivility repeated after warning was the justification for the block, and this is particularly egregious when it is a custodian who is being uncivil. The immediate harm would be a continued opinion by the attacked editor that Wikiversity is unlikely to recover from the serious and ongoing dysfunction, but there are other harms from incivility that is tolerated. I have addressed this in detail in a response to Jtneill on User talk:Abd/Custodian actions. --Abd 18:14, 5 August 2010 (UTC)
I should have had 48 hours to find a mentor ...
Few others than Jtneill attended to this injustice, the resolution of which must be much simpler than voting. Why didn't you insist on the simpler? -- KYPark [T] 13:59, 5 August 2010 (UTC)
- Because I did not want to seek a mentor under rushed conditions, so I considered it likely that one would not offer. Had one offered, within the 48 hours (and, probably, even after, maybe with an additional formality), there would have been a basis for immediate resysop, but I was not willing to request that Jtneill resysop just to gain a few hours of probationary custodianship, and Ottava could easily have prohibited all tool use, if he cared to, thus making it completely useless. (That promise, as written and intended, survived his mentorship withdrawal, if that's interpreted to have taken place, he never made it clear.) I would have left this candidacy in place for 48 hours, then it could have been closed if no mentor appeared. Simple. It was only Darklama who made it a bit more complicated by opening voting; I asked him to reverse that, but he declined. When actual voting started, I accepted it according to wiki tradition.
Ottava made it very complicated by his out-of-process actions, ... such as the opening of the vote by Darklama.
Who mentioned the vote first?-- KYPark [T] 13:59, 5 August 2010 (UTC)
- Without checking, I believe it was Darklama. That was also an out-of-process action, though of a different character than those of Ottava. Not all out-of-process actions are a problem. --Abd 18:14, 5 August 2010 (UTC)
- Summing up, thank you so much for answering my distracted questions in the distressed situation, Abd. You have proved yourself to be far sincerer than I as a mere newcomer would have expected from others, say, Jtneill, Ottava, and JWSchmidt (as in case of Wikiversity:Community Review/Problematic actions#Darklama and Custodianship). I am sure your answers would greatly help this community better judge the current situation of extreme disruption. Cheers.
-- KYPark [T] 00:17, 6 August 2010 (UTC)
Full Custodian Vote, motion to close[edit source]
It's fairly clear that this "vote" will not resolve in a consensus to promote Abd, so the vote should be closed.
- Support, as proposer. While I know Darklama's motivations for starting this poll were both creative and well-intentioned, I'm afraid it's actually backfired and inflated the tensions surrounding this situation. I encourage Abd to find another mentor with whom he can form a more egalitarian relationship, as this would have the additional benefit of giving him a month to absorb what's happened and come at things freshly next time. --SB_Johnny talk 16:36, 5 August 2010 (UTC)
- Support Thenub314 17:07, 5 August 2010 (UTC)
- Neutral I initially opposed the opening of voting here as an unnecessary deviation from policy. However, once it was opened, I accepted that it should be allowed to continue because it allows the community to express approval/disapproval of my actions, thus, even if it closes with inadequate support for promotion, it will provide some level of guidance for a future candidacy. I'm finding it valuable. But I'm not opposed to closing, it's really up to what the community wants, and I have a great deal of respect for SB_Johnny. I don't think that closing it will relieve the "tensions," though, and I'd urge looking at what tensions are caused by the actual voting here, and what are caused by underlying problems. Did, for example, Thenub's opposing vote cause additional tension? I don't think so. Rather, it discloses to me that there is some view that I should consider in the future, perhaps to be discussed. This is how problems are solved, not by sweeping them under the carpet. --Abd 17:45, 5 August 2010 (UTC)
- Abd, I agree that it's an opportunity to learn. I just don't think learning necessarily entails stomping on sore nerves, which is what seems to be happening here. A month to cool off would (IMO) bring a bit of (much needed) maturity and wisdom to the discussion. --SB_Johnny talk 18:30, 5 August 2010 (UTC)
- Support Let's give this nomination the mercy it deserves and humanely kill it. Geoff Plourde 19:05, 5 August 2010 (UTC)
- Comment Following Wikiversity:Custodianship for how long discussion for full Custodianship should be open for, this should be closed in 2 more days anyways. How much longer do you think consensus to close this would take? Seems like it would take longer to reach consensus for the motion to close this than just following how long full Custodianship discussion should be open for. -- darklama 19:08, 5 August 2010 (UTC)
- Comment. This is a 'crat decision. There is enough support for close to justify it at this point, unless opposition appears, but ... the argument for leaving it open for two days is also cogent. As I've written, I personally find this valuable, and I don't think it's actually inflaming any dispute that doesn't already exist independently. There are questions being asked that probably should be asked and answered, and that might be asked anyway, with or without a close. So ... whatever you think, 'crats, 'sfine with me. --Abd 19:18, 5 August 2010 (UTC)
- I agree when to close is a bureaucrat's decision. I was trying to put this discussion into a normal context, granted though this isn't a normal situation. Like jtneill, I think discussing the motion to close distracts from discussing and considering key issues that may affect support or opposition to full Custodianship. The moment I proposed this discussion I was prepared to step back and let jtneill and any other bureaucrat decide what should happen next, like Wikiversity:Custodianship says. I can even agree with describing what I did as cutting corners, since that may be part of the end result, although I also consider the situation is be a gray area not covered by any policy yet, and this seemed like the best way to deal with that particular gray area. -- darklama 14:26, 6 August 2010 (UTC)
- Oppose: I am concerned that corners were already cut - not giving Abd 48 hours to find a new mentor and bringing to vote without a mentor recommendation. So, I think we should let it run for 5 days. I'm also not convinced that some key issues have been discussed i.e., those described at User talk:Abd/Custodian actions are what I imagine a mentor might have brought forward for consideration. In particular, arguably the key one was Abd's block of Ottava - some further discussion about what the community would like to see happen in such situations could be helpful for us all. -- Jtneill - Talk - c 03:30, 6 August 2010 (UTC)
- support closing. According to policy, community discussions of candidates for full custodianship are initiated by the mentor, not some random onlooker, as was done on this page. There is no probationary custodian to make into a full custodian. The probation was terminated by a Steward according to the terms of an agreement made by Abd with the mentor. This is not the correct forum for discussing "such situations", Wikiversity talk:Custodianship is the place for such discussions. --JWSchmidt 05:46, 6 August 2010 (UTC)
- The above comment by JWSchmidt contains a blatant error, I ask him to correct it. The probationary custodianship was not terminated "according to the terms of an agreement made by" me. Period. It was closed out of process, through a deceptive request by Ottava, claiming it was "routine," that was functionally unnecessary because the actual agreement provided that Ottava could, in his sole discretion, prohibit me from using tools, partially or wholly, and it only provided for steward removal of tools if I violated that prohibition, which I did not, because none was issued. If this poll was improper, then any editor, including JWS, could have stopped it. I supported stopping it, but could not personally stop it for rather obvious political reasons, I'd have been accused of trying to avoid allowing the community to give me its opinion. Once it was open and !votes had been made, I supported continuing it to the normal conclusion, thus still hewing reasonably closely to policy. I agree completely with Jtneill's comment. Largely, the community is wasting this opportunity. That's not Ottava's fault, though he can be faulted for not discussing the elephant in the living room, my blocking him, and it's obvious why he has focused instead on quite minor stuff. He does not want that block discussed, because it was based in policy enforcement, neutrally applied. Does anyone think I was itching to block my mentor? Take responsibility, you who actually have the power here. Will you express yourselves and do what needs to be done, or will you sit back and make shallow comments, mere unconsidered opinions, and see what results you obtain? If you like the status quo, what you do is what you get. --Abd 13:41, 6 August 2010 (UTC)
- "a blatant error" <-- Abd, I assume that the Steward who terminated your sysop status read this statement that was made by you. Any Steward reading that would take note of the fact that you expressed the idea that a bureaucrat might terminate your sysop status, while such decisions are made by Stewards. Abd, you wrote, ", which any Steward is likely to interpret as you having granted permission to terminate your probationary custodianship upon request of the mentor. --JWSchmidt 16:34, 6 August 2010 (UTC)
- JWS, a far more frequently correct assumption would be that the steward would read the request only, and if an error in it was not recognized, the steward would simply act, and that is quite what the record shows. There was no reference to my statement, and I'd not expect a steward to read it unless the steward had extra time and was interested. Yes, technically, the comment about 'crat rather than steward was an error. So? The substance was clear; further, 'crat requests for termination of sysop status will routinely be respected without question, unless it appears there is some serious controversy. Stewards will assume that if there is a problem, that another 'crat, if there is more than one, will simply restore the bit, or that if there is only one, someone will complain about the misrepresentation. Because a 'crat was not involved, here, the steward would assume that if this was improper, a local 'crat could reverse it by restoring the bit. Ottava threatened Jtneill with a complaint at meta if he restored the bit, which was pretty outrageous, but I suggested that Jtneill not restore it anyway. At that point, I did not anticipate that anyone would start voting here, so it would have meant only two days' access to tools at best, until policy would require the removal of the bit. Not worth it. And not needed, I have another completely open path to obtain the bit again, if it's considered useful to the community. Please read my agreement carefully. It only allows immediately desysop if I violate the agreement, not simply at the whim of the mentor. If a steward interprets that as allowing immediate desysop, they are reading no more carefully than you. Your interpretation is quite opposite to the actual agreement. And the actual agreement was not mentioned in the report, which, for some odd reason, you never cite. Here it is. Laaknor confirmed the desysop as being in accord with "local policy," but we know it was not, and you know that, too, JWS, so what in the world are you arguing? I doubt very much that Laaknor reviewed local policy, i.e., looked at Wikiversity:Custodianship and reviewed it. I know how stewards work, you apparently do not. Laaknor properly stated that if the removal was wrong, it could be fixed. The steward was working on AGF, which is normal.
- And all this is diversion. What you wrote was that "The probation was terminated by a Steward according to the terms of an agreement made by Abd with the mentor," when the plain text of the removal record is that it was according to representation that the requested removal was routine. Jay Vandenburg, a former Wikipedia arbitrator, correctly noted that it was far from routine. But stewards (properly) don't want debate there. If it was wrong, any 'crat could fix it. The stewards were within discretion, given what they had in front of them, to remove it, and the problem here is that Ottava self-servingly misrepresented WV policy. What you wrote was plainly incorrect, but you have not corrected it. You are complaining, elsewhere, about others who allegedly "falsify" edit summaries, but when a clear falsehood from yourself is shown -- and it's obvious! -- you just repeat it in a different way, not acknowledging your error. That means that, by your own definitions, you are disruptive, a "rogue editor." Rogue custodians should be desysopped. What should be done with rogue editors? Should they be talked to death? Or is there some other remedy available? --Abd 17:15, 6 August 2010 (UTC)
- "a clear falsehood from yourself" <-- Abd, please help me out. Please write a single sentence of the form: "X, a statement by JWSchmidt, is a clear falsehood." Replace "X" by quoting something I wrote. --JWSchmidt 17:46, 6 August 2010 (UTC)
- Sure. The above comment, now bolded in my quotation of it, a statement by JWSschmidt, is a clear falsehood. It is possible to quibble with this. After all, suppose the steward did read all that text on the candidacy page, did read the agreement, and did consider it. But that is a supposition in contradiction to the plain text of the record cited and the confirmation from Laaknor that this was simply local policy that was being followed (i.e., what Ottava had presented as routine.) In an example that JWS previously cited, regarding my behavior, JWS claimed that my edit summary protecting a page was "falsification," when it simply stated facts not subject to interpretation. I.e., for example, Moulton was blocked at the time, that's a fact and not a claim that the block is proper or other matter of opinion. --Abd 18:19, 6 August 2010 (UTC)
Closure[edit source]
Closed as unsuccessful per the principle of SNOW and comments from the candidate and others. Per Wikiversity:Custodianship, the discussion of a candidate for custodianship is to run for five days before being closed by a bureaucrat. The discussion here has now been open for more than four days and it seems extremely unlikely that consensus to make Abd a custodian will emerge. Abd has also said "I am unopposed to closing this". It is important to note that whilst some of those opposing did so on the basis of their opinion of Abd's contributions, others were concerned about the unconventional process. The lack of a mentor was clearly a major problem. The time has come now to move on. I'd strongly suggest that Abd puts aside any aspirations to be a custodian for a while to allow time for things to settle down. I think there are porobably other issues that need sorting out first. Adambro 20:54, 6 August 2010 (UTC) | https://en.wikiversity.org/wiki/Wikiversity:Candidates_for_Custodianship/Abd | CC-MAIN-2021-31 | refinedweb | 18,974 | 60.65 |
14 January 2011 17:15 [Source: ICIS news]
HOUSTON (ICIS)--US-based energy major Marathon Oil’s board of directors has approved a plan to spin off its downstream refining and marketing business, a move followed by a slight drop in the company's stock price on Friday.
The spin-off should become effective on 30 June.
It will create Marathon Petroleum, the fifth-largest ?xml:namespace>
However, the company decided to move forward with the plan, citing a substantial improvement in the global-business and financial environments over the last two years.
The spin-off will allow each company to be more flexible and more transparent, Marathon said. Moreover, each company could pursue its own strategy and goals.
The company intends to distribute one share of Marathon Petroleum for every two shares of
Marathon Petroleum will be based | http://www.icis.com/Articles/2011/01/14/9426249/us-marathon-to-spin-off-refining-business-on-30-june.html | CC-MAIN-2014-42 | refinedweb | 139 | 52.8 |
grid_sampler¶
paddle.fluid.layers.
grid_sampler(x, grid, name=None)[source]
This operation samples input X by using bilinear interpolation based on flow field grid, which is usually generated by
affine_grid. The grid of shape [N, H, W, 2] is the concatenation of (x, y) coordinates with shape [N, H, W] each, where x is indexing the 4th dimension (in width dimension) of input data x and y is indexing the 3rd dimension (in height dimension), finally results is the bilinear interpolation value of 4 nearest corner points. The output tensor shape will be [N, C, H, W].
Step 1: Get (x, y) grid coordinates and scale to [0, H-1/W-1]. .. code-block:: text grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1) grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1) Step 2: Indices input data X with grid (x, y) in each [H, W] area, and bilinear interpolate point value by 4 nearest points. wn ------- y_n ------- en | | | | d_n | | | | x_w --d_w-- grid--d_e-- x_e | | | | d_s | | | | ws ------- y_s ------- wn x_w = floor(x) // west side x coord x_e = x_w + 1 // east side x coord y_n = floor(y) // north side y coord y_s = y_s + 1 // south side y coord d_w = grid_x - x_w // distance to west side d_e = x_e - grid_x // distance to east side d_n = grid_y - y_n // distance to north side d_s = y_s - grid_y // distance to south side wn = X[:, :, y_n, x_w] // north-west point value en = X[:, :, y_n, x_e] // north-east point value ws = X[:, :, y_s, x_w] // south-east point value es = X[:, :, y_s, x_w] // north-east point value output = wn * d_e * d_s + en * d_w * d_s + ws * d_e * d_n + es * d_w * d_n
- Parameters
x (Variable) – The input tensor, which is a 4-D tensor with shape [N, C, H, W], N is the batch size, C is the channel number, H and W is the feature height and width. The data type is float32 or float64.
grid (Variable) – Input grid tensor of shape [N, H, W, 2]. The data type is float32 or float64.
name (str, optional) – For detailed information, please refer to Name. Usually name is no need to set and None by default.
- Returns
- Output of shape [N, C, H, W] data samples input X
using bilnear interpolation based on input grid. The data type is same as input tensor.
- Return type
Variable
Examples
import paddle.fluid as fluid # use with affine_grid x = fluid.data(name='x', shape=[None, 10, 32, 32], dtype='float32') theta = fluid.layers.data(name='theta', shape=[2, 3], dtype='float32') grid = fluid.layers.affine_grid(theta=theta, out_shape=[3, 10, 32, 32]) out = fluid.layers.grid_sampler(x=x, grid=grid) | https://www.paddlepaddle.org.cn/documentation/docs/en/api/layers/grid_sampler.html | CC-MAIN-2020-24 | refinedweb | 433 | 68.5 |
In this post I'd like to talk a bit about the InitializeService method that ADO.NET Data Service writers should implement on their services.
Usually this would have been a virtual method that developers could override, however it was important to stress that this was meant to execute outside the context of a request, and the the initialization occurred a single time, and then "stuck" for every other request.
Now, here are a few interesting things about this method.
For one, you can't reinitialize the service once it's complete - the configuration is cached in an internal static dictionary, so it'll stay there as long as the AppDomain stays around. An AppDomain restart isn't usually a big deal if you're re-deploying the service. Configuration changes can modify the conceptual model (CSDL) provided by service.svc/$metadata, which means that different requests may see a different view of the URL space provided by the service - not a small thing. So we prefer to stay away from anything that can change what the client perceives as "static" on a per-request basis - thus the whole point for single-time initialization.
Now, the service itself doesn't spring into being initialized, so initialization actually happens when the first request is received. However from the above you can tell that it's a really, really bad idea to try and do something based on the requests that's available on the thread at that point (depending on your hosting story), so I urge folks not to do that. It's best to just use the InitializeService method to just set the configuration options that you want and leave it at that.
Another interesting point has to do with error handling. The option for error handling is set during InitializeService. If an exception is thrown while InitializeService is being called, we don't trust whatever was set on the configuration, and instead of the ADO.NET Data Service error handling kicking in, we'll let the exception bubble out. Typically the service will be running as a WCF service, which means you'll get the error page with the blue band on top (when viewed in a browser). To get detailed errors in this case, you can do something like this.
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class YourService : DataService<YourContext>{ ... }
I'll include the IncludeExceptionDetailInFaults warning here, and say that this is something that you only want to use for troubleshooting purposes during development - don't put this attribute in production code!
In the next post, a few more interesting tidbits that have to do with service initialization, but with a focus on the configuration object.
Very commonly, this has to do with how the service was initialized . The service configuration allows
Long on prose and short on code, this post just explores some patterns involving mutable/immutable objects
Trademarks |
Privacy Statement | http://blogs.msdn.com/marcelolr/archive/2008/06/16/so-special-initializeservice-in-ado-net-data-services.aspx | crawl-002 | refinedweb | 484 | 51.28 |
XOR Encryption in C++
Hello everyone, in this tutorial, we are going to learn about XOR Encryption in C++. XOR encryption is difficult to crack by the brute-force technique. In the brute force technique, we generate random encryption keys and match them with the right encryption key.
Algorithm
As we know, when we perform XOR operation between two values, then XOR of the resultant value and any of the previous values gives us the remaining value. For example, if XOR of a and b is c, then XOR of c and a will be b, and XOR of c and b will be a. XOR encryption method uses the above property.
Let’s say we have a string and we want to encrypt our string using XOR encryption. To do this, we will first define an encryption key randomly. It can be any character value. Then we will perform XOR operation on every character of our string. Thus we will have our encrypted string. We can get the original string again by performing XOR operation on every character of the encrypted string.
C++ implementaion of XOR encryption
Here is the C++ implementation of the above method. Have a look at the below code.
#include <iostream> using namespace std; string xor_operation(string inp_string) { char encryption_key = 'A'; string out_string = ""; int i = 0; while(i < inp_string.length()) { out_string += inp_string[i] ^ encryption_key; i++; } return out_string; } int main() { string inp_string = "codespeedy"; cout << "Original data: "; cout << inp_string << endl; string encrypted_string = xor_operation(inp_string); cout << "Encrypted data: "; cout << encrypted_string << endl; string decrypted_string = xor_operation(encrypted_string); cout << "Decrypted (original) data: "; cout << decrypted_string << endl; return 0; }
Output:
Original data: codespeedy Encrypted data: ".%$21$$%8 Decrypted (original) data: codespeedy
In the above example, our encryption key is ‘A’. We can change it to any value. However, we need to know the encryption key to decrypt the string.
As you can see, we can easily encrypt and decrypt our data using simple XOR encryption.
Also read: Implementation of Null Cipher in C++ | https://www.codespeedy.com/xor-encryption-in-cpp/ | CC-MAIN-2021-17 | refinedweb | 330 | 55.95 |
I recently attended an excellent presentation by John Chapman about Windows Communication Foundation (WCF). Before seeing his presentation, WCF was this complete black hole to me. I made an honest effort to learn WCF with the Help files, but every time I thought I "got" it, then it seemed like I didn't. Whenever I tried to read a book about WCF, my eyes would glaze over. I knew it was something that I would need to learn sooner or later, but I was dreading it.
During John's WCF presentation, things clicked for me. I'm sharing the information I learned from him (good work, John!) so you can get up and running with WCF as well. You'll want to download John's code from the presentation, since it has good examples of what I'm talking about.
The basicsInterface creation
The Message class is the fundamental basis of WCF. It is a SOAP-centric class and is the basic unit of exchange in WCF. This does not mean that WCF only uses SOAP, but SOAP is a natural analogue to WCF, and WCF can be exposed as SOAP.
Each WCF service consists of these three major portions:
- Address: how do you reach this service?
- Binding: how do you communicate with the service?
- Contract: what input and outputs does the service have?
When building a WCF service, you start by defining an Interface. You do not need to do this (you can just write a class with the appropriate decorators on the various methods and such), but for the sake of maintenance and separation of concerns, you use an interface. While I am generally against the creation of interfaces with only one implementation, it seems to make sense in WCF.
In this interface, you decorate the interface with ServiceContract, which gives the contract name and namespace; on individual methods, you give them the OperationContract decorator. You can add the FaultContract decorator to a method to indicate what class will be provided in case of an error condition. You would then throw a FaultException<T> object within your code when you have such an error condition, and WCF will turn it into the right kind of error for the client.Input and output
Input and output is an interesting topic. All parameters and return values must be primitive types. You can define a data structure if you like, but it can only contain other data structures or primitives; at the end of the day, all of the leaves on the data tree will be primitives. If you need to define any classes as data structures, the classes should receive the DataContract decorator. This is important because WCF is designed for interoperability with non-.NET systems. Even when a .NET application consumes the service, if the developer has access to the interface (and therefore don't need to use the WSDL or to parse XML trees), they refer to the naming in the various decorators, not the CLR types themselves.
Once you create your interface, you go ahead and implement it.Hosting the WCF service
Hosting the WCF service can be done in a number of ways, including IIS, a console application, or a Windows service. Your code will instantiate the ServiceHost class, and then add instances of binding classes to it. Each binding class gets an address, a port, and a binding type that tells it how to expose itself (such as SOAP). Each binding can have individual security assigned it to if you need to keep people out.
One thing that is interesting is that binding defined in app.config do not need to be instantiated by your code; when your application sees the binding details in the configuration, it will automatically create the binding at runtime. Another interesting point is that the services are not tied to the main thread; if the application is blocking (for example, a console app currently waiting on Console.ReadLine()) the bindings will still service clients.Consuming the WCF service
Consuming the WCF service is also quite easy. If the service is exposed with a SOAP binding, you can import the WSDL; but if you want to work in a more "native" fashion, you can. If you can read the interface that was created (this is why separating the interface from the class is a good idea), you can create a ChannelFactory object and pass to it binding details to receive an IRequestChannel. You can then send the previously mentioned Message objects to the request channel (which sends Message objects in response) in order to call its functionality.
Conclusion
WCF is really not as confusing as it seems at first. The impression you get from the documentation and the books is that it's an awful mess. The reality is 10% of its functionality is enough for 90% of your work, and the rest of it is for special scenarios, such as if you have complex security requirements.
Now that I know the basics of WCF, I am no longer afraid of it, and I am willing to experiment with it a little bit.
More about WCF on TechRepublic
- Book reviews: Get up to speed on .NET's Windows Communication Foundation
- Windows Presentation Foundation: Another piece of the .NET puzzle
- White paper: Build a Queued WCF Response Service. | http://www.techrepublic.com/blog/software-engineer/an-introduction-to-windows-communication-foundation/ | CC-MAIN-2017-09 | refinedweb | 886 | 61.56 |
By Moshfegh Hamedani for Udemy
Interested in more than just a guide? Check out a full ASP.NET course.
TABLE OF CONTENTS: CLICK TO JUMP TO A SPECIFIC SECTION
What We’re Going to Build
Setting Up the environment
Displaying the List of Videos
Step 1: Building the Model
Step 2: Generating the Database
Step 3: Populating the Table
Step 4: Creating a Page to Display Videos in the Database
Adding a New Video
Step 1: Creating a Page to Add a Video
Step 2: Saving the Video to the Database
Editing an Existing Video
Step 1: Creating a Page Populated with Video Details
Step 2: Updating a Video in the Database
Deleting a Video
Step 1: Creating a Page to Confirm Deletion
Step 2: Deleting a Video from the Database
Review
A Step-by-Step ASP.NET MVC Tutorial for Beginners
In this tutorial, I’m going to teach you the fundamentals of ASP.NET MVC 5 and Entity Framework 6.
Before we get started, I’m assuming you already have some experience with C# and Visual Studio. At a minimum, you should be able to write code and have very basic understanding of databases. However, no prior knowledge of ASP.NET MVC or Entity Framework is required. So, let’s get started.
What We’re Going to Build
As part of this tutorial, we’ll be building a simple web application for a video rental store. We want the admins to have a page to see the list of all videos in the store, as well as the ability to add, edit and delete videos. I’m going to exclude advanced features such as dealing with the stock, renting a video or returning it, calculating cost, etc., so we can focus on the core concepts of ASP.NET MVC. I’ll be covering those advanced scenarios in my comprehensive ASP.NET MVC course that will be published on Udemy soon.
So, as part of building this app, you’re going to learn how to:
- Create a data entry form to add, update and delete records in a database. In this tutorial, we’ll build a form for managing videos, but you can take what you learn from this tutorial and apply it in any real-world scenarios.
- Display a list of records. Again, here we’ll display a list of videos, but you can apply what you’ll learn here to any real-world scenarios. You can use these techniques to display lists of tweets, photos, blog posts, and literally anything else.
- Use Entity Framework to query or update your database. Entity Framework is an Object/Relational Mapper (ORM) that sits on top of a database. This frees you from having to work directly with database connections, writing SQL queries and commands, etc. You ask Entity Framework to load or save a set of objects, and Entity Framework will take care of all the dirty work for you.
- Generate your database using code. This is what we call Code First workflow (more on this later).
By the end of this tutorial, you’ll have a good understanding of ASP.NET MVC and Entity Framework fundamentals. Not only will you be able to build simple applications, but you’ll also be able to follow other tutorials more easily. So, let’s get started.
Setting Up the environment
To build this application, you need Visual Studio 2013. Any edition would work. You can get a free community edition of Visual Studio here:
Once you have Visual Studio ready, launch it. Then go to File > New > Project. In the New Project dialog, on the left side, under Templates, select Visual C# > Web. On the right side, select ASP.NET Web Application.
In the Name field, type Beaver. This is the code name for our video rental store application. In the Location box, specify a location to create the files on the disk. Preferably, use a local drive and not a network drive. Otherwise, sometimes you may run into security or performance issues. Finally, click OK.
On the next page, select MVC from templates. On the bottom right, make sure Host in the cloud is not checked, as we’re not going to cover deployment in this tutorial.
Next, wait a few seconds until Visual Studio creates your project template.
Now that our application is created, we can run it by pressing Ctrl+F5. Visual Studio will launch your browser and take you to an address like where 1234 is the port number. The port number on your machine might be different from mine, but that doesn’t matter.
Beginner’s Question: What is localhost? Every web application needs to be hosted by a web server. Localhost is a mini web server running on your machine. In the real world, you often publish an ASP.NET application to a full-fledged IIS server. Web hosting companies take care of installation of IIS for you. So you never have to worry about it. All you do is upload your files.
Now we have an application with some basic functionality. You can register a new account, log in, log out, change your password, etc. All this functionality comes with the ASP.NET MVC template. So, you never have to write code for these repetitive features that nearly every application needs.
Let’s test-drive our sample application. On the top right, click Register. Fill out the form with an email address and password, and click Register.
Note that you’re automatically logged in with the email address you supplied.
You can also log out.
All this functionality comes out of the box with a package called ASP.NET Identity. If the default registration form doesn’t work for you, you can always customize it. That is beyond the scope of this tutorial, and I’m going to cover it in my comprehensive ASP.NET MVC course.
Let’s recap: we built an ASP.NET MVC application using the template in Visual Studio. Now, it’s time to implement some functionality specific to our video rental store. Over the next few sections, in each section, we’ll add a new function to our application.
Displaying the List of Videos
The first feature I’d like to implement here is a page with a plain list of videos. It’s much easier to build this than a form to add or update a video. So, to build this page, first we need a database populated with some records.
The traditional workflow is to create a database, design the tables using table designers, and then generate domain classes based on these tables. This approach or workflow is called Database First. But in this tutorial, I’m going to teach you the modern way of working with a database. This approach is called Code First, which simply means code first, and let the tools create the database for you. Thus, we’re never going to use table designers to create our database.
At this point, you might ask, “What tooling do we need to auto-generate the database?” The answer is: Entity Framework, which comes automatically with our default ASP.NET MVC template.
Here is an overview of what we’re going to do in this section.
- We’re going to create a domain class that represents a video. This class is going to have properties such as Name, Description and Genre.
- We use Entity Framework to generate the database.
- We populate our table with some video records.
- We build a web page to display the list of videos in the database.
Step 1: Building the Model
Back to Visual Studio, go to Solution Explorer. If it’s not visible, open it from View > Solution Explorer. Right-click the Models folder in the project and select Add > Class… In the Add Class dialog, type Video in the Name field. Now, declare these properties in the Video class.
public class Video { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public Genre Genre { get; set; } } public enum Genre { Comedy = 1, Horror, SciFi, Romance, Documentary, Kids }
Here, we use the Id property to uniquely identify each video. This Id will be generated by the database.
Next, open IdentityModels.cs from the Models folder. This code is automatically generated as part of the project template. Inside this file, we have two classes: ApplicationUser, which represents a user, and ApplicationDbContext. A DbContext is an abstraction over the database which hides all the complexity of working with a database, such as opening and closing connections, running commands, reading and writing data, etc. Here is the auto-generated code for ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
Note the constructor of this class. The constructor calls the base constructor and passes “DefaultConnection”.
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { }
DefaultConnection is the name of the connection string for the database and is declared in Web.config, which is the configuration file for our application. Let’s have a quick look at the connection string. Going back to the Solution Explorer, open Web.config in the project root.
Under <connectionStrings>, note the element with the name DefaultConnection. Look at the value of the connectionString attribute. This is the actual connection string to the database:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Beaver-20150822102023.mdf;Initial Catalog=aspnet-Beaver-20150822102023;Integrated Security=True"
Let me break this down for you:
- Data Source: specifies the instance of your SQL Server. LocalDb is a lightweight version of SQL Server that is used for development, which is automatically installed with Visual Studio 2013. So you don’t need a full installation of SQL Server on your machine to do your development.
- AttachDbFilename: this is the path to the database file. Here DataDirectory represents the App_Data folder in your project. So if you look inside this folder, you’re going to see a file named aspnet-Beaver-xxxx. The value of xxxx depends on the date/time you create this project.
- Initial Catalog: is the name of the database. In this case, it is the same name as the database file itself.
- Integrated Security = True means you can connect to the database using your current Windows credentials, so you don’t need a separate username/password to connect to SQL Server.
Let’s quickly recap what we’ve done up to this point. We created a Video class and had a quick look at the auto-generated DbContext as well as the connection string for the database.
The last part of this step is to make a slight modification to our DbContext. Go back to IdentityModels.cs, and modify ApplicationDbContext as follows:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public DbSet<Video> Videos { get; set; } public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
Here I added a property of type DbSet<Video> called Videos. DbSet is a generic class that comes with Entity Framework. As the name implies, it represents a set (or a table) in a database. We work with this DbSet like a collection in memory. We add Video objects to it, we remove an object, or modify it and then when we ask Entity Framework to write changes to the database. Entity Framework keeps track of changes in this collection in memory, and based on those changes it will generate corresponding SQL commands and runs them on the database.
We built our model in this step. Next, we’re going to generate the database.
Step 2: Generating the Database
In this step, you’re going to learn how to use Entity Framework Code First workflow to generate a database. But before we get started, let me explain the process first, and then we’ll do it together. The Code First workflow includes three steps:
- Enabling migrations: The very first time you need to use Code First workflow, you need to enable migrations. With this, you instruct Entity Framework to keep track of changes in your domain classes.
- Adding a migration: Once migrations are enabled, every time you make a change to your domain classes (e.g., adding a new class, modifying an existing one, etc.), you create a new migration. A migration is a class with some auto-generated code that is used to upgrade or downgrade the database. Since Entity Framework is now aware of changes in your domain classes, it will automatically generate the code to migrate the database. For example, if you create a new class like Video and then add a migration, Entity Framework will generate code to create a new table called Videos.
- Updating the database: With this step, you tell Entity Framework to run migrations you’ve created on the database. Entity Framework will compare the migrations you have in your project with the ones that are run on the database, and if there are any new migrations, it will run them sequentially to bring your database up to date.
So this is the process. Now, it’s time to do the steps. We do all these steps in Package Manager Console. Go to Tools > NuGet Package Manager > Package Manager Console.
First, we need to run the Enable-Migrations command.
PM> Enable-Migrations
When you run this command, a new folder called Migrations will be added to your project. Inside this folder, you’ll see a file like [DATETIME]_InitialCreate.cs. Here, the value of DATETIME depends on the date/time you run this command.
What is this file? Let’s open it and see. You see a migration class called InitialCreate which derives from DbMigration and has two methods: Up and Down, which are executed when upgrading or downgrading the database, respectively. So with Entity Framework Code First, you get full versioning of your database. At any time, you can upgrade it to the latest version, or downgrade it to an earlier version. This is extremely useful in the real world, where you may need to maintain multiple versions of an application.
Let’s take a look at the Up method in our migration class. Inside this method, you see a number of calls to CreateTable method. Each of these calls aims to create a table in the database. When you run migrations, Entity Framework will read all this code and generate corresponding SQL statements to execute on your database. This migration aims to create tables such as AspNetRoles, AspNetUserRoles, AspNetUsers, etc. These are the tables used internally by ASP.NET Identity to manage user registration, login, etc.
Now, back to our migration process. I mentioned that every time you make a change to your domain model, you need to add a new migration. Thus, we created the Video class and added a DbSet<Video> to our DbContext. By adding this DbSet to our DbContext, we tell Entity Framework that this Video class needs to be stored in the database. Now, at this point, we don’t have any tables in the database for our videos. So, we need to add a new migration.
Back to Package Manager Console, run this command:
PM> Add-Migration AddVideosTable
This command takes an argument, which is the name of your migration, in this case AddVideosTable. This name is arbitrary, and you can call it anything. There is no magic behind it. It’s just a way to organize your migrations so you know how each migration affects your database. I tend to name my migrations based on the changes that should happen in the database. In this case, because the Video class is a new class, I expect Entity Framework to generate a migration to add a new table called Videos. This is why I called this migration AddVideosTable.
When you run this command, Entity Framework will create a new migration file in the Migrations folder, called [DATETIME]_AddVideosTable. Let’s take a look at this file.
So, you see another migration class that derives from DbMigration. Look at the Up method. Note the call to CreateTable, which tries to create a table called Videos.
public override void Up() { CreateTable( "dbo.Videos", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(), Description = c.String(), Genre = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); }
I’ve highlighted the key areas here that you need to understand. Note the name of this table: Videos. Entity Framework uses convention over configuration. Thus, there are certain conventions built into it that work in most cases. In this case, because we have a class called Video, it assumes the table should be called Videos.
Similarly, because we have four properties in our Video class, it will create four columns with the same name and type in the database: Id, Title, Description and Genre.
Also, look at the last line in this method:
.PrimaryKey(t => t.Id);
Again, based on the convention, it assumes that the Id property or column represents a unique key for a video. Hence, it marks this column as the primary key.
As you see, the convention is useful and works in most cases. But if it doesn’t work for you, you can always override it. For example, some developers prefer singular names for their database tables. You can always supply additional configuration to override the default conventions. This is beyond the scope of this tutorial, but it’s something I’ve covered in my Entity Framework course that will be published on Udemy soon.
Back to our migration process. We enabled the migrations, and added a new migration. Entity Framework detected that we have a new class, called Videos, and generated the corresponding code to create a new table in the database. The third step of the process is to run the migrations.
Open up Package Manager Console again and run:
PM> Update-Database
At this point, Entity Framework runs any pending migrations on your database. By pending, I mean any migrations that have not been run on the database before. So, let’s take a look at the database.
In Solution Explorer, expand App_Data folder. You should see your database file with MDF extension. If you don’t see it, it’s because it’s not part of the project, and by default, Visual Studio hides files on the disk that are not in your project. To see all files, click the Show All Files button in the toolbar on Solution Explorer.
You should see your database file in App_Data folder. Double-click it. A new panel called Server Explorer pops out of the left side. Expand the Tables.
The _MigrationHistory table is used by Entity Framework to keep track of migrations that have been run on the database. Tables starting with AspNet are used by ASP.NET Identity to manage authentication. And finally, we have our Videos table.
As you saw in this step, with the Code First workflow, we never wasted our time with table designers. Instead, we focused on our code, which is what we programmers do anyway. We modify our domain model, then add a migration and update the database. Entity Framework will take care of bringing the database up to date. With this, not only can we get things done faster, but we also get full versioning of our database. We can upgrade or downgrade our database to any version. When it comes to deploying our application to production, we can ask Entity Framework to generate a SQL script based on all migrations in our project. Then we can take this script and run it on the production database.
In this step you learned about Code First migrations. Now that we have our domain class and the corresponding table, it’s time to populate this table with some data so we can display it to the user.
Step 3: Populating the Table
In Server Explorer, right-click the Videos table and go to Show Table Data. Then add a few records to this table. Note that the Id column is an IDENTITY column, so you don’t need to supply any values for it. Again, by convention, Entity Framework marks the primary key of a table as an identity column.
Step 4: Creating a Page to Display Videos in the Database
In this step, you’re going to learn how to create new web pages with ASP.NET MVC. We’re going to create a simple page to display all videos in the database.
Again, before getting into the mechanics, let me give you some background on the process and how everything fits together.
ASP.NET MVC is based on the Model View Controller (MVC) pattern. MVC is one of the architectural patterns that aims to provide better separation of concerns in your application, which results in better maintainability.
To understand MVC, think of a restaurant. When you go to a restaurant, there is a waiter/waitress, a chef, one or more kitchen hands, a manager, etc. Every person in the restaurant is responsible for only one thing. Imagine what the restaurant would be like if all these people did everything! What would it be like if the chef came to you, took the order, then went shopping, and asked the cashier to cook your food? You’d probably run away! The same concept applies in software. Clean software is like a well-managed restaurant, where everyone has one and only role. Architectural patterns like MVC help us to achieve this by promoting separation of tasks. Therefore, different parts of your application will be responsible for only one thing. In MVC terms, we have:
- Views: which are purely responsible for presenting data. This is where we write our HTML markup. Views should only have logic related to viewing data, not for processing inputs. For example, you can use a foreach block to render a list of objects in a view. But you’re not supposed to use any other kind of logic for processing user input or controlling application flow.
- Controllers: responsible for processing user input, application flow, etc.
- Models: classes that represent the state of the application. In practical terms, this often means the domain model of an application. In our application, the Video class we created is part of the application domain. When we load data from the database, we create one or more Video objects that represent the state of the application.
As you see, with this structure, we get a clean separation. Every component is responsible for one thing.
Earlier, we created our domain model. In this step, we’re going to create a Controller and a View.
Right-click the Controllers folder and go to Add > Controller…. In the dialog box, select the first item (MVC 5 Controller – Empty).
There are other templates here that automatically generate some code for us, but in this tutorial I want to teach you how to write all this code by hand so you have a good understanding of how everything works. Click Add. Name this controller VideosController and click Add again. Visual Studio will create a basic empty controller like this:
public class VideosController : Controller { // GET: Videos public ActionResult Index() { return View(); } }
Our VideosController derives from the Controller class. Controller is part of ASP.NET MVC and encapsulates the basic functionality that every controller in the application might need.
Here, we have a method called Index which returns an ActionResult. In ASP.NET MVC, Methods in a controller are referred to as Actions. The job of an action is to handle a request. So, when an HTTP request comes into the ASP.NET runtime, it will be routed to an action for processing. This routing is based on convention, but you can always override it. The convention determines the name of a controller and an action from the URL of the request. So, as an example, if the URL of a request equals /videos/index, it should be handled by a controller called VideosController with the Index method (or action). I’ll explain routing in a bit more detail later on.
Here in this method: we need to write code to handle a request for the URL /videos/index. This means that we need to get the list of videos from the database and display them in a view. Change the code as follows, and then I’ll explain how everything works:
using System.Linq; using System.Web.Mvc; using Beaver.Models; public class VideosController : Controller { private ApplicationDbContext _dbContext; public VideosController() { _dbContext = new ApplicationDbContext(); } // GET: Videos public ActionResult Index() { var videos = _dbContext.Videos.ToList(); return View(videos); } }
What’s going on here? First, I added two using statements on the top to import the required namespaces.
Next, I declared a private field of type ApplicationDbContext in the controller and initialized it in the constructor.
In the Index action, we use _dbContext to get the videos from the database. Remember how earlier we added a DbSet<Video> to our AppicationDbContext? I told you that this DbSet represented a set (or a table) in the database. So, here _dbContext.Videos represents the set of videos. The ToList method is an extension method provided by LINQ. When we call this method, Entity Framework runs a query on the database and pulls out all videos from the database. If you need to better understand LINQ and extension methods, check out my C# Advanced course on Udemy.
As you see, with Entity Framework, getting data from the database can be as simple as one line of code. We never have to worry about working with plain ADO.NET objects such as SQL connections, commands, etc. Our DbContext takes care of all this complexity.
Finally, in the last line of our Index action, we call the View method and pass the videos object to it. This method is a helper method that is defined in the base Controller. It returns an instance of the ViewResult class. By returning an instance of a ViewResult, we tell ASP.NET MVC runtime to return a view upon processing this request. In a more complex application, we don’t always return a view from an action. Sometimes we may want to redirect the user to a new URL, or return a JSON object. This is the reason the return type of our Index action is ActionResult. This is an abstract class that specific action results inherit from. For example, ViewResult, RedirectResult and JsonResult all inherit from ActionResult. By using the base class as the return type, this method can return any of its derivatives. It’s common convention to return an ActionResult from controller actions.
Let’s recap: we built a controller with one action that returned a view populated by the list of videos from the database. But where is the actual view? We’re going to create it now.
Back in the Solution Explorer, expand the Views folder, right-click the Videos and go to Add > View… By convention, since we have a controller called Videos, we should have a folder here called Videos, which includes all the views this controller is going to use.
In the Add View dialog, set the view name to Index. Again, here by convention, since our action is called Index, we can create a view with the same name. We don’t have to follow this convention. We can always create a view with a different name, but following the convention helps us write less code to achieve the same thing.
Make sure Use a layout page is ticked and click ….
In the new dialog, in the Project folders pane on the left, navigate to Views > Shared. On the right, select the first item: _Layout.cshtml and click OK. Click Add to finish adding a new view.
So, what is a layout? It’s a template or a master page for all our views. By using a layout, we can ensure that all views have the same look and feel. The default ASP.NET MVC project template already has a layout that you saw when previewing the site. We can always change this layout to customize it for our own needs.
Let’s take a look at the newly generated view:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2>
In ASP.NET MVC, our views are files with the cshtml extension. Inside these files we can write both HTML and C# code. To write C# code, you need to prefix it with @ or @{ } if your code is more than one line. This syntax is based on what we call Razor Views. So, in ASP.NET MVC we have a view engine that knows how to parse these views with this special syntax, and generate raw HTML from our C# code.
Look at the top of this file:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; }
Here we have a code block indicated by @{ }. The first line specifies the title of this view. This title is what we see in the browser title bar when we access this page. The second line specifies the layout file that you selected in the Add View dialog. So you can always come back here and change the layout if you want.
Next, we need to display the list of videos in this view. First, we need to add this line on the very top of the view:
@model IEnumerable<Beaver.Models.Video>
With this line, we tell the view engine that the model behind this view is an instance of IEnumerable<Video>. What is IEnumerable? It’s an interface used for enumerating a list of objects. Earlier in the controller, we used the ToList method to get the list of videos from the database:
var videos = _dbContext.Videos.ToList();
Here, this videos object is a List<Video>. A list in C# implements the IEnumerable interface, which allows us to iterate the list using the foreach block. Alternatively, in the view, we could set the model to List<Video> instead of IEnumerable<Video>. Is there a difference? Yes, a tiny one. When you use a concrete class like List<Video>, your model has to be of that type. But if you use an interface, your model can be of any type that implements that interface. In this example, if we use IEnumerable and later we decide to pass an object of a different type to this view (e.g., a SortedList or Dictionary), everything will continue to work, because those types implement the IEnumerable interface as well. Hence, with interfaces, your application will be more loosely coupled and breaks less as a result of internal changes.
Back to the view: we specified the model passed to the view. Next, change the heading of the view from:
<h2>Index</h2>
to:
<h2>Videos</h2>
Now, write the following piece of code after the heading:
<ul> @foreach (var video in Model) { <li>@video.Title (@video.Genre)</li> } </ul>
Here, we’re using a UL (unordered list) to display the list of videos.
As you see, the code includes a mix of HTML and C# code, thanks to the Razor view engine! Note that our C# code is prefixed with @. This tells the view engine that this is C# code and needs to be executed.
We use a LI (list item) to render each video. Again, in this line, we have a mix of HTML and C# code. Here we simply display the Title and Genre of each video. In a more complex application, you can have a complex UL/LI structure with lots of child elements and display lots of attributes to the user. But the process is exactly the same as what we’ve done here. Thus, you can take this knowledge and apply it to a difference scenario.
Note that as you were typing:
@video.Title
IntelliSense showed you the properties of the video object when you used the dot notation. This is because we set the model of this view at the top of the view. If you didn’t do that, IntelliSense wouldn’t work, and in some cases you would even get a runtime exception.
That’s all you had to do to get the list of videos from the database and show them to the user. We created a controller and wrote a couple of lines of code in the Index action, then created a view and used a foreach block to display videos.
Let’s run the application and see the result. Press Ctrl+F5 to run the application. Your browser will launch and navigate to /Videos/Index. This is because you pressed Ctrl+F5 when you were viewing the Index view in the Videos folder.
Look at the content of the page. You see the list of videos. So we successfully built the first feature of our application. In the next section, we’ll implement the ability to add a new video to the database.
Adding a New Video
In this section, you’re going to learn how to create a data entry form and save data to the database using Entity Framework. We will be building a form for adding a new video to the database.
I’m going to break this section into two steps:
- Creating a page to add a video
- Saving the video to the database
Step 1: Creating a Page to Add a Video
Before. Take a look at the following table for a few examples:.
Now, write the following code in the view to create an HTML form element:
. In the next step, we’re going to save this video to the database.
Step 2: Saving the Video to the Database
Earlier in the last step, we defined a form with the following code:
using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" })) { }
As I explained before, when this form is posted, the Add action in the Videos controller will be executed. So in this step, we’re going to implement this action.
Open up VideosController and create a new action as follows:
public ActionResult Add(Video video) { _dbContext.Videos.Add(video); _dbContext.SaveChanges(); return RedirectToAction("Index"); }
This action takes a Video object populated with the values that the user enters into the form.
The first line adds the Video object to our DbSet. Remember DbSet? It’s a collection of objects in memory that is tracked by Entity Framework. When we add an object to this collection, nothing is saved to the database yet. Everything is in memory. When we call _dbContext.SaveChanges(), Entity Framework will look at all the changed objects in memory and will automatically run the right SQL statements to update the database.
In the last line, we are using the RedirectToAction helper method to redirect the user to the Index action. This means that once the video is saved, the user will be redirected to /videos/index where they will see the list of all videos in the database. The RedirectToAction method returns a RedirectToRouteResult which derives from ActionResult. So, by using ActionResult as the return type of our actions, we can return an instance of any classes that derive from ActionResult. So far, you’ve seen RedirectToRouteResult and ViewResult. There are a few other ActionResults which are beyond the scope of this tutorial.
It’s time to test our application. Run the application with Ctrl+F5 and in the browser, change the URL to go to /videos/new.
Fill out the form, and click the Save button. The new video should appear in the list.
Before we finish this step, it would be nice to add a link to the Add Video page in the list of videos. Open up Views > Videos > Index and type the highlighted code:
<h2>Videos</h2> <p> @Html.ActionLink("Add Video", "New") </p> <ul> @foreach (var video in Model) { <li>@video.Title (@video.Genre)</li> } </ul>
Here, Html.ActionLink is yet another helper method that we use to generate hyperlinks. The first argument is the text for the link, and the second argument is the name of the target action. We could optionally supply a third argument that would be the name of the controller, but in this case because we’re in a view for the Videos controller, it’s not necessary. It’ll be assumed by convention.
Now, you might ask, “Why do we use these helper methods to generate HTML markup? Why don’t we just use raw HTML elements?” We can use raw HTML, but the benefit of using these helper methods is that they are aware of routing configuration. In this case, when we tell this method to render a link for the New action, it will generate a link that points to /videos/new. If you override the default routing and map your New action to another route (eg /videos/create), this code will continue to work. It will generate a link to /videos/create. However, if we used a raw HTML anchor element (e.g., <a href=”/videos/new”>), the link will break because we no longer have an action that responds to /videos/new. So, we prefer to use helper methods to generate HTML markup.
Run the application again, and you should see the link.
Next, let’s add the ability to edit existing videos.
Editing an Existing Video
In this section, you’re going to learn how to use partial views in ASP.NET MVC (for promoting re-usability) and how to update data using the Entity Framework.
Similar:
<li>@video.Title (@video.Genre) @Html.ActionLink("Edit", "Edit", new { id = video.Id })</li>:
<a href=”/videos/edit/1”>Edit</a>:
public ActionResult Edit(int id) { var video = _dbContext.Videos.SingleOrDefault(v => v.Id == id); if (video == null) return HttpNotFound(); return View(video); }
In the first line, we’re using our DbSet (_dbContext.Videos) but this time, instead of using the ToList method (to get all videos), we use SingleOrDefault. Both of these methods are LINQ extension methods. If you’re not familiar with LINQ, checkout my C# Advanced course..
if (video == null) return HttpNotFound();
This method returns HttpNotFoundResult which is yet another ActionResult. With this line, the user will automatically be redirected to a standard “Page Not Found” page in your application.
Finally, if the video is found, we return a view and populate it with the video object:
return View(video);
Now, let’s go ahead and create this view. Inside the Views folder, right-click Videos" />
Make sure to set the model for this partial view at the top of the view:
@model Beaver.Models.Video
Back to New.cshtml, change the using block as follows:
@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" })) { Html.RenderPartial("_VideoForm"); }:
using (Html.BeginForm("Update", "Videos", FormMethod.Post, new { @class = "form" })) { Html.RenderPartial("_VideoForm"); }:
[HttpPost] public ActionResult Update(Video video) { var videoInDb = _dbContext.Videos.SingleOrDefault(v => v.Id == video.Id); if (videoInDb == null) return HttpNotFound(); videoInDb.Title = video.Title; videoInDb.Description = video.Description; videoInDb.Genre = video.Genre; _dbContext.SaveChanges(); return RedirectToAction("Index"); }
The code should be very familiar, except for a few minor differences.
First, I’ve decorated this action with the [HttpPost] attribute. This tells the MVC runtime that this action can only be called when there is an HTTP POST request.
Beginner’s question: What is HTTP POST, and why/when should we use it? HTTP requests have different verbs, and each verb has a different meaning. We have GET (for reading data), POST and PUT (for inserting/updating data), and DELETE for deleting data. As a best practice, whenever you’re changing data in ASP.NET MVC, you need to mark your actions as HttpPost. If you don’t do this, it is possible that when a search engine spider (like Google) is crawling your website, it modifies or deletes your data without you being aware of that. Because these spiders use HTTP GET to navigate to different parts of your website, when you use HTTP POST, you’re preventing a simple HTTP GET from modifying/deleting data in your database.
Back to our action: in the first line, we get the video with the given ID from the database.
var videoInDb = _dbContext.Videos.SingleOrDefault(v => v.Id == video.Id);
Note that I named this variable videoInDb to distinguish it from the video object passed as a result of posting the form.
Next, we check to see if the video was found or not, just like before.
if (videoInDb == null) return HttpNotFound();
Then we update the Title, Description and Genre properties of videoInDb and call _dbContext.SaveChanges() to update the database.
videoInDb.Title = video.Title; videoInDb.Description = video.Description; videoInDb.Genre = video.Genre; _dbContext.SaveChanges();
DbContext will issue an UPDATE SQL statement based on the properties we have updated. Finally, we redirect the user to the list of videos.
return RedirectToAction("Index");
Let’s run the application and see if everything is working. Navigate to /videos, and click:
var videoInDb = _dbContext.Videos.SingleOrDefault(v => v.Id == video.Id); and Genre, which come from the input fields on the form. To send the value of Video.ID, we need to add a hidden field.
Open up _VideoForm.cshtml and add a hidden field before the Save button:
@Html.HiddenFor(m => m.Id) <input type="submit" class="btn btn-primary" value="Save" />.
Next, we’ll add the ability to delete a video.
Deleting a Video
In this section, you’ll learn how to delete data in the database using the Entity Framework.
Again, we’re going to implement this feature in two steps: first, we’re going to add a Delete link in front of each video in the video list. When the user clicks this link, they’ll see a page with the details of the video to delete. This is the delete confirmation page. Next, we’ll be focusing on actually deleting the video from the database.
Step 1: Creating a Page to Confirm Deletion
This step is very similar to what we’ve done before. Add a Delete link in front of each video in the list. When this link is clicked, display a view with the details of the video to delete. Use a UL/LI to display different attributes of a video. Don’t worry about deleting the video from the database yet. After trying this, take a look at my solution:
First, we need to add the Delete link in front of each video. So open up Index.cshtml in Views > Videos, and change the LI as follows:
<li> @video.Title (@video.Genre) @Html.ActionLink("Edit", "Edit", new {id = video.Id}) | @Html.ActionLink("Delete", "Delete", new {id = video.Id}) </li>
Note that I added a vertical separator between Edit and Delete to separate them.
Next, we should create a new action in the VideosController as follows:
public ActionResult Delete(int id) { var video = _dbContext.Videos.SingleOrDefault(v => v.Id == id); if (video == null) return HttpNotFound(); return View(video); }
Nothing should be new to you at this point. We’re just pulling out the video to show to the user before deleting it.
Now, let’s create the corresponding view. Add a new view called Delete inside Views > Videos. Make sure it’s not a partial view and has a layout. Write the following code inside the view.
@model Beaver.Models.Video @{ ViewBag.Title = "Delete"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Delete</h2> <p> Are you sure you would like to delete this video? </p> <ul> <li>Title: @Model.Title</li> <li>Description: @Model.Description</li> </ul>
Here I am using a simple UL/LI to display the attributes of the video. You can use anything to lay out the details of a video. It doesn’t really matter from the perspective of learning ASP.NET MVC.
Next, write this code in the view:
@using (Html.BeginForm("DoDelete", "Videos", FormMethod.Post)) { @Html.HiddenFor(m => m.Id) <input type="submit" class="btn btn-danger" value="Yes, Delete it!" /> @Html.ActionLink("No, back to videos", "Index") }
You might wonder why I’m using Html.BeginForm when we don’t really have a data entry form here. The reason is that we need to call the Delete action using HTTP POST method. Again, anytime we need to modify data in ASP.NET MVC, we should use HTTP POST to prevent accidental data modification. In ASP.NET MVC, the only way to use HTTP POST is by creating a form. In this example, our form only has a submit button and no input fields.
Note that in this form, we also have a hidden field to render the ID of the video in our markup.
@Html.HiddenFor(m => m.Id)
This way, when we post to the server, we’ll have the ID of the video to delete.
I’ve used the btn-danger Bootstrap class to make our delete button red.
<input type="submit" class="btn btn-danger" value="Yes, Delete it!" />
Now, run the application. You’ll see a delete link in front of each video. Click one of them. Look at the new page we just built.
Click No, back to the videos. So, we have a nice navigation between these two pages. The only thing remaining is to actually delete a video from the database. That’s what we’re going to do in the next step.
Step 2: Deleting a Video from the Database
The form we created in the last step posts to an action named DoDelete.
@using (Html.BeginForm("DoDelete", "Videos", FormMethod.Post))
Let’s go to VideosController and create this action:
[HttpPost] public ActionResult DoDelete(int id) { var video = _dbContext.Videos.SingleOrDefault(v => v.Id == id); if (video == null) return HttpNotFound(); _dbContext.Videos.Remove(video); _dbContext.SaveChanges(); return RedirectToAction("Index"); }
Again, the code should look very familiar to you. I’ll just highlight the important aspects.
I’ve decorated this action with [HttpPost] to make sure an HTTP GET caused by a web crawler will not delete our records.
Inside the method, first we need to read the video from the database and then call the Remove method of our DbSet. This is how you ask Entity Framework to delete records in the database. You cannot directly delete a record in the database. You should always read that record first, remove it from the memory and then call SaveChanges. This way, Entity Framework’s change tracker will realize that an object is deleted and will issue a DELETE FROM SQL statement to the database.
Let’s run the application and test the delete functionality. Delete one of the videos.
Review
If you made it this far, well done. I hope you’ve enjoyed this tutorial and learned the basics of ASP.NET MVC.
Let’s quickly review what you’ve learned and what the next step is. In this tutorial,
- You learned and used the core building blocks of ASP.NET MVC (Models, Views and Controllers).
- You created a model using the Entity Framework Code First workflow.
- You used Code First migrations to generate your database.
- You built a controller with different actions for viewing lists of videos, adding a new video, and editing and deleting an existing one.
- You learned about the routing engine in ASP.NET MVC and how URLs get mapped to controllers and actions.
- You used Razor syntax to mix HTML and C# code in your views.
- You refactored your code by extracting the reusable view code into a partial view.
- You learned about the difference between HTTP GET and HTTP POST, and now you’re able to build more reliable applications.
- You used many HTML helper methods in views such as ActionLink, LabelFor, TextBoxFor, TextAreaFor and BeginForm.
- You used many helper methods in actions such as View, RedirectToAction and HttpNotFound.
What’s next? ASP.NET MVC is more than what you’ve read, and that’s why I’m planning to create a comprehensive course to teach you lots of things you can do with ASP.NET MVC. In particular, I’ll be teaching you:
- Authentication and authorization
- Prevention of common security attacks
- Data validation
- Caching
- Real-time connections
- Working with Javascript libraries
- Ajax
- Creating RESTful services with ASP.NET Web API
- And more
If you enjoyed my teaching style and would like to learn more from me, subscribe to my newsletter. I’ll send out an announcement once my course is ready. | https://blog.udemy.com/a-step-by-step-asp-net-tutorial-for-beginners/ | CC-MAIN-2019-09 | refinedweb | 8,059 | 66.44 |
Often layouting a web page is an afterthought. Put a
div here and there, sprinkle some CSS, and call it done. Perhaps you are more advanced and use CSS Grids to figure out exact positioning.
What if there was an alternative way to achieve the same while having more power as a developer? That is something that Artem Zakharchenko is exploring with atomic-layout, a layout solution designed for React.
Hi! My name is Artem, and I am a Full-stack JavaScript developer from Ukraine. I have graduated a medical university and decided to switch my occupation to programming because it's something I enjoy doing since I was a kid.Hi! My name is Artem, and I am a Full-stack JavaScript developer from Ukraine. I have graduated a medical university and decided to switch my occupation to programming because it's something I enjoy doing since I was a kid.
I'm grateful to find a job and turn my hobby into a full-time activity. That hasn't stopped me, however, from endeavoring into side projects and open source. Today I'd like to share with you one of such projects.
Atomic layout is a React library that provides you with a separate layer responsible for spacial distribution for your layouts. The layer decouples components and spacing, which opens vast opportunities to reuse layout units, as they are no longer bound to some context via specific spacing properties.
Practically speaking, it gives you a fast and maintainable way of developing responsive layouts that share global layout settings and create a unified system.
It generates React components based on provided CSS Grid template areas and controls their spacial relation via props. It also supports a feature called responsive props, that allows applying prop values conditionally, based on a breakpoint.
I will demonstrate the workflow below, but we need to install the library first:
npm install atomic-layout
The current version of the library uses
styled-components, so we need to install it too:
npm install styled-components
Would you like to use Atomic layout with another styling solution? Join the discussion!
Let's say we want to create a simple
Header component that consists of three areas: logo, menu, and actions. First, we define a verbose areas definition of our
Header:
const areas = "logo menu actions";
Areas definition uses pristine
grid-template-areassyntax.
That's all it takes to create a layout of three equally spaced areas positioned inline. Now we can provide this area string to the
Composition component of the library:
import React from 'react' import { Composition } from 'atomic-layout' // Layout areas definition const areas = 'logo menu actions' const Header = () => ( <Composition areas={areas} gutter={10}> {({ Logo, Menu, Actions }) => ( <> <Logo> <img src="logo.png" /> </Logo> <Menu as="nav"> <ul>{...}</ul> </Menu> <Actions> <a href="/login">Log in</a> </Actions> </> )} </Composition> )
After passing our areas to the
areas prop of the composition, it exposes a function as its children. That function accepts generated area components associated with the respective CSS Grid areas.
There are plenty of props to apply to the Composition and other components exported from the library to achieve the desired effect.
Atomic layout is mobile-first and responsive by default which means that it has rich support of conditional rendering and responsive props application.
To conditionally render one or multiple components, we can wrap them in the
Only component, providing it with breakpoint constraints.
import { Only } from "atomic-layout"; const Disclaimer = () => ( <Only from="sm" to="lg"> <p> Content displayed between small and large breakpoints. </p> </Only> );
Only component supports
from,
to and
except props, and any combination of those. You can pass breakpoint names as the values, or use an Object in case of a custom breakpoint.
You can use
Onlycomponent just as any other React component. For example, you can render it nested within generated layout areas!
When using the
except prop, the children will be rendered everywhere except the given breakpoints range:
import { Only } from 'atomic-layout' const Disclaimer = () => ( <Only except {...} </Only> )
Read more about the
Onlyhelper component.
Whenever a prop name is suffixed with a breakpoint name, its value is being applied only from that breakpoint and up. Take a look at how easy it is to have a per-breakpoint gap between the
Header's composites (areas):
import { Composition } from 'atomic-layout' const Header = () => ( <Composition areas={...} gutter={10} gutterMd={20} gutterLg={30} > {...} </Composition> )
Responsive props respect overrides, which means that would be applied as follows:
gutter={10}on the
xsbreakpoint and up;
gutterMd={20}on the
mdbreakpoint and up;
gutterLg={30}on the
lgbreakpoint and up.
You can define custom breakpoints and use them as the suffixes of your responsive props (i.e.
paddingRetinaor
alignItemsDesktop).
The
areas prop can be responsive as well! By providing different areas definitions on different breakpoints, we can alter the position and presence of our layout areas with a single prop.
const areasMobile = ` logo hamburger `; const areasTablet = ` logo menu actions `; const Header = () => ( <Composition areas={areasMobile} areasMd={areasTablet} gutter={10} > {({ Logo, Hamburger, Menu, Actions }) => ( <> {/** * "Logo" is present in both area definitions, * and is always rendered. */} <Logo /> {/** * "Hamburger" is present in "areas", but missing * in "areasMd". It's automatically rendered only * on "xs" and "sm" breakpoints. */} <Hamburger /> {/** * "Menu" and "Actions" are present in "areasMd", * and are automatically rendered on "md" breakpoint * and up. */} <Menu /> <Actions /> </> )} </Composition> );
Welcome declarative layouts: you describe what and when to render, and let Atomic layout handle media queries and conditions.
Unlike other solutions, Atomic layout's purpose is to distribute spacing. Spacing effectively defines a layout composition. That's why there is no predefined
Col or
Row components, but a
Composition that can be anything you want.
A grid is a composition of rows and columns, and a header may be a composition of logo and menu, and so on. There is no need to be specific when you are wielding the entire power of composition as a physical entity.
One of my favorite differences is that Atomic layout teaches you to think in terms of composition, which you can configure and render. Since its counterparts compose any layout element, you can get consistent components declaration throughout the entire application. Having a predictable way how components are defined makes their maintenance superb.
Instead of deciding what CSS properties I need to create a layout, I started asking myself: "What does this layout consist of? What is the relation between its counterparts?"
We try to make an experience of working with Atomic layout a fun way to learn CSS Grid and gain the knowledge you could apply without any libraries whatsoever. To do so, we minimize the amount of library-specific transformations of the options you provide to your composition.
<Composition areas="header footer" templateCols="1fr auto" />
.composition { grid-template-areas: "header footer"; grid-template-columns: "1fr auto"; }
Verbose prop names and no value transformations grant almost 1-1 compatibility with the emitted CSS.
Needless to say that layout development becomes fast and efficient. You can develop production-ready components in a few minutes, without writing a single CSS line (if you want). And that involves responsive as well!
During the work on one of the side projects, I've noticed that I repeat the same layout patterns over and over. So I've tried to abstract the logic that makes those patterns into a contextless layout unit.
My admiration of Atomic design came into play, and in no time I realized that atoms and molecules could be described using CSS Grid template areas. One proof-of-concept later Atomic layout has been open-sourced.
The roadmap is to refine the existing API, improve server-side rendering, and listen to the community to evolve this library. The mission is to provide a great experience when implementing layouts.
I hope that CSS Grid will be getting more usage, as it's indeed a future of the web. There's also a lot of attention bound to TypeScript and GraphQL, and I believe they will be the main trends this year.
As of Atomic layout, I would love to see people creating layouts with it, and sharing their experience. I hope together we can improve our process, encourage us to use modern technologies, and teach developers to think in terms of composition.
I wish newcomers to find a balance between practical and theoretical knowledge and don't neglect to have a deeper understanding of a subject, even if it means spending more time. Don't be afraid to fail, and don't fear the unknown. In the end, programming is about challenging yourself every day.
I suggest interviewing Honza Javorek (@honzajavorek), who is a person behind an API testing tool called Dredd. I'm also excited to join his team full-time to work on that project.
Thank you for the interview! I want to invite everybody to the upcoming React Finland 2019, where I will be giving a talk on Atomic layout. I will be glad to answer your questions there, or via Twitter.
Thanks for the interview, Artem! At least for me, it is a refreshing new way to look at how to develop and compose layouts. You can learn more about the approach in the video below:
Check out Atomic layout on GitHub and read its documentation to grasp it better. | https://survivejs.com/blog/atomic-layout-interview/ | CC-MAIN-2022-40 | refinedweb | 1,548 | 54.02 |
I've added a new method Page.endResponse() which does the following:
- If called from within an awake() or sleep() method, it immediately skips
all further awake(), respond(), and sleep() processing and sends the
accumulated response.
-...
- Geoff
| - If called from within an awake() or sleep() method, it immediately skips
| all further awake(), respond(), and sleep() processing and sends the
| accumulated response.
Shouldn't it still call sleep?
Usually, one subclasses Page and has something like this in SitePage (or
whatever):
def awake(self,transaction):
# call the super
Page.awake(self,transaction)
# proceed with this class stuff
...
self.endResponse()
So, as far as Page is concerned, awake() has happened. Shouldn't sleep()
also happen in this case, too?
Anyway, this is a good idea. We've got our own hack of much the same thing
to handle redirects. | http://sourceforge.net/p/webware/mailman/message/12378129/ | CC-MAIN-2014-42 | refinedweb | 137 | 67.15 |
vim's easy mode: making vim behave like a 'conventional' text editor
So it turns out vim has an "easy mode." Who knew? That will be the topic today, we will learn what's the deal with this mode, we'll figure out how to enable it, see why almost nobody pays attention to it, and lastly I'll show you some stuff you can do to make it a bit nicer.
Easy, what does that mean?
According to the documentation it was made to help people that don't use vim often enough to learn its commands. In this mode vim is suppose to behave like a conventional text editor, you know the type, one of those that let us edit things immediately.
What does it do?
It gives us the gift of convenience. On a more serious note, the first thing you'll notice is that we can insert and edit text in a more conventional way. For the people who have entered
vim by accident and have no knowledge of how it works this feature alone could be a huge improvement. It also provides some keyboard shortcuts that we all know and love, such as:
Ctrl + s: to save a file.
Ctrl + z: to undo changes.
Ctrl + y: to redo some changes.
Ctrl + c: copy text to the clipboard.
Ctrl + x: cut text to the clipboard.
Ctrl + v: paste text from the clipboard.
Ctrl + a: selects all text in the file.
It even enables some options that will make the experience a bit more intuitive, like mouse support, so we can select text with the mouse.
How does it work?
Good question. This "easy mode" is actually just a set of options written in a file called evim.vim. You can check it out with vim if you want, use this command
vim -R -c 'edit $VIMRUNTIME/evim.vim' (to get out use
ZZ or just close the terminal). So, when we active this mode vim just reads and executes this file.
How do we use it?
On the command line we provide the
-y flag to
vim, like this
vim -y. Another way would be using the
evim command.
The big flaw on the plan
Cool, now why is it that no one talks about this mode? Well maybe is because it makes it even harder to get out of vim (oh, the irony). They were so close. Anyway, if you want to exit vim while in this mode this is what you do: use
ctrl + o to go in normal mode, press
:, type
q and then press
Enter.
Why are you like that, vim?
It does look like this easy mode was designed to be used in a GUI. That's right, with vim in a graphical interface. So I guess they thought it wasn't necessary, because you would just close the "application" where vim is in.
Some workarounds
Some command-line experts out there must be thinking "well, just use
nano." I mean, yeah, that's a good solution. But if you want to give this mode a chance, keep reading.
The GUI
If what we need is a graphical interface then lets just use one. We could create an alias that uses our favorite terminal to open vim.
alias evim='xterm -e vim -y'
Or maybe you prefer a script.
$@xterm -e vim -y
Might want to replace
xtermwith something else.
This way when you call the
evim command or call the script
vim will open in another window. And when you finish editing stuff you just close that window.
The missing piece
On the other hand, if all we want is a shortcut to get out I say we create one. We could do this.
vim -y -c "inoremap <c-q> <c-o>:q<cr>"
This command will open vim in easy mode and create a
Ctrl + q shortcut that will close vim. Again, you can put this in an alias or script.
Easy by default
There is another way to enable this mode without using command line arguments. In our home folder, we can create a file called
.vimrc and in it we can put this.
" enable 'easy mode' source $VIMRUNTIME/evim.vim " Ctrl + q to get out of vim inoremap <c-q> <c-o>:q<cr>
Now when you open
vim just like that, it will already be in easy mode. And what's even better, is that we can get out of it easily using
Ctrl + q.
This method is what I would recommend for the people who have no intention of using
vim frequently (or even use it at all). By doing this, even if you enter vim by accident, you can use it like a normal text editor or at the very least you can get out of it fast.
Since we are here
By "here" I mean editing the
.vimrc file, may I suggest a couple options for you to add?
- Avoid creating temporary files.
set noswapfile set nobackup
- Highlight the line where your cursor is at.
set cursorline
- Enable syntax highlight and better colors.
if (has("termguicolors")) set termguicolors endif syntax enable
- Shortcuts for search and replace.
" Ctrl + f to begin searching inoremap <c-f> <c-o>/ " Ctl + f (x2) to stop highlighting the search results inoremap <c-f>f <c-o>:nohlsearch<cr> inoremap <c-f><c-f> <c-o>:nohlsearch<cr> " F3 go to the previous match inoremap <F3> <c-o>:normal Nzz<cr> " F4 go to the next match inoremap <F4> <c-o>:normal nzz<cr> " Ctrl + h begin a search and replace inoremap <c-h> <c-o>:%s///gc<Left><Left><Left><Left>
That last one needs some explanation. After pressing
Ctrl + h you'll have this in the prompt
%s/|//gc (
| is the cursor). This is a substitute command, it works something like this.
s/{search query}/{the replacement}/gc
For example, let's say I want to replace
Left with
Right, I would need to write this.
s/Left/Right/gc
This will make
vim search for every
Left instance, when it finds one it will ask us if we want to replace it, and it will put
Right if we say yes.
Conclusion
Now finally you have all the tools you need to make vim behave like a conventional text editor. From now on your experience with vim doesn't have to be so terrible.
Sources
Thank you for reading. If you find this article useful and want to support my efforts, buy me a coffee ☕. | https://vonheikemen.hashnode.dev/vims-easy-mode-making-vim-behave-like-a-conventional-text-editor | CC-MAIN-2021-39 | refinedweb | 1,089 | 81.73 |
Published 2020-09-15
This article documented down on how to skip to the next iteration when you're using
foreach. Besides, you will also know the correct scenario to use
foreach.
Without further ado, let's start.
Skipping a
foreach loop is easy. Simply using
return when it is matching the condition. Refer the code below.
const arr = ['Peter', 'Sam', 'Helena']; arr.forEach((name) => { if (name === 'Helena') { return; } console.log(`Person name: ${name}`); });
Output
"Person name: Peter" "Person name: Sam"
With this example, we're skipping the loop when the iteration reached "Helena".
However, are we using
forEach in all the scenarios?
The answer is obvious, No!
For this scenario, it would be the best case for
forEach. This is because no matter what happened, we're going to loop until the end of the array and find out the person with the first name Mary.
const guestNames = [ { firstName: 'Mary', lastName: 'Skola'}, { firstName: 'Peter', lastName: 'Machinki'}, { firstName: 'Mary', lastName: 'Jones'}, { firstName: 'Helen', lastName: 'Kovavic'}, ]; guestNames.forEach((name, index) => { console.log(`Running ${index + 1} iteration`); // We're skipping as long as the firstName is not Mary. if (name.firstName !== 'Mary') { return; } console.log(`Guest: ${name.firstName} ${name.lastName}`); });
Output
"Running 1 iteration" "Guest: Mary Skola" "Running 2 iteration" "Running 3 iteration" "Guest: Mary Jones" "Running 4 iteration"
For this scenario, you can also simply achieve what you want using
forEach loop. However, that is not the best-case scenario. This is because you would have to go through the whole size of the array to find "Mary Jones". It is like the metaphor below:
Is there a better approach we can use? Absolutely YES. We can leverage
find .
const guestNames = [ { firstName: 'Mary', lastName: 'Skola'}, { firstName: 'Peter', lastName: 'Machinki'}, { firstName: 'Mary', lastName: 'Jones'}, { firstName: 'Helen', lastName: 'Kovavic'}, ]; const foundGuest = guestNames.find((name, index) => { console.log(`Running ${index + 1} iteration`); return (name.firstName === 'Mary' && name.lastName === 'Jones'); }); console.log('Found Guest', foundGuest);
Output
"Running 1 iteration" "Running 2 iteration" "Running 3 iteration" "Found Guest" [object Object] { firstName: "Mary", lastName: "Jones" }
Here are the key points of this article.
returnto skip the loop and go to the next iteration in
foreach
forEachwhen you decided to go through all elements in the array no matter what happened.
findwhen you decided to get the matching element from the array and ignore the rest.
Thank you for reading. See you in the next article. | https://tekloon.dev/how-to-skip-foreach-loop/ | CC-MAIN-2021-10 | refinedweb | 398 | 59.8 |
Difference between revisions of "Python"
Latest revision as of 09:22, 17 October 2021:
Conventions
In this documentation, some conventions for Python examples should be followed.
This is a typical function signature
Wire = make_wire(pointslist, closed=False, placement=None, face=None, support=None)
- Arguments with key-value pairs are optional, with the default value indicated in the signature. This means that the following calls are equivalent:
Wire = make_wire(pointslist, False, None, None, None) Wire = make_wire(pointslist, False, None, None) Wire = make_wire(pointslist, False, None) Wire = make_wire(pointslist, False) Wire = make_wire(pointslist)
- In this example the first argument doesn't have a default value so it should always be included.
- When the arguments are given with the explicit key, the optional arguments can be given in any order. This means that the following calls are equivalent:
Wire = make_wire(pointslist, closed=False, placement=None, face=None) Wire = make_wire(pointslist, closed=False, face=None, placement=None) Wire = make_wire(pointslist, placement=None, closed=False, face=None) Wire = make_wire_wire([p1, p2, p3], closed=True)
- If code needs to be broken over several lines, this should be done at a comma inside brackets or parentheses; the second line should be aligned with the previous one.
a_list = [1, 2, 3, 2, 4, 5] Wire = make_wire(pointslist, False, None, None, None)
- Functions may return an object that can be used as the base of another drawing function.
Wire = make_wire(pointslist, closed=True, face=True) Window = make_window_window() and
myModule.make_window() may coexist without problem.
Full examples should include the necessary imports and the prefixed functions.
import FreeCAD as App import Draft p1 = App.Vector(0, 0, 0) p2 = App.Vector(1, 1, 0) p3 = App.Vector(2, 0, 0) Wire = Draft.make_wire([p1, p2, p3], closed=True)
import FreeCAD as App import Draft import Arch p1 = App.Vector(0, 0, 0) p2 = App.Vector(1, 0, 0) p3 = App.Vector(1, 1, 0) p4 = App.Vector(0, 2, 0) pointslist = [p1, p2, p3, p4] Wire = Draft.make_wire(pointslist, closed=True, face=True) Structure = Arch.make_structure(Wire, name="Big pillar")
> | https://wiki.freecadweb.org/index.php?title=Python&curid=111533&diff=1055508&oldid=1027027 | CC-MAIN-2021-49 | refinedweb | 340 | 57.06 |
declaration/definition
domain-bound? global type name (variable (to numeric-expression)? (initial-size numeric-expression)? | size numeric-expression)? (initial shelf-literal | elsewhere)? (local | field) type name (variable (to numeric-expression)? (initial-size numeric-expression)? | size numeric-expression)? (initial shelf-literal)? constant type name (size numeric-expression)? (initial shelf-literal | elsewhere)?
Argument definitions
You can use the keywords
global and
local to declare shelves of any supported data type. A shelf is a data container that can have
its value changed at any time.
The keyword
constant is used to declare constants of any
supported data type. A constant is a data container that can have its value set once when it is created, and
cannot be changed later.
The keyword
field declares a field in a record. A record
can contain one or more fields, and each field is a data container, like a shelf.
Three classes of data types are available in OmniMark:
integer,
string,
stream, and
switch.
declare record.
global and
constant shelves are available across your entire program. However,
globals
declared inside a module are not visible outside that
module, unless
exported, and
globals declared in the main program are not visible inside the
modules it
imports, unless exposed to those modules using
supply.
A
global shelf declaration can be prefixed by keyword
domain-bound. The actions
save and
save-clear treat such shelves differently from ordinary
global variables, but otherwise they have
the same properties.
local shelves are available in the scope in which they are
created. All
constants are
global and must be declared in a global context. Local constants are
not permitted.
The following code declares four
global shelves of different types:
global integer i global string s global switch w global tcp.connection c global point xThe last two of these assume that the types
tcp.connectionand
pointhave been declared.
The following code declares a
local shelf in the scope of a
find rule:
find letter+ local integer j
Initial values can be assigned to shelves when they are declared:
global integer i initial { 6 } global string s initial { "Mary had a little lamb." } global switch w initial { true }
A constant must be initialized when it is declared because its value cannot be changed:
constant float x initial { -1.0 }
Shelves and constants can be initialized using dynamic values:
global bcd x initial { 6.5 } global bcd y initial { x + 9.3 } global integer port-number initial { 5300 + #args[3] } global tcp.service service initial { tcp.create-service on port-number } constant string birth-time initial { date "=h:=m:=s" } process local tcp.connection connection initial { tcp.accept-connection from service }
Any value used in a dynamic initializer must itself be initialized before it is used.
Shelves can be declared to have a fixed-size or a variable-size shelves:
global integer i variable global string s size 3
A variable-size shelf can also be given an initial size:
process local switch w variable initial-size 5
The default initial size of a variable-size shelf is 0.
Initial values can be declared for both fixed-size and variable-size shelves. For variable-size shelves, the
number of initial values must match the number of items on the shelf. For fixed-size shelves, the number of
initial values cannot exceed the size of the shelf.
process local integer fibonacci variable initial-size 9 initial { 0, 1, 1, 2, 3, 5, 8, 13, 21 } local string animals size 4 initial { "cow", "dog", "pig", "hen" }
Keys can also be assigned to the initial values that are declared:
process local switch mammals variable initial-size 3 initial { true with key "cow", false with key "hen", true with key "dog" }
The initial size of a variable-size shelf can be omitted when initial values are specified. The initial size
of the shelf will be set to the number of initial values specified:
process local switch mammals variable initial { true with key "cow", false with key "hen", true with key "dog" }
Similarly, the
size of a multi-item fixed-sized shelf does not need to be specified: specified, the
resulting shelf has a fixed-size equal to the number of items in the
initial part.
The initializer can be empty, thus creating a shelf with zero items. This is useful for creating a
constant shelf with no items:
constant integer empty-integer-shelf initial { }
A
constant cannot be
variable in size. If a
size is specified, it must be the number
of items in the
initial part.
global shelves can be initialized from the command line using the
-os,
-define,
-activate,
-deactivate, or
-counter command-line options. A shelf with an initial size other than 1 cannot be
initialized from the command line.
constants and
globals decared in
modules cannot be
initialized from the command line.
globals shelves and
constant shelvess can be pre-defined by using the
keyword
elsewhere instead of an initializer.
initial-size cannot be specified in a
pre-definition.
local shelves and
fields of
record types cannot be pre-defined.
The default values of OmniMark's built-in shelvf types are as follows:
streamare initialized to
unattached,
stringare initialized to the empty string,
integerare initialized to 0, and
switchare initialized to
false.
A
global or
constant declaration occurring in a module may be preceded by the
export keyword. This makes that
global shelf or
constant shelf available to the importer of the
module.
A
global declaration in a module can be preceded by
require to indicate that a
global shelf of the same type must be provided to it using
supply. The importer of the
module
must provide the required
global using a
supply clause on the
import declaration.
require declarations may not indicate any size or initial value information. | http://developers.omnimark.com/docs-extract/html/keyword/150.htm | CC-MAIN-2013-48 | refinedweb | 957 | 53.92 |
It is not recommended to server static files through Flask app, you have to configure your web server to do that. However If you still need to serve static files through your Flask app, here is the way how to do that.
There is a function called “send_from_directory” which can take a file from given path and return.Let’s use it
send_from_directory( <FilePath>, <FileName> )
- Import Modules
from flask import send_from_directory
- Creating route
@app.route('/js/<filename>') def js_files(path): return send_from_directory('js', path) @app.route('/css/<filename>') def css_files(path): return send_from_directory('css', path) @app.route('/images/<filename>') def image_files(path): return send_from_directory('images', path)
Here I have implemented three routes for serving js, css and images. Replace ‘js’ , ‘css’, ‘images’ with your static file paths. | https://errorsfixing.com/python-flask-serve-static-files-images-js-css-etc/ | CC-MAIN-2022-27 | refinedweb | 127 | 57.47 |
C Interface
#include <papi.h>
int PAPI_cleanup_eventset(int EventSet );
int PAPI_destroy_eventset(int * EventSet );
Fortran Interface
#include fpapi.h
PAPIF_cleanup_eventset(C_INT EventSet, C_INT check )
PAPIF_destroy_eventset(C_INT EventSet, C_INT check )
PAPI_cleanup_eventset() removes all events from a PAPI event set and turns off profiling and overflow for all events in the eventset. This can not be called if the EventSet is not stopped. PAPI_destroy_eventset() deallocates the memory associated with an empty PAPI event set.
EventSet -- an integer handle for a PAPI event set as created by PAPI_create_eventset (3). *EventSet -- a pointer to the integer handle for a PAPI event set as created by PAPI_create_eventset (3). The value pointed to by EventSet is then set to PAPI_NULL on success.
PAPI_EINVAL One or more of the arguments is invalid. Attempting to destroy a non-empty event set or passing in a null pointer to be destroyed.
PAPI_ENOEVST The EventSet specified does not exist.
PAPI_EISRUN The EventSet is currently counting events.
PAPI_EBUG Internal error, send mail to ptools-perfapi@ptools.org and complain.
/* Remove all events in the eventset */
if (PAPI_cleanup_eventset(EventSet) != PAPI_OK)
handle_error(1);
/* Free all memory and data structures, EventSet must be empty. */
if (PAPI_destroy_eventset(&EventSet) != PAPI_OK)
handle_error(1);
If the user has set profile on an event with the
call, then when destroying
the EventSet the memory allocated by
will not be freed. The user should turn off
profiling on the Events before destroying the
EventSet to prevent this behavior.
PAPI_profil(3), PAPI_create_eventset(3), PAPI_add_event(3), PAPI_stop(3) | http://icl.cs.utk.edu/projects/papi/wiki/PAPI3:PAPI_destroy_eventset.3 | CC-MAIN-2016-36 | refinedweb | 245 | 59.4 |
This section is the place to post your general code offerings -- everything from one-liners to full-blown frameworks and apps.
So, I've been asked by a couple of people now if I would take some of the experience I've gained over the last half year or so, and put together some form of tutorial on wrapping a C library, and more generally, XS. This is the first cut of that tutorial.
Relatively, I am still very new to all of this, as it's a pretty complex world. Before I started, I didn't have any real C experience, so I've been dealing with that learning curve at the same time, so I know there are better and more efficient ways of doing what I do, and would appreciate any feedback.
I'll get right to it. Here's an overview:
The actual C code is irrelevant at this point, but knowing the definitions in use is, so here they are for the xswrap library:
int mult (int x, int y);
void speak (const char* str);
unsigned char* arr (); // returns (0, 1, 2)
[download]
Create a new shell distribution
I use Module::Starter:
module-starter \
--module=XS::Wrap \
--author="Steve Bertrand" \
--license=perl
[download]
Now change into the new XS-Wrap directory, which is the root directory of the new dist. The Perl module file is located at lib/XS/Wrap.pm. I've removed a bunch of stuff for brevity, but the shell looks something like this:
package XS::Wrap;
use warnings;
use strict;
our $VERSION = '0.01';
[download]
Create the base XS file
I use Inline::C to do this for me, as like most Perl hackers, I'm often lazy. Note the flags in use. clean_after_build tells Inline to not clean up the build directory (_Inline after build). This allows us to fetch our new .xs file. name is the name of the module we're creating this XS file for.
use warnings;
use strict;
use Inline Config =>
disable => clean_after_build =>
name => 'XS::Wrap';
use Inline 'C';
__END__
__C__
#include <stdio.h>
#include <xswrap.h>
[download]
The resulting XS file is located in _Inline/build/XS/Wrap/Wrap.xs. Copy it to the root directory of the dist:
Here's what our base XS file looks like. It doesn't do anything yet, but we'll get there:
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "INLINE.h"
#include <stdio.h>
#include <xswrap.h>
MODULE = XS::Wrap PACKAGE = main
PROTOTYPES: DISABLE
[download]
See the PACKAGE = main there? Change main to the name of our dist, XS::Wrap.
Adding the functions from the shared library to XS
Now we need to define our C functions within the XS file. After I've done that using the C definitions for the functions above, my XS file now looks like this
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "INLINE.h"
#include <stdio.h>
#include <xswrap.h>
MODULE = XS::Wrap PACKAGE = XS::Wrap
PROTOTYPES: DISABLE
int mult (x, y)
int x
int y
void speak (str)
const char* str
unsigned char* arr ()
[download]
Note that at this point, because we're not using Inline anymore, you can remove the include for the INLINE.h header file. However, in our case, we're going to be using some Inline functionality a bit later on, so instead of removing that, copy the INLINE.h file to the same directory we copied our XS file into: cp _Inline/build/XS/Wrap/INLINE.h .
Readying the module file for use
Now we have some work to do to pull in the XS, wrap the functions, and export them. Note that you do not *need* to wrap the functions with Perl, you can export them directly as depicted in the XS file if you wish, as long as you know you don't need to add any further validation or functionality before the XS imported C function is called. I'll wrap all three. The functions that each wrapped function calls is the literal C function, as advertised through the XS file we hacked above.
use warnings;
use strict;
our $VERSION = '0.01';
require XSLoader;
XSLoader::load('XS::Wrap', $VERSION);
use Exporter qw(import);
our @EXPORT_OK = qw(
my_mult
my_speak
my_arr
);
our %EXPORT_TAGS;
$EXPORT_TAGS{all} = [@EXPORT_OK];
sub my_mult {
my ($x, $y) = @_;
return mult($x, $y);
}
sub my_speak {
my ($str) = @_;
speak($str);
}
sub my_arr {
my @array = arr();
return @array;
}
[download]
Telling the Makefile to load the external C library
Because we're using an external shared library, we need to add a directive to the Makefile.PL file. Put the following line anywhere in the Makefile.PL's WriteMakefile() routine:
LIBS => ['-lxswrap'],
[download]
Building, installing and initial test
Let's build, install and write a test script for our new distribution.
perl Makefile.PL
make
make install
[download]
At this point, if everything works as expected, you're pretty well done. However, in the case here, we're going to unexpectedly run into some issues, and we'll need to do other things before we finalize our distribution.
Test script (example.pl). Very basic, it just tests all three wrapped functions:
use warnings;
use strict;
use feature 'say';
use XS::Wrap qw(:all);
say my_mult(5, 5);
my_speak("hello, world!\n");
my @arr = my_arr();
say $_ for @arr;
[download]
Output:
25
hello, world!
[download]
Hmmm, something is not right. The arr() C function was supposed to return an array of three elements, 0, 1, 2, but we get no output.
This is because arr() returns an unsigned char* which we can't handle correctly/directly in Perl.
In this case, I will just wrap the arr() function with a new C function (I've called it simply _arr()) that returns a real Perl array based on the output from the original C arr() function. Technically, I won't be returning anything, I'm going to just use functionality from Inline to push the list onto the stack (one element at a time), where Perl will automatically pluck it back off of the stack.
To do this, I'll be leveraging Inline again, but with a couple of changes. We change the name, and add also bring in our shared library because we need it directly now.
Returning a Perl array from a C function
use warnings;
use strict;
use Inline config =>
disable => clean_after_build =>
name => 'Test';
use Inline ('C' => 'DATA', libs => '-lxswrap');
print "$_\n" for _arr();
__END__
__C__
#include <stdio.h>
#include <xswrap.h>
void _arr (){
unsigned char* c_array = arr();
inline_stack_vars;
inline_stack_reset;
int i;
for (i=0; i<3; i++){
inline_stack_push(sv_2mortal(newSViv(c_array[i])));
}
inline_stack_done;
}
[download]
After I execute that Perl script, I'm left with a new XS file within the _Inline/build/Test/Test.xs.. It looks like this:
= Test PACKAGE = main
PROTOTYPES: DISABLE
void
_arr ()
PREINIT:
I32* temp;
PPCODE:
temp = PL_markstack_ptr++;
_arr();
if (PL_markstack_ptr != temp) {
/* truly void, because dXSARGS not invoked */
PL_markstack_ptr = temp;
XSRETURN_EMPTY; /* return empty stack */
}
/* must have used dXSARGS; list context implied */
return; /* assume stack size is correct */
[download]
We only need a couple of pieces of it, so get out your CTRL-V and CTRL-C. Here are the sections (cleaned up a bit for brevity) that we need to copy into our real Wrap.xs file.
The C portion:
void _arr (){
unsigned char* c_array = arr();
inline_stack_vars;
inline_stack_reset;
int i;
for (i=0; i<3; i++){
inline_stack_push(sv_2mortal(newSViv(c_array[i])));
}
inline_stack_done;
}
[download]
The XS portion:
void
_arr ()
PREINIT:
I32* temp;
PPCODE:
temp = PL_markstack_ptr++;
_arr();
if (PL_markstack_ptr != temp) {
PL_markstack_ptr = temp;
XSRETURN_EMPTY;
}
return;
[download]
The C part goes near the top of the XS file, and the XS part goes in the XS section at the bottom. Here's our full XS file after I've merged in these changes.
Finalized XS file
= XS::Wrap PACKAGE = XS::Wrap
PROTOTYPES: DISABLE
int mult (x, y)
int x
int y
void speak (str)
const char* str
unsigned char* arr ()
void
_arr ()
PREINIT:
I32* temp;
PPCODE:
temp = PL_markstack_ptr++;
_arr();
if (PL_markstack_ptr != temp) {
PL_markstack_ptr = temp;
XSRETURN_EMPTY;
}
return;
[download]
So, in our XS, we have four functions. Three that are imported directly from the C shared lib (mult(), speak() and arr()) and one new one written in C locally that wraps an imported XS function (_arr()).
We need to do a quick update to the wrapper in the module file. Change the call to arr() to _arr() in the .pm file within the my_arr() function:
sub my_arr {
my @array = _arr();
return @array;
}
[download]
Repeat the build/install steps, then test again:
perl example.pl
25
hello, world!
0
1
2
[download]
Cool! Our custom C wrapper for arr() works exactly how we want it to.
Creating a release of our distribution
It's very trivial to do:
rm -rf _Inline
perl Makefile.PL
make
make test
make manifest
make install
make dist
[download]
Of course, you have written all of your POD and unit tests before reaching this point, but I digress :)
I've also posted this at blogs.perl.org.
update: I want to thank all of the Monks here who have provided me help, feedback, advice and in a couple of cases, some ego-kicking. I will not name said Monks because I'm very afraid of leaving someone out, but you know who you are.
Pi day isn't quite over, but given that most know about my Raspberry Pi work, I thought I'd share something.
I have been focusing on creating a physical layout for all of the supported Integrated Circuits and other peripherals that are available to Perl under the Pi, so that I can create a full-blown automated test regimen that runs continuously against the code using my Test::BrewBuild software.
Because the work is very precise and requires diligence to ensure everything is as connected properly as it is confirmed that numbers match up so that when proper tests are finally written everything aligns, I thought I'd share a tiny piece of what I was working on before Pi day is over.
Given this diagram, which utilizes a RPi 3, an MCP3008 analog to digital converter, an MCP4922 digital to analog converter and a 74HC595 shift register as a baseline, here's some base initial test code that produces human-readable output so I can ensure the setup is reasonable:
use warnings;
use strict;
use feature 'say';
use RPi::WiringPi;
use RPi::WiringPi::Constant qw(:all);
my ($dac_cs_pin, $adc_cs_pin) = (12, 26);
my $adc_shiftreg_in = 0;
my $adc_dac_in = 1;
my $pi = RPi::WiringPi->new;
my $dac = $pi->dac(
model => 'MCP4922',
channel => 0,
cs => $dac_cs_pin
);
my $adc = $pi->adc(
model => 'MCP3008',
channel => $adc_cs_pin
);
print "DAC...\n\n";
for (0..4095){
$dac->set(0, $_);
if ($_ % 1000 == 0 || $_ == 4095){
say $adc->percent($adc_dac_in);
}
}
my $sr = $pi->shift_register(100, 8, 21, 20, 16);
print "\nShift Resgister...\n\n";
my $sr_pin = $pi->pin(100);
$sr_pin->write(HIGH);
say $adc->percent($adc_shiftreg_in);
[download]
DAC...
0.00
24.24
48.68
73.02
97.46
99.80
Shift Resgister...
100.00
[download]
Much is on the chopping block for change, but I am making no fundamental changes until my CI is complete, and I get a much better understanding of what isn't working properly, and where. I know that PWM requires root which actually crashes the Pi if you don't sudo, and I know that Interrupts aren't doing the right thing.
This step back from coding to focus on tests first, is how I usually do things. Having wrapped a lot of this code, it's come off as a bit of a new challenge to me (because it isn't write tests first then code, it's been code first, then think tests), but I've realized I need to get back to basics; test it first, then move on.
Anyways, as I said early this morning, I'll say the same thing heading out. Happy Pi day ;)
Hello,
I came across a cool post by Abigail-II and thought to try it with MCE::Hobo. Thank you, trippledubs for posting the link.
On Windows, MCE::Hobo spawns threads. Otherwise, childrens on Cygwin and other platforms. The following is a demonstration for many hobos, but never more than a fixed number at a given time.
use strict;
use warnings;
use MCE::Hobo;
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Based on ( by Abigail-II ).
# Currently, MCE::Hobo emits a message to STDERR if unable to spawn.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sub mhobo ($$&) {
my ($count, $max, $code) = @_;
foreach my $c (1 .. $count) {
MCE::Hobo->waitone() unless $c <= $max;
exit(255) unless defined (my $h = MCE::Hobo->create($code, $c));
}
MCE::Hobo->waitall();
}
sub ahobo (\@$&) {
my ($data, $max, $code) = @_;
my $c = 0;
foreach my $data (@$data) {
MCE::Hobo->waitone() unless ++$c <= $max;
exit(255) unless defined (my $h = MCE::Hobo->create($code, $data))
+;
}
MCE::Hobo->waitall();
}
STDOUT->autoflush(1); # Perl 5.14 or higher
mhobo 9, 3, sub {
print $_[0]."\n";
for (1 .. 4e7) { 1 } # simulate busy
};
my @input = ( 'a' .. 'i' );
ahobo @input, 3, sub {
print $_[0]."\n";
for (1 .. 4e7) { 1 } # ditto
};
[download]
Regards, Mario.
I.
class PaganVision2::Entity is GameObject
{
has $!staticimagelib ### StateImagelibrary.pm6
method update(%keys, %keydefs) {
}
method draw($renderer) {
$!staticimagelib.getImage().display($renderer);
}
}
class PaganVision2::MovingEntity is GameObject
{
has $!direction;
has $!moving;
has $!dx; ### move x + dx
has $!dy;
has $!leftstaticimagelib ### StateImagelibrary.pm6
has $!righttstaticimagelib
has $!upstaticimagelib
has $!downstaticimagelib
has $!leftimagelib
has $!rightimagelib
has $!upimagelib
has $!downimagelib
has $!currentlibrary;
method update(%keys, %keydefs) {
foreach $e in %keydefs.keys {
if (not $e[0]) { ### UP
$!currentlibrary = $upstaticimagelib;
} elif (not $[1]) { ### DOWN
$!currentlibrary = $downstaticimagelib
+;
} elif (not $e[2]) { ### LEFT
$!currentlibrary = $leftstaticimagelib
+;
} elif (not $e[3]) { ### RIGHT
$!currentlibrary = $rightstaticimageli
+b;
}
}
}
method draw($renderer) {
$!currentlibrary.getImage().display($renderer);
}
}
### Note that Room is a GameObject and that it can be put in e.g. a ba
+g of wonders
class PaganVision2::Room is GameObject
{
method BUILD() {
### Image $!bg_image .= new;
}
}
### This entity is recursive which means that
### it contains things that contain this entity
### If an Entity becomes recursive it
### morphs into EntityRec in the game engine
class PaganVision2::EntityRec : is Entity
{
method update(%keys, %keydefs) {
}
method draw($renderer) {
$!staticimagelib.getImage().display($renderer);
}
}
[download]
Dear Monks,
Most likely, everyone who's needed to access a serial port on *NIX systems
has used, or at least come across, Device::SerialPort.
It's nice because it provides a decent level of portability, being designed to be
a replacement for Win32::SerialPort. However, it's always bugged me a
little bit that the module is a bit unwieldy, with a lot of configuration and
functions I never use, several documented as being experimental, and that its
filehandle interface is tied instead of native.
So, I'd like to present an alternative that has been working well for me over
the past months, IO::Termios. It's a subclass of
IO::Handle, and the handles can be used directly in IO::Select
loops, which can be used to implement nonblocking I/O and timeouts, or for
example a POE POE::Wheel::ReadWrite, just to mention two possibilities.
(Note: I'm not saying IO::Termios is "better" than Device::SerialPort,
just that so far it has been a viable alternative.)
Here's a basic example:
use IO::Termios ();
my $handle = IO::Termios->open('/tmp/fakepty', '4800,8,n,1')
or die "IO::Termios->open: $!";
while (<$handle>) { # read the port line-by-line
chomp;
print time." <$_>\n";
# write something to the port
print {$handle} "Three!\n" if /3/;
}
close $handle;
[download]
You may have noticed that in the above example, instead of the usual device names like e.g. /dev/ttyAMA*, /dev/ttyS*, or /dev/ttyUSB*, I used "/tmp/fakepty".
I created this for testing using the versatile tool socat, here are two examples:
# connect the fake pty to a process that generates output
$ socat pty,raw,echo=0,link=/tmp/fakepty \
exec:'perl -e "$|=1;while(1){print q{Foo },$x++,qq{\n};sleep 2}"'
# connect the fake pty to the current terminal
$ socat pty,raw,echo=0,link=/tmp/fakepty -,icanon=0,min=1
[download]
It's also possible to use sysopen for the ports, if you want to
have control over the exact flags used to open the port. Also, if you need
to set some stty modes, you can do so with IO::Stty.
I've found that for several of the USB-to-Serial converters I've used that
it's necessary to set the mode -echo for them to work correctly,
and raw is necessary for binary data streams.
use Fcntl qw/:DEFAULT/;
use IO::Termios ();
use IO::Stty ();
sysopen my $fh, '/tmp/fakepty', O_RDWR or die "sysopen: $!";
my $handle = IO::Termios->new($fh) or die "IO::Termios->new: $!";
$handle->set_mode('4800,8,n,1');
IO::Stty::stty($handle, qw/ raw -echo /);
my $tosend = "Hello, World!\n";
$handle->syswrite($tosend)
== length($tosend) or die "syswrite";
for (1..3) {
my $toread = 1;
$handle->sysread(my $in, $toread)
== $toread or die "sysread";
print "Read $_: <$in>\n";
}
$handle->close;
[download]
My error checking in the above example is a little simplistic, but
I just wanted to demonstrate that using sysread and syswrite
is possible like on any other handle.
I've noticed that there is some interaction between IO::Termios
and IO::Stty - for example, when I had to connect to a serial device
using 7-bit and even parity, I hat to set the termios mode to
4800,7,e,1 and set the stty modes
cs7 parenb -parodd raw -echo for things to work correctly.
I have written a module that wraps an IO::Termios handle
and provides read timeout, flexible readline, signal handling support,
and a few other things. However, I need to point out that while I've
been using the module successfully in several data loggers over the past
few months in a research environment, it should not yet be considered
production quality! The major reason is that it's not (yet?) a real CPAN
distro, and it has zero tests! But if you're still curious, for example how
I implemented a read timeout with IO::Select, you can find the code
here.
Update: Added mention of some /dev/* device names.
Greetings, fellow Monks.
I came across an old thread. One might do the following to consume extra CPU cores. The pigz binary is useful and depending on the data, may run faster than gzip. The requirement may be to have each MCE worker process a single file inside the MCE loop. So we set chunk size accordingly (chunk_size => 1).
To make this more interesting, workers send data to STDOUT and gather key-value pairs.
use strict;
use warnings;
use feature qw(say);
use MCE::Loop chunk_size => 1, max_workers => 4;
my @files = glob '*.gz';
my %result = mce_loop {
my ($mce, $chunk_ref, $chunk_id) = @_;
## $file = $_; same thing when chunk_size => 1
my $file = $chunk_ref->[0];
##
## For pigz, we want -p1 to run on one core only.
## open my $fh, '-|', 'pigz', '-dc', '-p1', $file or do { ... }
open my $fh, '-|', 'gzip', '-dc', $file or do {
warn "open error ($file): $!\n";
MCE->next();
};
my $count = 0;
while ( my $line = <$fh> ) {
$count++; # simulate filtering or processing
}
close $fh;
## Send output to the manager process.
## Ensures workers do not garble STDOUT.
MCE->say("$file: $count lines");
## Gather key-value pair.
MCE->gather($file, $count);
} @files;
## Workers may persist after running. Request workers to exit.
MCE::Loop->finish();
## Ditto, same output using gathered data.
for my $file (@files) {
say "$file: ", $result{$file}, " lines";
}
[download]
Is your (Unix/Linux) filesystem getting full and you wonder whether removing some old log files would help? Use this one-liner to find out how much space would be freed:
find /opt/app/logs -iname "*log*" -type f -mtime +30 | perl -lne '$sum
+ += (stat)[7] }{ print $sum'
[download]. | http://www.perlmonks.org/?next=15;node_id=1044 | CC-MAIN-2017-17 | refinedweb | 3,289 | 61.87 |
Send an Email Through Amazon SES Using the AWS SDK for Java
The following procedure shows you how to use Eclipse IDE for Java EE Developers and AWS Toolkit for Eclipse to create an AWS SDK project and modify the Java code to send an email through Amazon SES. It retrieves your AWS credentials from environment variables.
Before you begin this procedure, complete the setup tasks described in Before You Begin with Amazon SES and Send an Email Through Amazon SES Using an AWS SDK. AWS SDK for Java
Create an environment variable called AWS_ACCESS_KEY_ID and set it to your AWS access key ID. The procedure for setting environment variables depends on your operating system. Your AWS access key ID will look something like:
AKIAIOSFODNN7EXAMPLE.
Create an environment variable called AWS_SECRET_ACCESS_KEY and set it to your AWS secret access key. Your AWS secret access key will look something like:
wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY.
Create an AWS Java Project in Eclipse by performing the following steps:
Open Eclipse.
In Eclipse, choose File, choose New, and then choose AWS Java Project. If you do not see AWS Java Project as an option, try selecting Other.
In the Create an AWS Java Project dialog box, type a project name.
Choose Finish.
In Eclipse, in the Package Explorer window, expand your project.
Under your project, right-click the src directory, choose New, and then choose Class.
In the Java Class dialog box, in the Name field, type
AmazonSESSampleand then choose Finish.
Replace the entire contents of AmazonSESSample.java with the following code:Copy
import java.io.IOException; import com.amazonaws.services.simpleemail.*; import com.amazonaws.services.simpleemail.model.*; import com.amazonaws.regions.*; Amazon SES by using the AWS SDK for Java."; static final String SUBJECT = "Amazon SES test (AWS SDK for Java)"; public static void main(String[] args) throws IOException { // Construct an object to contain the recipient address. Destination destination = new Destination().withToAddresses(new String[]{TO}); // Create the subject and body of the message. Content subject = new Content().withData(SUBJECT); Content textBody = new Content().withData(BODY); Body body = new Body().withText(textBody); // Create a message with the specified subject and body. Message message = new Message().withSubject(subject).withBody(body); // Assemble the email. SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination).withMessage(message); try { System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java..."); // Instantiate an Amazon SES client, which will make the service call. The service call requires your AWS credentials. // Because we're not providing an argument when instantiating the client, the SDK will attempt to find your AWS credentials // using the default credential provider chain. The first place the chain looks for the credentials is in environment variables // AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. // For more information, see AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(); // Choose. Here, we are using // the US West (Oregon) region. Examples of other regions that Amazon SES supports are US_EAST_1 // and EU_WEST_1. For a complete list, see Region REGION = Region.getRegion(Regions.US_WEST_2); client.setRegion(REGION); // Send the email. client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } } }
In AmazonSESSample.java, replace the following.
REGION—Set this to. In this example, we are using the US West (Oregon) region. Examples of other regions that Amazon SES supports are US_EAST_1 and EU_WEST_1. For a complete list of AWS regions that Amazon SES supports, see Regions and Amazon SES.
Save AmazonSESSample.java.
To build the project, choose Project and then choose Build Project. (If this option is disabled, you may have automatic building enabled.)
To start the program and send the email, choose Run and then choose Run again.
Review the program's console output to verify that the sending was successful. (You should see "Email sent!")
Log into the email client of the recipient address. You will find the message that you sent. | http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-java.html | CC-MAIN-2017-17 | refinedweb | 653 | 52.26 |
Client
Apache Axis2 - Apache Axis2 Tutorial
In this example we will develop
client application and test it. ...
Apache Axis2 - Apache Axis2 Tutorial
In this section we will learn Apache Axis2 with the help of
examples. Apache
Axis2 Eclipse plugin Tutorial
are
developing the client application to consume the Web service, it is
also...
Axis2 Eclipse plugin Tutorial
In this section we will learn about Axis2 Eclipse plugins. There
are plugins available
Apache Axis2 Introduction
Apache Axis2 Introduction
Axis2: An Introduction
In this section introduces you with the Apache Axis2 framework.
Apache Axis2 is a core engine for Web services. It is a modified version of widely
Axis2 client - Axis2 Client example
Axis2 client - Axis2 Client example
Apache Axis2 Client code
In this section we will develop client code example... we will write the
Web service client code and call the web service.
Webservices(Axis
Apache Axis2 Hello World Example
;
message to the Web service client.
Directory Structure of the application
Create...
Apache Axis2 Hello World Example
Apache Axis2 Hello World Example
In this section we will develop a simple Hello World
installing axis2
Installing Axis2
Installing Axis2:
Download.../
axis2.
Unzip it into c:\axis2-1.4 folder.
Set
Axis2 sample program
Axis2 sample program Hi..
I have tried the HelloWorldServie example in axis2. While running which showing as a faulty service. The error showned as follows
This Web axisService has deployment faults
Error
What is axis2?
What is axis2?
Axis2 is Apache?s Web services
framework with two... earlier Web services are very good means of inter
application communication
Apache axis2 installation
Apache axis2 installation I have installed Apache tomcat for **axis2** Installation. But the downloaded tomcat 7.0 exe bin file, it can have no option of START and SHUTDOWN. The latest downloaded version have no such options
Installing axis2 eclipse plugin
Installing axis2 eclipse plugin
Axis2 eclipse installation - Installing Axis2 plugin on
Eclipse IDE
In this section we will install the Axis2 plugin on the Eclipse Integrated section we generated the client code manually and developed the
client to test
Webservices - WebSevices
Webservices Hi All,
Can anybody send me the sample application for developing webservices using axis2 with Eclipse Plugin.
Thanks.
regards
anwar Tutorial, Develop the Next Generation of Apache Web Services using Apache Axis2
services.
Apache Axis2 also provides the tools to generate the client code...
client code.
Apache Axis2 new features and improvements
The Apache Axis2...
Apache Axis2 tutorial
Apache Axis2
Java Client Application
Java Client Application Java Client Application
Java Client Application example
Java Client Application example Java Client Application example
Java HTML Client Application
Java HTML Client Application Java HTML Client Application
Developing Simple Web Service
developing web services with Axis2 by
an easy example ?HelloWorldService? and deploying it on the tomcat
web server.
Step 1: Build Axis2 Web Application: (axis2.war)
Download and install Apache Ant
Thin client
Thin client What is a thin client?
A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy
tcp client server communication
tcp client server communication i am not been able to find the error..."))
break;
System.out.println("FROM CLIENT: " + clientSentence...();
outToClient.close();
serverInput.close();
}
}
client:
import java.io.*;
import
Webservices - WebSevices
Webservices Hi,
I have a problem in webservices. I have defined... at the client side but i am not able to pass the xml file to webservice.
Please help... for more information.
Failed Client-Socket Communication
Failed Client-Socket Communication I hve written a server program & a client program. The server is supposed to echo watever is typed in the client. I hve to get 16 values to be echoed. I hve created a string and all
http Client Authentication
http Client Authentication hi friends,
i am trying a java API... {
System.out.println("\n Place Collection URL = "+ placeurl);
HttpClient client = new... the form parameters
method.addParameter( "CONTENT-TYPE", "application/atom+xml
MySQL Client
MySQL Client
My Sql Client Engle
This all-in-one tool will help you create, manage and edit... client programs. It also describes how to use several specific types of clients
Axis2 on Tomcat
|
Web services technologies |
Installing axis2 eclipse plugin
|
Axis2 Eclipse plugin Tutorial |
Learn WSDL2java utility of Axis2
|
Axis2 client |
Apache Axis2 Hello World |
Downloading
MySQL Client
client programs that access MySQL databases. This library defines an application...
MySQL Client
My Sql Clint... discusses general principles that are common to most MySQL client programs
Client Side validation in Struts 2 application
Client Side validation in Struts 2 application
.../showLoginClientSideValidation.action">Login Application (Client Side Validation)</a></li>... screen:
Now click on "Login Application (Client Side
Validation)"
Client Side Application
Client Side Application
For creating the Client side application firstly... side application follows these steps :
In the client sides firstly creates
who is client
who is client tell me who is client is management
Client Interview
Client Interview Hi,
I am kumar i am having client round in polaries client is a BANK. how to face client interview.
what are the expected questions from CITI
Chapter 5. Client View of an Entity
Chapter 5. Client View of an EntityPrev Part I. Exam Objectives Next
Chapter 5. Client View of an EntityIdentify correct and incorrect statements or examples about the client
RMI Client And RMI Server Implementation
application
provides the mechanism by which the server and the client communicate... RMI Client And RMI Server Implementation
Introduction
The RMI application
Rmi client
Rmi client Sir i just created client and server following the RMI rule, its running properly in the localhost, when i am trying to run the program in the different machine its not working, i changed the ip also, when i copied
Developing Axis Web services with XML Schemas.
: If you are looking for RESTful web services, please refer Axis2 ) with Axis1.4... StockQuote\webservice-client\webserviceclient-build.xml file. Note the deployed web... port and host name are different. This will generate the required client stub
Client Side and Server Side coding
Client Side and Server Side coding
The combo of client side and server side coding means the need of both scripts in an application. Without the mutual support
Java Client webservice
the wizard to help the developer to create, deploy and test the webservices application very quickly.
In this project we will make a web service program for factorial calculation.
Then develop a Java Client file instead of Servlet or Jsp
Save file on Client Machine - Development process
Save file on Client Machine Hi my application is running on main server machine and all the users of the application are accessing them as http... to save the file created by my application on the client machine how can i do
Identify correct and incorrect statements or examples about the client's view
of exceptions received from an enterprise bean invocation.
, the client can continue calling the enterprise bean. An
application....
If a client program receives an application exception from..., the client can
typically continue the transaction because an application
Unable to create web service client in java
error as I click Finish button for Client creation:
IWAB0014E Unexpected exception...Unable to create web service client in java When i try to create a client for the WSDL
JAVA - WebSevices
JAVA Hi All,
Can anybody send me the sample application for developing webservices using axis2 with Eclipse Plugin.
Thanks.
regards...://
Thanks="
Chapter 2. Client View of a Session Bean
Chapter 2. Client View of a Session BeanPrev ...;Client View of a Session BeanIdentify correct and incorrect statements or examples about the client view of a session
bean's local and remote home
struts client side validation
struts client side validation how can i code for client side validation
ssl client - JSP-Servlet
ssl client How do you write SSL Client? Take example of SSL Socket Client
Java FTP Client Example
Java FTP Client Example How to write Java FTP Client Example code?
Thanks
Hi,
Here is the example code of simple FTP client in Java which downloads image from server FTP Download file example.
Thanks
server client comms
server client comms i am trying to return frame through server client comms anyone can help me about that
i want to return a class to client side but my class defined in server side
Client Server Java app
Client Server Java app I developed a client server based java networking Instant Messaging app. The client program is needed to be run on the client... some servers and so,so that my friend who is in another city can run the client
What is Java Client Socket?
What is Java Client Socket? Hi,
What is client socket in Java...,
The client socket is basic communication interface between networked computers. The socket that make connectivity with socket client and with a socket server
Eclipse Plugin-Rich Client Applications
. Is is an example of a business oriented, rich client application which benefits from... Eclipse Plugin-Rich Client Applications....
Matchmaker-Client
Application
Java FTP Client
Java FTP Client What all Java FTP Client available to the Java programmers? Is there any Free FTP Client Library?
Thanks
Hi,
Apache... Client libraries which can be used to connect to the FTP server for:
Uploading
webservices security
webservices security am doing project in web services security. can one sugesst me a best application for web service
Client side refresh
Client side refresh What is client side refresh?
The standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.
<META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet
WebServices In JAVA
WebServices In JAVA need sample example for webservice in java platform(web application)
Hi,
Please check Web Services Examples in NetBeans.
Thanks
Client Side Address Validation in Struts
the validation error messages. In our application we need to define the messages...
Client Side Address Validation in Struts
... for the displaying the error message to the user.
Developing
Client-Server Architecture
Client-Server Architecture
Client-server architecture can be considered...; and a client machine where server has some resources that can be
shared by different
detection of the operating system on the client machine
detection of the operating system on the client machine How to detect the operating system on the client machine
importing client side web history
importing client side web history Hello,
i am just trying to import the web history of client in lan through java....
can u plz help me
Webservice client using xmlhttprequest - WebSevices
Webservice client using xmlhttprequest Hi friends, I have created a webservice using XFire api and published it. Can u plz tell me how to access this webservice using xmlhttprequest from client
Backbase AJAX Client Edition
Backbase AJAX Client Edition
Backbase offers a comprehensive AJAX Development Framework for building.... The Backbase
AJAX Client Edition takes care of all the AJAX plumbing work, allowing
Client Side Coding
Client Side Coding
Here, the client side coding refers to the code scripted for the end-client that reflects on the clients’ terminal. This type of coding is known
Features and Limitations of the Application
the client application on client side, enters the login name and hits the login... arraylist to every client.
Limitations of the application are as
follows... but the message is shown to every client. Means
this application is unable to provide
Registration timer expired, but client is still registering!
Registration timer expired, but client is still registering! Registration timer expired, but client is still registering
how to connect client to server using Sockets
how to connect client to server using Sockets how to connect client to server using Sockets
proxy server and client using java - Java Beginners
proxy server and client using java how to write program in java for proxy server and client
Application Server : Java Glossary
computer on
which the client's application is running. There are several types...
Application Server : Java Glossary
An Application server is a server side program that is
used
web service problem - WebSevices
.
Please let me know will axis2 support jax rpc client handler?
How...web service problem I have created web service client and server for File transfering using axis2/java.I want to add JAX-RPC client Handler
How to design project document for client and programmer
How to design project document for client and programmer As a business analyst, how one can create a tailored artifacts for client and programmer
client side validation based on the xml in validation.xml
client side validation based on the xml in validation.xml How you will enable front-end client side validation based on the xml in validation.xml
Client Auto Refresh in Servlets
Client Auto Refresh in Servlets
This section illustrates you how client gets auto refresh.
We are providing you an example which explains you clearly. In the example,
We have created
thin-client project - Java Interview Questions
thin-client project what is thin-client project??? Plz help me Hi Friend,
Please visit the following link:
Hope that it will be helpful for you
Multicast Client in Java
UDP Multicast Client in Java
... to send and receive the IP
packet or message by multicast client. Here, we provide...') and port number(5000). Those of any client sends
and receives IP packet
Create text file at client's directory from server.
Create text file at client's directory from server. Need java code to create text file at client's directory from server.....
Please Help
Server side validation vs client side validation
Server side validation vs client side validation Can any one tell me the difference between these two different ways of Validation? Also features of Server side validation vs client side validation.
The client side | http://www.roseindia.net/tutorialhelp/comment/99700 | CC-MAIN-2014-52 | refinedweb | 2,279 | 53.92 |
Please see org.netbeans.modules.cnd.completion.CCBasicCompletionTestCase for example.
Product Version: NetBeans IDE Dev (Build 201307122300)
Hi Petr, isn't this a Maven based CND project? If so, this might be a duplicate of issue #232519.
Hi Jiri, no, this is Ant based project.
Maybe a CND project issue?
I don't know, but really doubt that this is our issue. Even could not imagine how it might be related to us, because it is a bug in Java project ;)
By the way, in other modules (org.netbeans.modules.utilities for example) both items are active in all test classes, but if I create new one, they are still inactive in it.
Test class, which I use for tests:
public class NewClass extends NbTestCase {
public NewClass(String name) {
super(name);
}
// Debug focused should be active
public void testABC() throws Exception {
}
}
Later I'll try to create new module and check if the bug could be reproduced in it.
Then it must be a problem of JUnit integration. The fact that it concerns Run as well, proves that it's not a bug of debugger.
I experience the same issue in Linux. Run/Debug focused test method doesn't work i.e. if I open org.netbeans.modules.cnd.completion.NamespacesTestCase
(In reply to petrk from comment #4)
> I don't know, but really doubt that this is our issue.
The problem lies with the naming of your test casses. The menu items are disabled in all the classes that end with TestCase.java and are enabled in all classes that end with Test.java right? If this is the case then this is as designed. please see bug 227358 for discussion about the way the "Run/Debug focused test method" menu items get enabled.
When you try to create a new test case for an existing class then the wizard informs you that you need to have a test class ending with Test.java in order for the infrastructure to be able to run the file and navigate between test and tested classes.
Honestly I've never used wizard to create tests :-)?
*** Bug 234620 has been marked as a duplicate of this bug. ***
Can we restore "Run/Debug focused test method" inside *TestCase classes back? While it's ok to have disabled navigate between test and tested classes if this is a problem.
(In reply to Vladimir Voskresensky from comment #8)
> Honestly I've never used wizard to create tests :-)
on the other hand I almost always use the wizard :)
>?
Fair enough. Fixed:. Now the actions are enabled if the activated file is a java file and is contained in a test folder.
Great! Thank you so much!
*** Bug 232519 has been marked as a duplicate of this bug. ***
*** This bug has been marked as a duplicate of bug 232519 *** | https://netbeans.org/bugzilla/show_bug.cgi?id=232709 | CC-MAIN-2017-51 | refinedweb | 471 | 74.39 |
A one pass solution can be done using pointers. Move one pointer fast --> n+1 places forward, to maintain a gap of n between the two pointers and then move both at the same speed. Finally, when the fast pointer reaches the end, the slow pointer will be n+1 places behind - just the right spot for it to be able to skip the next node.
Since the question gives that n is valid, not too many checks have to be put in place. Otherwise, this would be necessary.
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0); ListNode slow = start, fast = start; slow.next = head; //Move fast in front so that the gap between slow and fast becomes n for(int i=1; i<=n+1; i++) { fast = fast.next; } //Move fast to the end, maintaining the gap while(fast != null) { slow = slow.next; fast = fast.next; } //Skip the desired node slow.next = slow.next.next; return start.next; }
Here a new node with value 0 is added in the beginning of the linked list.
initially fast and slow are pointing to start and "slow.next=head" will change the start.next to head (because at this time start,slow and fast all are pointing to the same node in the linked list).
Hope this clears your doubt.
In my opinion, this is not a valid solution.
Supposing the length of this list is l, this solution will visit the previous (l-n) elements twice, which has no difference with first getting the length of this list and in the SECOND pass find the index of the node to delete.
it is impossible to find a solution in one pass unless the length of the list is known upfront.
public ListNode removeNthFromEnd(ListNode head, int n) { // Solve [1] 1 if (head.next == null) { return null; } // Solve [1,2] 1, or [1,2] 2 or [1,2,3] 2, or [1,2,3,4,5] 2 int counter = 1; ListNode start = new ListNode(0); start.next = head; ListNode fast = start; ListNode slow = start; while (fast.next != null) { fast = fast.next; if (counter <= n) { counter++; } else { slow = slow.next; } } slow.next = slow.next.next; return start.next; }
This solution is essentially the same with the original solution in this post, but without the for loop. So now, people can understand that it IS a one pass solution.
Easier to understand
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode newHead = new ListNode(0); newHead.next = head; ListNode p = newHead; ListNode runner = newHead; while(n>0){ runner = runner.next; n--; } while(runner.next!=null){ runner = runner.next; p=p.next; } p.next = p.next.next; return newHead.next; } }
I tried "return head;" but it returned the original linked list. I'm wondering where the "delete" is operating.
If you return head, it will failed some tests. e.g. A list has only one Node and will delete it later.
Yes. The problem is meaningless. The funny thing is your answer is the one which is close to being correct. But it has just one upvote.
Two pointer technique is a good technique which can be used in other places like finding cycle in the list. But this problem is particularly worded to force people to think that two pointer technique can give the answer in one pass.
I have try to implement your idea without using the dummy-head node but failed. I think it is really tricky whether to use the dummy-head node. As we may delete the head node 2333333
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/7031/simple-java-solution-in-one-pass | CC-MAIN-2017-51 | refinedweb | 612 | 84.47 |
Use histogram facets with numerical and date fields to retrieve the number of documents whose field value falls within an interval. For example, in a search of products, use a histogram facet to retrieve the number of products whose price ranges from 0 to 100, 101 to 200, and so on.
Use the HistogramFacetFor method to request histogram facets for numerical and date fields. .
- The first parameter takes an expression which determines the field for which to build the histogram. For example, PublishDate.
- The second parameter requires an interval, either a numerical value or a value of the enum type DateInterval (located in the EPiServer.Find.Api.Facets namespace). This parameter is based on the field defined in the first parameter.
After the search is executed, extract histogram facets from the search results object using the method with the same name, HistogramFacetFor. | https://world.episerver.com/documentation/Items/Developers-Guide/EPiServer-Find/10/DotNET-Client-API/Searching/Facets/Histogram-facets/ | CC-MAIN-2018-22 | refinedweb | 142 | 53.81 |
On 2013-01-30 11:23, Johannes Stezenbach wrote:> On Mon, Jan 28, 2013 at 11:29:14PM -0500, Nicolas Pitre wrote:>> On Mon, 28 Jan 2013, Andrew Morton wrote:>>>>> On Sat, 26 Jan 2013 14:50:43 +0900>>> Kyungsik Lee <kyungsik.lee@lge.com> wrote:>>>>>>> This patchset is for supporting LZ4 compressed kernel and initial ramdisk on>>>> the x86 and ARM architectures.>>>>>>>> According to, LZ4 is a very fast lossless>>>> compression algorithm and also features an extremely fast decoder.>>>>>>>> Kernel Decompression APIs are based on implementation by Yann Collet>>>> ().>>>> De/compression Tools are also provided from the site above.>>>>>>>> The initial test result on ARM(v7) based board shows that the size of kernel>>>> with LZ4 compressed is 8% bigger than LZO compressed but the decompressing>>>> speed is faster(especially under the enabled unaligned memory access).>>>>>>>> Test: 3.4 based kernel built with many modules>>>> Uncompressed kernel size: 13MB>>>> lzo: 6.3MB, 301ms>>>> lz4: 6.8MB, 251ms(167ms, with enabled unaligned memory access)>>>>>> What's this "with enabled unaligned memory access" thing? You mean "if>>> the arch supports CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS"? If so,>>> that's only x86, which isn't really in the target market for this>>> patch, yes?>>>> I'm guessing this is referring to commit 5010192d5a.>>>>> It's a lot of code for a 50ms boot-time improvement. Does anyone have>>> any opinions on whether or not the benefits are worth the cost?>>>> Well, we used to have only one compressed format. Now we have nearly >> half a dozen, with the same worthiness issue between themselves. >> Either we keep it very simple, or we make it very flexible. The former >> would argue in favor of removing some of the existing formats, the later >> would let this new format in.> > This reminded me to check the status of the lzo update and it> seems it got lost?> proposed LZO update currently lives in the linux-next tree.I had tried several times during the last 12 months to provide an updateof the kernel LZO version, but community interest seemed low and Ibasically got no feedback about performance improvements - which madewe wonder if people actually care.At least akpm did approve the LZO update for inclusion into 3.7, but the codestill has not been merged into the main tree. > On 2012-10-09 21:26, Andrew Morton wrote: > [...] > The changes look OK to me. Please ask Stephen to include the tree in > linux-next, for a 3.7 merge.Well, this probably means I have done a rather poor marketing. Anyway, aspeople seem to love *synthetic* benchmarks I'm finally posting some timings(including a brand new ARM unaligned version - this is just a quick hack whichprobably still can get optimized further).Hopefully publishing these numbers will help arousing more interest. :-)Cheers,Markusx86_64 (Sandy Bridge), gcc-4.6 -O3, Silesia test corpus, 256 kB block-size: compression speed decompression speed LZO-2005 : 150 MB/sec 468 MB/sec LZO-2012 : 434 MB/sec 1210 MB/seci386 (Sandy Bridge), gcc-4.6 -O3, Silesia test corpus, 256 kB block-size: compression speed decompression speed LZO-2005 : 143 MB/sec 409 MB/sec LZO-2012 : 372 MB/sec 1121 MB/secarmv7 (Cortex-A9), Linaro gcc-4.6 -O3, Silesia test corpus, 256 kB block-size: compression speed decompression speed LZO-2005 : 27 MB/sec 84 MB/sec LZO-2012 : 44 MB/sec 117 MB/sec LZO-2013-UA : 47 MB/sec 167 MB/secLegend: LZO-2005 : LZO version in current 3.8 rc6 kernel (which is based on the LZO 2.02 release from 2005) LZO-2012 : updated LZO version available in linux-next LZO-2013-UA : updated LZO version available in linux-next plus ARM Unaligned Access patch (attached below)> (Cc: added, I hope Markus still cares and someone could> eventually take his patch once he resends it.)> > Johannes> -- Markus Oberhumer, <markus@oberhumer.com>, 8745b927fcfcd6953ada9bd1220a73083db5948aAuthor: Markus F.X.J. Oberhumer <markus@oberhumer.com>Date: Mon Feb 4 02:26:14 2013 +0100 lib/lzo: huge LZO decompression speedup on ARM by using unaligned access Signed-off-by: Markus F.X.J. Oberhumer <markus@oberhumer.com>diff --git a/lib/lzo/lzo1x_decompress_safe.c b/lib/lzo/lzo1x_decompress_safe.cindex 569985d..e3edc5f 100644--- a/lib/lzo/lzo1x_decompress_safe.c+++ b/lib/lzo/lzo1x_decompress_safe.c@@ -72,9 +72,11 @@ copy_literal_run: COPY8(op, ip); op += 8; ip += 8;+# if !defined(__arm__) COPY8(op, ip); op += 8; ip += 8;+# endif } while (ip < ie); ip = ie; op = oe;@@ -159,9 +161,11 @@ copy_literal_run: COPY8(op, m_pos); op += 8; m_pos += 8;+# if !defined(__arm__) COPY8(op, m_pos); op += 8; m_pos += 8;+# endif } while (op < oe); op = oe; if (HAVE_IP(6)) {diff --git a/lib/lzo/lzodefs.h b/lib/lzo/lzodefs.hindex 5a4beb2..b230601 100644--- a/lib/lzo/lzodefs.h+++ b/lib/lzo/lzodefs.h@@ -12,8 +12,14 @@ */ +#if 1 && defined(__arm__) && ((__LINUX_ARM_ARCH__ >= 6) || defined(__ARM_FEATURE_UNALIGNED))+#define CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS 1+#define COPY4(dst, src) \+ * (u32 *) (void *) (dst) = * (const u32 *) (const void *) (src)+#else #define COPY4(dst, src) \ put_unaligned(get_unaligned((const u32 *)(src)), (u32 *)(dst))+#endif #if defined(__x86_64__) #define COPY8(dst, src) \ put_unaligned(get_unaligned((const u64 *)(src)), (u64 *)(dst)) | http://lkml.org/lkml/2013/2/3/367 | CC-MAIN-2015-32 | refinedweb | 849 | 55.84 |
Recursion is a technique that you should have in your programming arsenal, but that doesn't mean you should always use recursion when writing Python code. Sometimes you should convert the recursion to another programming style or come up with a different algorithm altogether.
Follow me on Twitter, where I write about Python, APL, and maths.
(If you are new here and have no idea what a Pydon't is, you may want to read the Pydon't Manifesto.)
In this Pydon't I am going to talk a little bit about when and why recursion might not be the best strategy to solve a problem. This discussion will entail some particularities of Python, but will also cover broader topics and concepts that encompass many programming languages. After this brief discussion, I will show you some examples of recursive Python code and its non-recursive counterparts.
Despite what I said I'll do, don't take me wrong: the purpose of this Pydon't is not to make you dislike recursion or to say that recursion sucks. I really like recursion and I find it very elegant.
Now that you know what is the purpose of this Pydon't, let me mention some things that can influence the suitability of recursion to solve problems.
RecursionError
The first thing we will discuss is the infamous recursion depth limit that Python enforces.
If you have no idea what I am talking about, then either
The recursion depth limit is something that makes your code raise a
RecursionError if you make too many recursive calls.
To see what I am talking about, just do the following in your REPL:
>>> def f(): ... return f() ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f File "<stdin>", line 2, in f File "<stdin>", line 2, in f [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded >>>
In many cases, this limit helps, because it helps you find recursive functions for which you did not define the base case properly.
There are, however, cases in which \(1000\) recursive calls isn't enough to finish your computations. A classical example is that of the factorial function:
>>> def fact(n): ... if n == 0: ... return 1 ... return n*fact(n-1) ... >>> fact(10) 3628800 >>> fact(2000) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in fact File "<stdin>", line 5, in fact File "<stdin>", line 5, in fact [Previous line repeated 995 more times] File "<stdin>", line 2, in fact RecursionError: maximum recursion depth exceeded in comparison
Our function is properly defined but by default Python does not allow us to make sufficient recursive calls.
If you must, you can always set your own recursion depth:
>>> import sys >>> sys.setrecursionlimit(3000) >>> fact(2000) 33162... # (omitted for brevity) >>> sys.getrecursionlimit() 3000
Just be careful with it. I never tried, but you are likely not to be interested in having Python run out of memory because of your obscenely large amount of recursive calls.
Hence, if your function is such that it will be constantly trying to recurse more than the recursion depth allowed, you might want to consider a different solution to your problem.
In some programming languages, the factorial function shown above could be tweaked -- so as to perform a tail call -- and that would prevent some problems while saving memory: tail calls happen when the recursive call is the very last thing that is done inside the function, which more or less means that you do not need to keep any information whatsoever about the context you are in when you recurse.
In the factorial function above, after recursing with
fact(n-1)
we still have to perform a multiplication before returning from the function.
If we rewrote the function to carry the partial factorial as an accumulator,
we could have a factorial function that performs tail calls:
>>> def fact(n, partial=1): ... if n <= 1: ... return partial ... return fact(n-1, n*partial) ... >>> fact(10) 3628800
As you can see, the very last thing done inside the
fact function is
to call itself, so in theory Python could “forget everything about its
surroundings” when making the recursive call, and save a lot of memory
in the process.
In practice, Python does not do this intentionally, and I refer you to the two articles on the Neopythonic blog (by Guido van Rossum) in the references to read more on why Python does not have such a feature.
Converting recursive functions into tail recursive functions is an interesting exercise and I challenge you to do so, but you won't get speed gains for it. However, it is very easy to remove the recursion of a tail recursive function, and I will show you how to do it in the examples below.
Another thing to take into account when considering a recursive solution to a problem is: is there going to be much overlap in the recursive calls?
If your recursive function branches in its recursive calls and the recursive calls overlap, then you may be wasting plenty of time recalculating the same values over and over again. More often than not this can be fixed easily, but just because a problem probably has a simple solution, it doesn't mean you can outright ignore it.
A classical example of recursion that leads to plenty of wasted computations is the Fibonacci sequence example:
def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2)
A simple modification to this function shows that there are many recursive calls being made:
call_count = 0 def fibonacci(n): global call_count call_count += 1 if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10)) print(call_count) # 177
If your function is more involved, then the time you waste on recalculations can become unbearable.
Something else to take into consideration when writing recursive solutions to your problems is that recursive solutions are inherently depth-first in nature, whereas your problem might warrant a breadth-first solution.
This is unlikely to be a large concern, but it just goes to show that sometimes, even though a solution has a very clear recursive solution, you are better off with not implementing a purely-recursive solution.
A very good example of this distinction popped up when I solved the water
bucket riddle: I wanted to write code that solved
(a more generic version of)
that riddle
where you have a bucket that can hold
A litres, another one that holds
B litres,
and you have to move water around to get one of the buckets to hold exactly
T litres.
The solution can be easily expressed in recursive terms, but my implementation
actually used a
while loop and a BFS algorithm.
If you don't know what this means, the best thing to do is to google it. For example, visit the Wikipedia pages on Depth-first Search and Breadth-first Search. In a short and imprecise sentence, Depth-First Search (DFS) means that when you are traversing some structure, you prioritise exploring in depth, and only then you look around, whereas in Breadth-First Search (BFS) you first explore the level you are at, and only then go a level deeper.
I will now show some recursive code that can incur in some of the problems mentioned above, and will also share non-recursive versions of those same pieces of code.
The toy example of the factorial is great because it lends itself to countless different implementations, and the ideas that these implementations exhibit can then be adapted to more complex recursions.
The main characteristic here is that the recursion of the factorial is a “linear” recursion, where each call only performs a single recursive call, and each recursive call is for a simpler problem.
The vanilla recursion follows:
def factorial(n): if n <= 1: return 1 return n * factorial(n-1)
Like we have seen above, we could use an accumulator to write a tail recursive version of the factorial, even thought Python won't optimise that in any way:
def factorial(n, partial=1): if n <= 1: return partial return factorial(n-1, n*partial)
Now that we have this function written in a tail recursive way, we can actually remove the recursion altogether following a simple recipe:
def factorial(n): partial = 1 while n > 1: n, partial = n-1, n*partial return partial
This is a generic transformation you can do for any tail recursive function and I'll present more examples below.
Still on the factorial, because this is a linear recursion
(and a fairly simple one, yes),
there are many ways in which this function can be rewritten.
I present a couple, pretending for a second that
math.factorial doesn't exist:
import math def factorial(n): return math.prod(i for i in range(1, n+1)) import functools, operator def factorial(n): return functools.reduce(operator.mul, [i for i in range(1, n+1)]) def factorial(n): fact = 1 for i in range(1, n+1): fact *= i return fact
If you are solving a problem and come up with different solutions, don't be afraid to try them out.
Let me show you a couple of simple recursive functions, their tail recursive equivalents and then their non-recursive counterparts. I will show you the generic transformation, so that you too can rewrite any tail recursive function as an imperative one with ease.
You can implement your own
sum recursively:
def sum(l): if not l: return 0 return l[0] + sum(l[1:])
If you carry a partial sum down the recursive calls, you can make this tail recursive:
def sum(l, partial=0): if not l: return partial return sum(l[1:], l[0] + partial)
From the tail recursive function to the
while solution is simple:
def sum(l): partial = 0 while l: l, partial = l[1:], l[0] + partial return partial
Notice what happened:
whileloop whose condition is the complement of the base case condition;
whileyou return the auxiliary variable.
Of course there are simpler implementations for the
sum, the point here is that
this transformation is generic and always works.
Here is another example where we sort a list with selection sort. First, “regular” recursion:
def selection_sort(l): if not l: return [] m = min(l) idx = l.index(m) return [m] + selection_sort(l[:idx]+l[idx+1:])
Now a tail recursive version:
def selection_sort(l, partial=None): # partial=[] is bad! if partial is None: partial = [] if not l: return partial m = min(l) idx = l.index(m) selection_sort(l[:idx]+l[idx+1:], partial + [m])
In the above we just have to be careful with something:
the default value of
partial is supposed to be the empty list, but you should
avoid mutable types in your arguments' default values,
so we go with
None and then
the very first thing we do is set
partial = [] in case it was
None.
Finally, applying the recipe, we can remove the recursion:
def selection_sort(l): partial = [] while l: m = min(l) idx = l.index(m) l, partial = l[:idx]+l[idx+1:], partial + [m] return partial
The Depth-first versus Breadth-first distinction is more likely to pop up when you have to traverse something.
In this example, we will traverse a full directory, printing file names and file sizes. A simple, purely recursive solution follows:
import pathlib def print_file_sizes(path): """Print file sizes in a directory.""" path_obj = pathlib.Path(path) if path_obj.is_file(): print(path, path_obj.stat().st_size) else: for path in path_obj.glob("*"): print_file_sizes(path)
If you apply that function to a directory tree like this one,
- file1.txt - subdir1 | - file2.txt | - subdir2 | - file3.txt | - subdir3 | - deep_file.txt
then the first file you will see printed is
deep_file.txt, because this recursive
solution traverses your file-system depth first.
If you wanted to traverse the directory breadth-first, so that you first found
file1.txt, then
file2.txt, then
file3.txt, and finally
deep_file.txt, you
could rewrite your function to look like the example that I took from my “Truthy, Falsy, and bool” Pydon't
uses the
paths_to_process list to keep track of the, well, paths that still
have to be processed, which mimics recursion without actually having to recurse.
When your recursive function branches out a lot, and those branches overlap, you can save some computational effort by saving the values you computed so far. This can be as simple as having a dictionary inside which you check for known values and where you insert the base cases.
This technique is often called memoisation and will be covered in depth in a later Pydon't, so stay tuned!
call_count = 0 fibonacci_values = {0: 0, 1: 1} def fibonacci(n): global call_count call_count += 1 try: return fibonacci_values[n] except KeyError: fib = fibonacci(n-1) + fibonacci(n-2) fibonacci_values[n] = fib return fib print(fibonacci(10)) print(call_count) # 19
Notice that this reduced the recursive calls from 177 to 19. We can even count the number of times we have to perform calculations:
computation_count = 0 fibonacci_values = {0: 0, 1: 1} def fibonacci(n): try: return fibonacci_values[n] except KeyError: global computation_count computation_count += 1 fib = fibonacci(n-1) + fibonacci(n-2) fibonacci_values[n] = fib return fib print(fibonacci(10)) print(computation_count) # 9
This shows that saving partial results can really pay off!
To show you how you can rewrite a recursive, branching function as a function
that uses
while loops we will take a look at another sorting algorithm,
called merge sort.
The way merge sort works is simple: to sort a list, you start by sorting the
first and last halves separately, and then you merge the two sorted halves.
Written recursively, this might look something like this:
def merge(l1, l2): recursively with the merge sort algorithm.""" # Base case. if len(l) <= 1: return l # Sort first and last halves. m = len(l)//2 l1, l2 = merge_sort(l[:m]), merge_sort(l[m:]) # Now put them together. return merge(l1, l2)
If you don't want to have all this recursive branching, you can use a generic list to keep track of all the sublists that are still to be sorted:
def merge(l1, l2): """Merge two lists in order.""" with the merge sort algorithm.""" # Save all sorted sublists. already_sorted = [] # Keep track of sublists that need sorting: to_sort = [l] while to_sort: # Pick a list to be sorted. lst, *to_sort = to_sort # Base case. if len(lst) <= 1: already_sorted.append(lst) else: # Split in halves to sort each half. m = len(lst) // 2 to_sort.append(lst[:m]) to_sort.append(lst[m:]) # Merge all the sublists. while len(already_sorted) > 1: l1, l2, *already_sorted = already_sorted # Factored out the `merge` to keep this short. already_sorted.append(merge(l1, l2)) return already_sorted[0]
If you don't really know what the
h, *l1 = l1,
h, *l2 = l2,
lst, *to_sort = to_sort and
l1, l2, *already_sorted = already_sorted lines
are doing, you might want to have a look at
this Pydon't about unpacking with starred assignments.
In this particular example, my translation of the merge sort to a non-recursive solution ended up being noticeably larger than the recursive one. This just goes to show that you need to judge all situations by yourself: would this be worth it? Is there an imperative implementation that is better than this direct translation? The answers to these questions will always depend on the programmer and the context they are in.
This also shows that the way you think about the problem has an effect on the way the code looks: even though this last implementation is imperative, it is a direct translation of a recursive implementation and so it may not look as good as it could!
Here's the main takeaway of this article, for you, on a silver platter:
“Pydon't recurse mindlessly.”
This Pydon't showed you that:
RecursionErrorif you cross that limit; 16. | https://mathspp.com/blog/pydonts/watch-out-for-recursion | CC-MAIN-2021-39 | refinedweb | 2,665 | 56.79 |
Rygel, a home media solution (UPnP AV MediaServer) that allows users to easily share audio, video, and pictures to other devices, is now at version 0.17.5.1.
With Rygel, users will be able to browse the media collection from the TV or PS3 on a PC running GNOME, and they will have the possibility to play any of said media.
Highlights of Rygel 0.17.5.1:
• "content-synchronization" DLNA capability is now announced, if it's available;
• Some public classes have been moved to GObject-style construction;
• An internal plug-in in librygel-renderer;
• Renderer-side PlaySpeed support has been added;
• A fullscreen renderer has been added.
Check out the official changelog for a complete list of updates and new features.
Download Rygel 0.17.5.1 right now from Softpedia. Remember that this is a development version and it should NOT be installed on production machines. It is intended for testing purposes only. | http://linux.softpedia.com/blog/Rygel-0-17-5-1-MediaServer-Improves-DLNA-Capability-315432.shtml | CC-MAIN-2015-22 | refinedweb | 157 | 55.44 |
C Programming Structure and Function
In C, structure can be passed to functions by two methods:
- Passing by value (passing actual value as argument)
- Passing by reference (passing address of an argument)
Passing structure by value
A structure variable can be passed to the function as an argument as normal variable. If structure is passed by value, change made in structure variable in function definition does not reflect in original structure variable in calling function.
Write a C program to create a structure student, containing name and roll. Ask user the name and roll of a student in main function. Pass this structure to a function and display the information in that function.
#include <stdio.h> struct student{ char name[50]; int roll; }; void Display(struct student stu); /* function prototype should be below to the structure declaration otherwise compiler shows error */ int main(){ struct student s1; printf("Enter student's name: "); scanf("%s",&s1.name); printf("Enter roll number:"); scanf("%d",&s1.roll); Display(s1); // passing structure variable s1 address location of structure variable is passed to function while passing it by reference. If structure is passed by reference, change made in structure variable in function definition reflects in original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user. To solve this program, make a structure. Pass two structure variable (containing distance in feet and inch) to add function by reference and display the result in main function without returning it.
"
Explaination
In this program, structure variables dist1 and dist2 are passed by value (because value of dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by reference ,i.e, address of dist3
(&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3 variable in main function. | http://www.programiz.com/c-programming/c-structure-function | CC-MAIN-2016-07 | refinedweb | 328 | 51.68 |
sys/time.h - time types
#include <sys/time.h>
The <sys/time.h> header defines the timeval structure that includes at least the following members:
time_t tv_sec seconds suseconds_t tv_usec microseconds
The <sys/time.h> header defines the itimerval structure that includes at least the following members:
struct timeval it_interval timer interval struct timeval it_value current value
The time_t and suseconds_t types are defined as described in <sys/types.h>.
The <sys/time.h> header defines the fd_set type as a structure that includes at least the following member:
long fds_bits[] bit mask for open file descriptions
The <sys/time.h> header definesises the file descriptor set fdset to have zero bits for all file descriptors.
- FD_SETSIZE
- Maximum number of file descriptors in an fd_set structure.
If implemented as macros, these may evaluate their arguments more than once, so that arguments must never be expressions with side effects.
The following are declared as functions and may also be defined as macros. Function prototypes must be provided for use with an ISO C compiler.
int getitimer(int, struct itimerval *); int setitimer(int, const struct itimerval *, struct itimerval *); int gettimeofday(struct timeval *, void *); int select(int, fd_set *, fd_set *, fd_set *, struct timeval *); int utimes(const char *, const struct timeval [2]);
None.
None.
getitimer(), gettimeofday(), select(), setitimer(), utimes(). | http://www.opengroup.org/onlinepubs/007908799/xsh/systime.h.html | crawl-001 | refinedweb | 214 | 63.39 |
Uploading from camera library via xmlrpclib
I couldn't find anything else in the forums, but I'm trying to upload an image to a Wordpress site via xmlrpclib. I was able to do it with an image hosted online using this code:
def new_image(url, post_id = None): import urllib2 from re import findall raw = urllib2.urlopen(url) image = raw.read() content = {} content['bits'] = xmlrpclib.Binary(image) content['name'] = findall('[^\/]+?$',url)[0] content['type'] = 'image/jpeg' if post_id is not None: content['post_id'] = post_id img = server.wp.uploadFile(1,username,password,content) return img
(server, username and password are defined earlier)
I'm trying to do the same thing with an image chosen from my camera roll (I go through my company's Instagram feed and upload it for a weekly blog post, but sometimes I have a 4:3 version I want to use instead). To get
content['bits']I'm using:
import photos image = photos.pick_image(False, True, False) image[0].verify() content = {} content['bits'] = xmlrpclib.Binary(image[0].tostring())
This... works, in that an object is returned, but the image doesn't actually upload. See this example.
File and I/O stuff are what I hate most about coding, and I don't really understand all the components, so maybe (hopefully) there's something easy I'm missing.
See
Image.tostring()
Image.tostring(encoder, parameters)
Returns a string containing pixel data, using the given data encoding.
Note: The tostring method only fetches the raw pixel data. To save the image to a string in a standard file format, pass a StringIO object (or equivalent) to the save method.
tostringis not returning the binary of an encoded image file, but more like the binary underlying the PIL image format. Use save instead with a StringIO object, then use getValue to get the binary.
See for the basic approach, except you won't then convert to a ui.Image.
Thank you! But now I'm having trouble with
.save():
with io.BytesIO() as bIO: image[0].save(bIO,'JPG') content['bits'] = bIO.getvalue()
The second line gives
KeyError: 'JPG'. So I thought it might be interpreting that as an option and not format I added
{'quality': 80}and got
TypeError: save() takes at most 3 arguments (4 given)
So... It thinks there's an extra argument? To make sure
image[0]was correct I did
.show()and it worked...
Use 'jpeg ', not 'jpg'.
Actually, if you don't need to manipulate it at all, use the
raw_data=Trueargument to
pick_image, which returns the raw binary without having to use save, etc.
Wonderful, thank you!
Using JPEG still didn't work, so I went the raw_data route, and it works perfectly. For posterity:
content = {} image = photos.pick_image(False, True, True ,True ) content['bits'] = xmlrpclib.Binary(image[0]) | https://forum.omz-software.com/topic/1692/uploading-from-camera-library-via-xmlrpclib | CC-MAIN-2018-13 | refinedweb | 467 | 59.6 |
OOP vs type classes
From HaskellWiki
Latest revision as of 12:57, 1 June 2012
:)
[edit] 1 Everything is an object?. It's extremely useful to browse the structure of large C++ project in terms of classes instead of individual functions.
Haskell provides other solutions for these problems.
[edit])
The equivalent C++ implementation using inheritance requires much more machinery than our 5 line, ADT-based solution. This also illustrates a Haskell benefit--it's much easier to define types/functions. Perhaps objects are not as great as you thought before. :D
.
[edit] IO inside#Example: returning an IO action as a result and following sections to find more examples of using closures instead of OOP classes.
[edit].
[edit]
Dividing a whole program into classes and using their hierarchy to represent entire an program structure is a great instrument for OO languages. Unfortunately, it's again impossible in Haskell. Instead, the structure of a program is typically rendered in a module hierarchy and inside a module - in its export list. Although Haskell doesn't provide facilities to describe a hierarchical structure inside of a module, we have.
[edit] 2 Type classes is a sort of templates, not classes
At this moment, C++ has classes and templates. What is the difference? With a class, type information is carried with the object itself while with templates it's outside of the object and is part of the whole operation.
For example, if the == operation is defined as a virtual method in a class, the actual procedure called for a==b may depend on the run-time type of 'a', but if the operation is defined in template, the actual procedure depends only on the instantiated template (which is determined at compile time).
Haskell's objects don't carry run-time type information. Instead, the class constraint for a polymorphic operation is passed in the implementation of "==" and "/=" operations for objects of type 'a'. If there are several class constraints, a dictionary for each is passed.
If the class has base class(es), the dictionary tuple includes the base class dictionaries, so
class Eq a => Cmp a where cmp :: a -> a -> Ordering cmpList :: (Cmp a) => [a] -> [a] -> Ordering
turns into:
type CmpDictionary a = (EqDictionary a, a -> a -> Ordering) cmpList :: CmpDictionary a -> [a] -> [a] -> Ordering
Compared to C++, this is more like templates, not classes! As with templates, type information is part of operation, not the object! But while C++ templates are really a form of macro-processing (like Template Haskell) and at last end generate non-polymorphic code, Haskell's use of dictionaries allows run-time polymorphism (explanation of run-time polymorphism? -what is this? a form of dynamic dispatch?).
Moreover, Haskell type classes support inheritance. Run-time polymorphism together with inheritance are often seen as OOP distinctive points, so during long time I considered type classes as a form of OOP implementation. But that's wrong! Haskell type classes build on a different basis, so they are like C++ templates with added inheritance and run-time polymorphism! And this means that the usage of type classes is different from using classes, with its own strong and weak points.
[edit] 3 Type classes vs classes
Here is a brief listing of differences between OOP classes and Haskell type classes
[edit].
[edit] 3))
[edit] 3 a function that requires base class from a function that requires subclass:
f :: (Stream m s) => s -> m String show :: (Show s) => s -> String f s = return (show s)
But downcasting is absolutely impossible - there is no way to get subclass dictionary from a superclass one
[edit] 3
[edit] 3.5 Downcasting is a mission impossible
Selection between instances is done at compile-time, based only on information present at.
- Remark: This isn't even a legal program unless you use thelanguage extension. The error message:IncoherentInstances
Overlapping instances for Foo a arising from a use of `foo' at /tmp/I.hs:17:4-6 Matching instances: instance [overlap ok] (Num a) => Foo a -- Defined at /tmp/I.hs:10:9-24 instance [overlap ok] Foo Int -- Defined at /tmp/I.hs:13:9-15 (The choice depends on the instantiation of `a' To pick the first instance above, use -XIncoherentInstances when compiling the other instance declarations)
- Details: GHC User's Guide
[edit] 3!
[edit] 3' neither 'b' dictionary. Even if orderings for apples and penguins are defined, we still don't have a method to compare penguins to apples!
[edit] 4 Other opinions
[edit]
>!)
[edit]".
[edit] 5 Haskell emulation of OOP inheritance with record extension
Brian Hulley provided us the code that shows how OOP inheritance can be emulated in Haskell. His translation method supports data fields inheritance, although don't supports downcasting.
> although i mentioned not only pluses but also drawbacks of type > classes: lack of record extension mechanisms (such at that implemented > in O'Haskell) and therefore inability to reuse operation > implementation in an derived data type...
You can reuse ops in a derived data type but it involves a tremendous amount of boilerplate.)
[edit] 6 Type class system extensions
Brief list of extensions, their abbrevi)
[edit] | http://www.haskell.org/haskellwiki/index.php?title=OOP_vs_type_classes&diff=45857&oldid=28236 | CC-MAIN-2014-23 | refinedweb | 850 | 52.9 |
This post will show how to take advantages of The Tactigon’s BLE Central capabilities. We wanted to control our robot by using The Tactigon as a “3D steering wheel” controlling speed with pitch and steering with roll. We made so few changes in the Alphabot2 original Bluetooth example code and wrote a sketch for The Tactigon to connect to the robot’s BLE characteristic and write in wheels speeds.
What We Need
- The Tactigon with a configured Arduino IDE
- Robot. We used a 2 wheels robot with Arduino board and BLE radio interfaced with UART. Other kind of robots or custom ones can work as well.
- Robot BLE MAC Address and Characteristic
- Fun
Gathering BLE MAC Address and characteristic
After our environment is configured and our boards are ON, we need to gather BLE MAC Address and Characteristic. To do so we used a free android application called BLE Scanner.
Few seconds after the application should show the robot’s BLE:
As we see, all BLE devices around us are showed in this section. We need to write down the Waveshare_BLE MAC address: in this instance it is: 00:0E:0B:0C:4A:00
By clicking on the CONNECT button we access to device’s informations as attribute, service and custom characteristic.
Here we need to write down the CUSTOM CHARACTERISTIC UUID, in this case: 0000ffe1-0000-1000-8000-00805f9b34fb .
With this items we can set our Tactigon BLE to act as BLE Central in the setup() section of the code.
The Tactigon Sketch
Loop
In this section we have the core of the sketch. At a frequency of 50Hz, we update quaternions and euler angles.
Analizyng pitch angle provided by Tactigon library, we can determine steering radius by slowing internal wheel and accelerating external wheel.
Analizying roll, instead, we can determine travel speed of the robot.
With a sprintf we prepare the buffer to write in the characteristic.
Robot Sketch
Since our Bluetooth sends received data over UART, we get wheels speed directly in the serial buffer.
We have set robot pins as follows, all as output:
To parse the command we first read all the serial buffer and verify if it is longer than 0:
If the command contains “Wh” we can so parse the string and gather leftSpeed and rightSpeed.
The direct_motor function assign the speed transmitted by The Tactigon to each wheel of the robot. By doing so The Tactigon will act as a virtual-steering wheel!
Final Considerations
This sketch shows a potential application of The Tactigon, with the BLE Central mode is possible to connect to existing BLE devices and gather informations or control them.
Stay tuned for more Tactigon’s code!
Alphabot2 Code
The Tactigon Code
#include <tactigon_led.h> #include <tactigon_IMU.h> #include <tactigon_BLE.h> extern int ButtonPressed; T_Led rLed, bLed, gLed; T_QUAT qMeter; T_QData qData; T_BLE bleManager; UUID targetUUID; uint8_t targetMAC[6] = {0x00,0x0e,0x0b,0x0c,0x4a,0x00}; T_BLE_Characteristic accChar, gyroChar, magChar, qChar; int ticks, ticksLed, stp, cnt, printCnt; float roll, pitch, yaw; void setup() { // put your setup code here, to run once: ticks = 0; ticksLed = 0; stp = 0; cnt = 0; //init leds rLed.init(T_Led::RED); gLed.init(T_Led::GREEN); bLed.init(T_Led::BLUE); rLed.off(); gLed.off(); bLed.off(); //init BLE bleManager.setName("Tactigon"); bleManager.InitRole(TACTIGON_BLE_CENTRAL); //role: CENTRAL targetUUID.set("0000ffe1-0000-1000-8000-00805f9b34fb"); //target characteristic bleManager.setTarget(targetMAC, targetUUID); //target: mac device and its char UUID } void loop() { char buffData[24]; int deltaWheel, speedWheel; int pitchThreshold, rollThreshold, th1, th2; //update BLE characteristics @ 50Hz (20msec) if(GetCurrentMilli() >= (ticks +(1000 / 50))) { ticks = GetCurrentMilli(); //get quaternions and Euler angles qData = qMeter.getQs(); //Euler angles: rad/sec --> degrees/sec roll = qData.roll * 360/6.28; pitch = qData.pitch * 360/6.28; yaw = qData.yaw * 360/6.28; //build command to rover depending on Euler angles //left/right pitchThreshold = 15; if(pitch < -pitchThreshold || pitch > pitchThreshold) { if(pitch<-pitchThreshold) { deltaWheel =- (fabs(pitch) - pitchThreshold)*3; } else { deltaWheel =+ (fabs(pitch) - pitchThreshold)*3; } } else { deltaWheel=0; } //forward/backword rollThreshold = 15; th1 = 90 + rollThreshold; th2 = 90 - rollThreshold; roll = fabs(roll); if(roll > th1) { speedWheel = (roll - th1) * 3; } else if(roll < th2) { speedWheel = (roll - th2) * 3; } else { speedWheel = 0; } //command in buffData sprintf(buffData,"Wh(%d)(%d)", speedWheel-(-deltaWheel/2), speedWheel+(-deltaWheel/2)); //if connected and attached to peripheral characteristic write in it if(bleManager.getStatus() == 3) { //signal that connection is on bLed.on(); //send command every 100msec rLed.off(); cnt++; if(cnt > 5) { cnt = 0; bleManager.writeToPeripheral((unsigned char *)buffData, strlen(buffData)); rLed.on(); } } //say hello on serial monitor every second and blink green led printCnt++; rLed.off(); if(printCnt > 50) { //Serial.println("Hello!"); //Serial.println(roll); printCnt = 0; rLed.on(); } } } | https://maker.pro/arduino/projects/arduino-powered-robot-controlled-with-the-tactigon | CC-MAIN-2018-39 | refinedweb | 775 | 55.13 |
Your message dated Fri, 23 May 2008 17:52:45 +0100 with message-id <200805231652.m4NGqju4012521@kmos.homeip.net> and subject line ecos has been removed from Debian, closing #301862 has caused the Debian Bug report #301862, regarding ecosconfig: configtool is too generic of a name; use ecos-configtool or similar,.) -- 301862: Debian Bug Tracking System Contact owner@bugs.debian.org with problems
--- Begin Message ---
- To: Debian Bug Tracking System <submit@bugs.debian.org>
- Subject: ecosconfig: configtool is too generic of a name; use ecos-configtool or similar, please
- From: "Wesley J. Landaker" <wjl@icecavern.net>
- Date: Mon, 28 Mar 2005 13:28:17 -0700
- Message-id: <20050328202817.EFB3889A4@tonberry.icecavern.net>Package: ecosconfig Version: 2.0-0pre2.1 Severity: minor The ecosconfig package includes a GUI called "configtool". This is way too generic of a name! Please rename this to ecos-configtool, ecosconfig-gui or something similar. Not only does being generically named clutter up the global namespace unreasonably, as well as cause a lot of confusion for users, but it also makes this eCos GUI configuration tool harder to find (e.g. ls /usr/bin/ecos*, or $ ecos<tab> at the shell; I noticed it when I finally said, "where is the GUI config tool?" and did dpkg -L ecosconfig). -- System Information: Debian Release: 3.1 Architecture: amd64 (x86_64) Kernel: Linux 2.6.11.6 Locale: LANG=en_US.UTF-8, LC_CTYPE=en_US.UTF-8 (charmap=UTF-8) Versions of packages ecosconfig depends on: ii libc6 2.3.2.ds1-20.0.0.1.pure64 GNU C Library: Shared libraries an ii libgcc1 1:3.4.3-12 GCC support library ii libstdc++5 1:3.3.5-12 The GNU Standard C++ Library v3 ii libwxgtk2.4 2.4.2.6 wxWindows Cross-platform C++ GUI t ii tcl8.3 8.3.5-4 Tcl (the Tool Command Language) v8 -- no debconf information
--- End Message ---
--- Begin Message ---
- To: 301862-done@bugs.debian.org
- Subject: ecos has been removed from Debian, closing #301862
- From: Marco Rodrigues <gothicx@sapo.pt>
- Date: Fri, 23 May 2008 17:52:45 +0100
- Message-id: <200805231652.m4NGqju4012521@kmos.homeip.net>Version: 2.0-0pre3+rm The ecos --- | https://lists.debian.org/debian-qa-packages/2008/05/msg00286.html | CC-MAIN-2018-26 | refinedweb | 363 | 60.31 |
The Modern JavaScript Tutorial Series; Part 1
Author's note:
This tutorial series should explain everything that I have learned in my time using JavaScript.
I've known the language for less than a whole year.
Part one was written in less than 12 hours, and may contain plenty of intricate text, or may otherwise need to be fixed; please leave a comment on what sections should be improved or elaborated upon.
Lastly, part one is already incredibly long, despite having been written in such a short period of time and containing so little content, any suggestions as to what should be moved out of part 1 would be appreciated.
Please upvote to encourage the release of the next parts!
The Modern JavaScript Tutorial
Part 1: background & basics
This tutorial series should thoroughly explain the following:
- What JavaScript is
- What you can do with JavaScript
- How you should actually structure/write your code
- JavaScript best practice
- How JavaScript is executed
- Tips on programming/scripting in general, that apply to almost any language and/or situation
Why am I making this tutorial series?
There are well over a thousand tutorials that attempt to teach JavaScript, so why waste my time doing it myself?
This is intended to teach modern JavaScript, not how they did it 15 years ago, not how they will use it 15 years in the future, but how it should be written today, in the modern-day and age.
If you want to learn how to write ancient code, just search up "JavaScript tutorial" on any browser. They're all outdated, after discussing this with someone, I realized that the only way to break the chain was to do myself, leading us here.
I will not explain everything, because there is a whole lot of stuff that should've never been known in the first place, or even added.
Now, let's get back to what we all came here for: JavaScript.
What is JavaScript?
Developed in 1995, JavaScript is a simple weakly and dynamically typed, multi-paradigm scripting language.
JavaScript is an imperative language, meaning that authors define both, how something is done, and what is done. This is in contrast to declarative programming, where one simply gives instructions on what must be done, leaving room for how that goal should be reached.
A massive amount of JavaScript control flow revolves around an event loop, meaning that JavaScript is an event-driven language.
While running on a single thread, an implementation's event loop should buffer events to which JavaScript may choose to respond to.
This execution is concurrent, but not parallel. Parallel execution requires threading.
By default, JavaScript often runs on a single thread, but modern JavaScript is not limited to only using that thread.
What makes the language so unique is that JavaScript, and JavaScript alone, has for the longest time, been the only language that allows developers to dynamically manipulate stuff on the web.
No other language is allowed to fire HTTP requests from within a browser, besides the browser's native code.
No webpage can create interaction between a user.
This has essentially forced developers for years to learn JavaScript.
This has finally changed, as another language is on the web nowadays, and it's gaining popularity, but we're here to focus on JavaScript. I'll create a post for that language another time.
Finally, browsers are supposed to be able to execute JavaScript that was written 15 years ago and today's code. This means that you can write a page today, and it'll still work years from now.
This is both, one of its greatest strengths... and its greatest downfall.
Because backward-incompatible changes essentially can't be made, JavaScript has accumulated a large amount of less than desirable features.
Miscellaneous:
- JavaScript is abbreviated "JS"
- The file extension for JavaScript since 2015 has been ".mjs" (the older one was .js)
Who makes JavaScript?
JavaScript was originally written by Brendan Eich, a technologist who had co-founded Mozilla and is currently CEO of Brave Software.
But JavaScript isn't maintained by a single man.
All JavaScript implementations are strongly encouraged to conform to the ECMAScript specification (ES262). The ECMAScript committee is the group responsible for developing the core language.
Implementations that don't conform to the specification are considered to simply not support JavaScript properly.
(That link above points to the actual ES262 specification. It's massive, over a few MB, and it reaches over 20k lines of HTML alone, as of this writing; opening it may be slow)
Usually, the terms ECMAScript and JavaScript are interchangeable, but JavaScript is far more prevalent.
The syntax + language
How can you learn a language, without seeing the actual code‽
Here's a "hello world" script, written in JavaScript:
console.log("Hello, world!");
One line. Simple.
What does this show you, right off the bat?
JavaScript is a C-family language, it takes inspiration from C, Java, and other C-family languages.
Notice the dot in between the words
console and
log, this is a property lookup, on an object. JavaScript is an object-orientated language.
Notice that there is nothing else, no importing the
console object, no
main function where the control flow starts, it's just top to bottom, and some stuff is already defined by the runtime.
Thus, we can infer that JavaScript is, by default, unstructured. It was originally intended for amateurs who know little about computer science. This is especially problematic, considering how many developers are only given two options: JavaScript or nothing.
JavaScript is intended as a simple language to understand. A beginner does not need an understanding of formal computer science, nor do they need an understanding of the low-level details about hardware in order to grasp JavaScript. The language is generally considered to be easier to learn than some other popular languages, such as Java, C#, C++, Ruby, PHP, Go, R, Swift, although, it may be harder to learn than some languages, such as Python, or some command line shell languages.
Because JavaScript is dynamic, weakly typed, and so unstructured, generally, it becomes exponentially harder to maintain any large scale project that is written in the language. It can happen, it's just unnecessarily hard and unmaintainable, or it's incredibly poor in performance.
If you write 50 lines of terse, simple code, it's not that bad.
But, since many users actually are amateurs, trying to debug even a relatively small project that reaches even 400 lines can become difficult.
These problems have caused a whole plethora of languages and pseudo-languages to be created that transpile to JavaScript.
Some of the languages, take TypeScript for example, simple build upon JavaScript, attempting to make it more structured and sensical.
Others, for example, Dart, are whole languages, with their own runtime semantics and structure, that just happen to also have language-level support for transpilation to JavaScript.
In reality, these languages aren't just transpiling to JavaScript, they are misusing JavaScript as if it were a compilation target.
Datatypes
This part gets interesting, considering how JavaScript is a weakly and dynamically typed language.
JavaScript has types, and variables can be reassigned with a new value of a different type.
But just because a variable can be reassigned with a different type doesn't mean that you should change the type.
There are plenty of types that can be represented in JavaScript.
There is a major division that needs to be made: objects and primitives.
Datatypes: Primitives
Primitives are simply raw values. They generally don't have properties, as those are unique to objects, and they are immutable.
Here's an incomplete list of JavaScript primitives and their subtypes:
- Numbers
- Floating-point numbers
- 32-bit float
- 64-bit float
- NaN (Not A Number)
- Infinity
(There is a separate
NaNand
Infinityfor both, 32 bits, and 64 bits, but you'll never be able to distinguish between them)
- Integers
- 8-bit (Signed and unsigned)
- 16-bit (Signed and unsigned)
- 32-bit (Signed and unsigned)
- BigInts (arbitrarily long integers)
- 64-bit (Signed and unsigned)
- Strings
- Template strings
- Booleans
- Undefined
- Symbols
Records Tuples
Numbers are generally merged into one category, as there is little to distinguish between the sizes and types of numbers.
For example, performing division between two integers may result in a floating-point result. Using
5 and
2 as an example:
5 / 2 = 2.5.
There are operations to truncate or floor a floating-point number, removing the decimal place, resulting in an integer.
Once one has exceeded the "safe" precision capacity of a number, precision is lost, results are heavily rounded, and arithmetic becomes lossy.
Generally, the only real distinctions that need to be made are whether the value is a number or what is known as a BigInt.
BigInts are integers that are designed for maintaining precision when working with massive values.
For example, the division between two BigInts exceeding over one thousand digits should have perfect precision.
In contrast to numbers, which are represented as their literal digits, BigInts are similar, yet they end with the character 'n'.
BigInts can only be integers, meaning that operations performed involving two BigInts have any would-be decimals truncated.
Once again, using
5 and
2 as an example, we would add the character 'n' as a suffix to every value, and get a BigInt as a result:
5n / 2n = 2n.
The reason for the distinction between "plain" numbers and BigInts is that mixing them will always result in a runtime type error being thrown.
Strings are similar to arrays of characters, and like objects, they have properties, namely, the
.length property, and indexes corresponding to each of their values.
There is no "character" data type in JavaScript, indexing into a string simply yields another string, with a length of one.
Strings are generally viewed as one type, yet a distinction can be made between literal strings: strings and template strings. Template strings will be explained in more depth later.
String literals are denoted as their contents, beginning and ending with one of the three different JavaScript quotes. Note, the ending and beginning must be the same character.
The three characters that a string may start and end with are the apostrophe
', the quote
", and the grave accent mark
`.
The three different characters are often called the "single quote," "double quote," and "back-tick
" or "backquote," respectively.
Examples:
"That's the novel that had made me reconsider what I was doing"; 'The criminal broke into the store and said, "hand over the money!"'; `And the reader groaned, "couldn't this tutorial have been shorter?"`;
Note that template strings use the
` character, whereas the other two strings are just plain strings.
Booleans represent conditions. They are denoted by the literal tokens
true or
false in JavaScript.
Examples:
true; false;
On their own, they are relatively useless. But when operated on, in more complex pieces of code, they can be incredibly valuable. Oftentimes they are involved in statements that result in conditional execution of code.
Undefined is JavaScript's representation of a non-existent value.
For example, accessing out of bounds memory in JavaScript generally results in
undefined, as opposed to a runtime error, which is common in many other languages.
It may be denoted by the built-in property
undefined, or any operation that may yield the value.
An example of accessing the global property:
undefined;
Symbols are unique values that are only equivalent to the original value.
They take a role similar to enums in other C-family languages.
They have no literal syntax, instead, they must be constructed from the
Symbol constructor.
Symbol("This is a unique value") === Symbol("This is a unique value");
The result of the above expression would be
false because although the constructor was called with the same value, the symbol that was returned is different.
Symbols are primarily used with objects.
Datatypes: Objects
Objects, in contrast to primitives, are mutable.
Similar to
Symbols, the result of comparing two objects results in
true only when comparing an object to the original object.
Objects have properties, when a property is a function, that when called, operates on the object that holds the function, the function is not called a property, but a method.
Objects are used to represent more complex structures than what the primitive data types can.
They can represent just about anything, here are a few:
- Null
- Objects
- Arrays
- Functions
- Functions sub types (listed later)
- Maps
- Sets
- ArrayBuffers (raw memory)
- Exceptions
- Structs
- Files
- Directories
- Dates (Time)
- Events
- GUI Elements
- References (to other objects)
...
(If you haven't caught on, the list could go on forever)
Null is separate from the rest of the objects.
Sometimes it is considered a primitive, other times it is considered to be an object.
JavaScript's
typeof operator claims that
null is an object, while some say that this is simply a known mistake.
JavaScript uses prototypical inheritance, instead of the common class-based inheritance common to other C-family languages.
Null is often used in the same ways that
undefined is used, that is, to represent a missing value.
Null is denoted by the literal token
null.
null;
All objects inherit from
null, via what is known as the "prototype chain."
All objects must be constructed, that is, to call a function, save for two specific types of objects, simple objects, and simple arrays.
Object literals start with the character
{, and end with the character
}.
Take, for example, a point on a graph. A point is two dimensional, and cannot be represented using a primitive.
({ x: 4.0, y: 9.0 });
Array literals consist of a list of values, separated by a comma, wrapped on both ends with a bracket.
[ "This", "is", "an", "array" ];
Objects will be covered in a later tutorial.
Variables
Variables are defined using one of two keywords,
let or
const, followed by a valid JavaScript name.
Here's a simplified pattern to define a valid JavaScript name: a chain of characters that does not include an operator, any whitespace, and that may not start with a numerical digit.
(character refers to any character in the UTF-8 encoding)
const creates an immutable binding to a value.
let creates a mutable binding to a value.
const x = 0; const y = 1; const z = x + y;
The value stored in
z should be the numerical
1.
Now, if we were to attempt to change the value stored in the variable
z, like so:
z = 3;
We would get a runtime error, as JavaScript is interpreted, whereas many other languages would give a compile-time error.
The other way to define a variable is to use
let.
let name = "John Doe";
Now, if we reassign the variable, like so:
name = "Jane Doe";
It should run perfectly fine!
Functions
Functions are sections of executable code, exposed to JavaScript as objects.
Functions are can be categorized into plenty of different categories, here are a few common ones:
- Named functions
- Anonymous functions
- Arrow functions
- Generator functions
- JavaScript functions
- Non-JavaScript functions
If you think that's a lot, some of these may overlap, and it's not uncommon for them to overlap.
And I'm confident that there might be more added later.
Take a close look at the last two, recall that functions are only
exposed to JavaScript as objects
A function that is called from JavaScript may not necessarily be executing JavaScript code.
Some examples of non-JavaScript functions come from foreign function interfacing.
If you want to, you could look into Mozilla's old XPCOM language bindings, Node.js' C++ addons, or Deno's plugin system for some examples of JavaScript FFIs.
Generally, non-JavaScript functions are written in native code, and as a result, are much more performant, as they are compiled to efficient, direct machine instructions.
In contrast, JavaScript is interpreted and may be compiled, but even compiled JavaScript has quite some runtime overhead holding it back.
Functions in JavaScript are defined using one of three primary ways, with slight variations for different function types:
- Naming a function using the
functionkeyword
- Assigning a variable with a function defined using the
functionkeyword
- Assigning a variable with a function defined using the arrow character combination
Examples:
function f(x, y) { // ... } const g = function (x, y) { // ... } const h = (x, y) => { // ... };
The third function here is called an "arrow function," whereas the former two are often simply referred to as functions. Arrow functions are often more common than plain functions, depending on a script's author.
Take note, although these are how you declare a function, you main obtain a function through other means. For example, calling a function could return another function.
Functions are reusable sections of executable instructions, they are generally used to compute a value based on given values and return it to the caller, just like the mathematical sense of a function. Some functions are called purely for their side-effects. The difference will be covered in a later tutorial.
Functions may be declared almost anywhere in code, even in other functions, and they may access any variables that were declared in the scope that they were declared in, creating what is known as a "closure."
Once you realize that you've written a similar piece of code more than once, use a function.
Operators
Every JavaScript operator, as of 2020, using
x and
y as placeholders for potential values:
- Arithmetic operators
x + yAddition / concatenation
x - ySubtraction
-xUnary numerical negation
x * yMultiplication
x / yDivision
x % yModulo
x ** yExponentiation
- Conditional operators
!xBoolean negation
x < yLess than
x > yGreater than
x === yEquality
x !== yInequality
x <= yLess than or equal to
x >= yGreater than or equal to
x || yOr
x && yAnd
- Bitwise operators
x ^ yExclusive or
x & yBitwise and
x | yBitwise inclusive or
~xBitwise negation (x & 1)
x << ySigned left shift
x >> ySigned right shift
x >>> yUnsigned right shift
- Miscellaneous operators
x = yAssignment
x, yComma
- Property lookups
- Unconditional
x.yDot
x[y]Bracket access
- Conditional
x?.yDot
x?.[y]Bracket access
- Function calls
x(y)Call
x?.(y)Conditional call
??Nullish coalescing
new xConstruction
x ? y : zConditional
await x"await"
typeof x"typeof"
delete x.ydeletion
Whew, that's quite a few operators, and I intentionally left some out.
The operators under "arithmetic" all yield a number when operating on two numbers, or a BigInt when given two BitInts. If both operands are strings, the addition operator (
+), will yield a new string, which is the result of merging both of the operands.
The five basic mathematical operations (
+,
-,
*,
/,
**) all operate on two floating-point numbers, without care as to whether or not an input was an integer or a floating-pointer number. Operations that would be considered mathematically undefined, for example, division by zero, will oftentimes simply return "infinity" or "nan."
The operator denoted by
** is equivalent to the mathematical exponentiation, usually written as a number, with another number as a superscript.
The modulo operator (
%) computes the remainder of the division between their operands.
The mathematical function for computing the same would be the following:
f(x, y) = y - x * ⌊ x / y ⌋
Or, in JavaScript:
const modulo = (x, y) => y - x * Math.floor( x / y );
All operators listed under "Conditional" are operations that return boolean values, which are represented as
true or
false.
Some of them may cast their operands to boolean values, namely
!,
||, and
&&.
Values are considered "truthy" or "falsy," meaning that they aren't the literal boolean
true or
false defined by the core of the language, but they can be used equivalently, or similarly.
All of the bitwise operators, with the sole exception of the unsigned right shift (
>>>), all specifically operate on 32-bit signed integers. When used on a floating-point number, they will truncate the decimal.
All of the bitwise operators, with the same exception being the unsigned right shift, are usable on BitInts, if, and only if, both operands are BigInts. (BigInts will be covered in the next tutorial)
The unsigned right shift requires an understanding of computer science and hardware representation of numbers.
It will convert its operands to unsigned 32-bit integers, removing decimals, as 32-bit conversions do, but also reinterpreting the operand as unsigned, meaning that negative values become positive.
Each of the operators under "miscellaneous" are oddballs that deserve separate explanations.
Every operator listed above will be gone over in-depth in the next tutorial.
What you can do with JavaScript
The core language of JavaScript isn't very useful, but instead, it's the fact that JavaScript is given so many functions and objects that make it useful. Essentially, JavaScript is very bloated.
Every built-in object has a method or property for almost anything that you could want to do with it.
If you want to re-encode a string from, say a Chinese encoding, to say UTF-8, there's a built-in object dedicated to just that.
Want to get the current time? There's an object dedicated to it. Another is being proposed as of this writing!
Want to send an HTTP request to get a resource? There are an object and a function both dedicated to it.
What to modify a web site's document? There's the entire
document object provided in every browser for doing just that.
Want to work with raw binary data? JavaScript has you covered, there is a standard interface for doing just that.
Are you trying to perform some mathematical transformations involving trigonometry? There's a standard object quite literally called "Math," dedicated to just that.
You can probably get where I am going with this, most algorithmic and low-level details are already taken care of for you.
Generally, there will be a proper tool for the job.
Examples of actual JavaScript code will be given in later tutorials.
How you should actually structure/write your code
Recall that JavaScript is a dynamically-typed language, in reality, its dynamic typing is rarely, if ever, helpful to developers.
Being dynamically-typed, variables and functions are not explicitly annotated with type meta information, which reduces code size, but also reduces readability, as one cannot read over someone else's code and easily determine what a function is intended to accept and output.
Oftentimes, comments and documentation are used to convey this information to other developers, removing whatever tradeoff in code size that there was.
JavaScript has type errors that can still occur from misusage of types.
And, to top it off, most implementations will be able to JIT compile statically typed code, whereas duck-typed code will be interpreted.
Try to write somewhat statically-typed code, that is clear in its intention, and with a few comments to explain modules of code.
Don't use a loop or a large structure, if there is already a built-in function dedicated to a purpose, oftentimes it is easier to recognize a well-named function when compared to a few lines of code intended to compute a value or execute an operation.
Developed in 1995, JavaScript, weakly and dynamically typed, multi-paradigm scripting language.
I feel like that is an insult to JS but at the same time it’s not wrong xD. Great tutorial I loved (re)learning JS!
@RayhanADev
a) I don't remember it reading that badly, rewrote it:
Developed in 1995, JavaScript is a simple weakly and dynamically typed, multi-paradigm scripting language.
b) How is that an insult? What part suggests such to the reader?
@xxpertHacker nono, it’s not ’insulting’ I just felt like that when I read weakly but I know that’s how it was written. You’re fine :D.
@RayhanADev Whew. I didn't insult JS.
But as I wrote this, I personally felt like I might've been seen as insulting JS here:
Thus, we can infer that JavaScript is, by default, unstructured. It was originally intended for amateurs who know little about computer science.
@xxpertHacker well you’re not wrong actually. JS was the first language I learned (when I was 8 mind you), but at the same time you aren’t putting into comparison to languages that are so many more times easier (aka Python). To me, that sounds fine but at least have a comparison to what it seems amateur to.
@RayhanADev Hmm... I'll see if I can rewrite it to fit in comparison and give a bit more there.
Thank you for the suggestion!
@CodeLongAndPros I can't even tell which one of their comments that you're responding to.
@CodeLongAndPros
also me seeing your github and realizing your full username is codelongandprosper
weakly and dynamically typed, multi-paradigm scripting language.
@CodeLongAndPros I don't get where the animal references are coming from though.
Weakly typed = Cat
Dynamically typed = Dog
Multi-paradigm language = Horse
Scripting language = Bat
Is that correct?
If so, I'm still lost.
@EpicGamer007
@DynamicSquid
There's literally no way that you two found this and finished reading this that fast.
@xxpertHacker mah dude: ive read this fast. anyways, i didnt need to learn all of it so i skim read most of it too.
(No it aint advertising)
@xxpertHacker i didnt know it was actually changed to mjs now too so that was really cool!
@EpicGamer007 Oh yeah, I gotta write about that in the next tutorial, seriously, it's work a whole section of it's own.
@xxpertHacker what you went over here is just basic js, you should go over ES Modules features which is what distincts .mjs from .js
@realTronsi And yes, the title is "background & basics," I haven't even mentioned how to run JavaScript yet. The next tutorial should have plenty of usable examples. (probably will be out tomorrow)
@xxpertHacker uh alright, can't tell what the point of this tbh since there is plenty of documentation online. Perhaps making advanced tutorials would be more suitable?
@realTronsi Yeah, it's going to be more advanced than normal at least, the simple tutorials are boring.
Also, everyone and their dog already know the basics of JavaScript, so if it's not advanced, then it's going anywhere.
...can't tell what the point of this tbh since there is plenty of documentation online...
Also, you might want to check the section labeled:
Why am I making this tutorial series?
@xxpertHacker I know but modern javascript has plenty of tutorials and docs online, and the majority is the same, not sure why you're starting with universal javascript knowledge. There's like a few key points you could cover in detail and personally I think that would be better
I know but modern javascript has plenty of tutorials and docs online
Lmao, MDN still uses
var, so idk about that.
All of the popular JS sites start by teaching old code, and that alone is enough to make me question everything.
There's like a few key points you could cover in detail and personally I think that would be better
Any particular key points in mind?
I'm still thinking about what should really be gone over in the (super short) series since the basics are well... basic.
And I don't care too much about covering how to use APIs, because every API has documentation surrounding it, explaining how to use it already.
I'm thinking that I should dedicate a section to promises, async, await, and whatnot, but I think there's a good tutorial out there already...
So I'm really looking for suggestions and feedback here.
@xxpertHacker well sure MDN uses
var, and I mean some people are super against it although it isn't that bad. javascript.info is probably the best site for learning the basics js imo. async, await, etc. are all covered in pretty much every good javascript tutorial.
Modern js mainly differs from its module system so covering that could be a good start
@realTronsi
Hmm... I think I'll try to get a
few more cycles bit more feedback from the community, and some more responses.
But really, the module system is built around two keywords,
import and
export.
Not much else to it.
export default foo; export const bar = ...; export { bar as baz }; export * as quux from "module1.mjs"; import foo, { bar, baz, quux } from "module2.mjs";
Eh, I guess I have a start.
@xxpertHacker I mean yeah it's a bit different
but tbh not many cycles you can milk from this not many people even know what mjs is
@realTronsi Yeah, most have no clue.
I saw a web application that literally demoed a feature of modern code, and didn't even use modules.
I'll make sure to point out the difference in detail, in the next post, once again, probably tomorrow.
but tbh not many cycles you can milk from this
Phf, why did the ultimate Java tutorial get almost 90 cycles?
@xxpertHacker because it had this line:
Also, I do not think I ask this a lot but because I think I put a lot of effort into this, I will ask this: PLEASE UPVOTE IF YOU ENJOYED. IT REALLY MOTIVATES ME TO CONTINUE WORKING ON THESE KINDS OF THINGS. NO THIS IS NOT SOME KIND OF GARBAGE tutorial that teaches you nothing and does not explain well. THIS IS AT LEAST 1400 lines and 2 1/2 months of work!
@realTronsi
Lmao
2 1/2 months of work
I only wrote about 400 lines in a few hours, I should feel ashamed of myself. And I had barely touched upon the basics.
But seriously, which specific part about it drew people in?
@xxpertHacker not sure, probably because Java is more well known. I am willingly to bet 0% of people read through the entire wall of a post
because Java is more well known
Perfect plan: create a Python tutorial on Repl.it.
Also, I had only read halfway through their post too.
@xxpertHacker simple solution: just realize you probably have a higher chance of succeeding in life as a coder than people who post and make projects for cycles and start doing productive things that will later actually get you a job rather than on marketing ;)
@realTronsi Eh, I just know how to code, since I picked it up quickly, but I definitely won't try to get a job coding.
From what I've seen, the industry isn't the right place for me. (although, I might just go ahead and change the industry instead)
But really I've been inactive and haven't been making any large projects.
...and start doing productive things
Even the cycle farmers are doing stuff.
Take Coder100 as an example, they're still making applications and web pages, that gives them experience.
Then I look at how I practically forgot everything about CSS and can't fix that nav bar.
I really need to start finishing what I begin.
Probably gonna post in /ask about that web page soon.
(although, I might just go ahead and change the industry instead)
damn thats some bold words
Even the cycle farmers are doing stuff.
Take Coder100 as an example, they're still making applications and web pages, that gives them experience.
well idk Coder doesn't necessarily farm as much as others in that regard, since he just naturally gets a lot of cycles due to already being popular
@realTronsi Eh, okay, Coder's just popular, not a farmer.
And I've settled on making part 2 quickly get into modules, comparing them to scripts, giving some context about their origins, the differences, the benefits, etc, encouraging their use all-around.
Referencing what you had said near the beginning:
Perhaps making advanced tutorials would be more suitable?
But I have to ask, what do you consider to be "advanced"?
Complex code isn't always advanced.
Cleverly written code isn't always advanced.
Modern written code isn't always advanced.
What is it that really shows advanced JavaScript?
I'd say the most advanced scripters that I've met, (including myself), their code sort of masks how complex a task really is by breaking it down, so it still seems simple.
What is it that is recognizable about advanced code?
What makes you realize that someone has an advanced understanding of code?
Whether it's specifically JavaScript or not, I don't mind.
@xxpertHacker well "advanced" is a pretty subjective term, tbh now that I think of it being "advanced" does just come with experience and you can't really simulate that with a tutorial, but imo I'd classify it as your approach to solving a problem.
Super simple example:
sorting an array
a naive approach could just keep looping with O(n!)
while an "advanced" coder could use quick sort
I know this is a super simplified example and also obviously knowing quicksort algorithm doesn't define your experience but just stuff like that
Thank you so much for this tutorial! I was looking for a short and comprehensive tutorial and I found just the one. Looking forward to the part 3!
@represa Sorry, unfortunately, it seems that the tutorial was cut short.
I guess you'll have to look elsewhere, maybe javascript.info?
Wherever you learn it from, good luck!
@xxpertHacker I'm so sad to hear that.
Thanks for the sugestion, I will definitely look it up. | https://replit.com/talk/learn/The-Modern-JavaScript-Tutorial-Series-Part-1/79566 | CC-MAIN-2021-25 | refinedweb | 5,550 | 62.17 |
HelloCustomer Thank you for coming to Just Answer and allowing us to help with your tax problem. I am very sorry to hear that you are having difficulties with your previous and current tax preparers. If I am correctly reading your question, H&R Block was responsible for the error on your 2006 return. There is a 3 year period in which the IRS will return money to taxpayers if the original return is amended. You will have to have the 2006 taxes amended and sent to the IRS before april 15, 2010 or the IRS will never pay you the money that you are owed under any circumstances. If it is at all possible, you need to go back to the H&R Office that performed the incorrect return and have them correct their mistake by correctly preparing the amended return at no cost to you. If the mistake was clearly theirs, they should give you a fight about it. If the mistake was clearly theirs and they won't help you, demand to know the location and phone number of their district office and the name of the district manager. The district manager should fix the problems.
If H&R Block didn't start the problem or it can't be proven to clearly be the result of their mistake, then your situation is trickier. H&R Block will amend the return for you, but you will have to pay them to correct it. Depending on the type of poblem, they will charge from about $50 t0 $100. If you don't want to work with them at all ever again, then you go to the office where your return was prepared and you demand that they give all of your paperwork back to you. Then, you take the paperwork to another preparer and have them prepare the amended return.
If either of the tax preparers continue to claim that they mailed all of your paperwork to you and that they didn't keep anything, they're not telling you the truth. A tax preparer is required by law to keep the tax forms they fill out, a copy of your w-2(s), and a copy of any 1099 forms you receive. These are the minimum paperwork a preparer needs to fix the return needed amended. A lot of items can be gotten of the internet. If you can't get your W-2s, either the IRS has a copy or the state has a copy of your earnings and withholdings, so at worst go to the Social Security office, the IRS office, and the state bureau of employment and request an earnings statement for 2006.
For your 2008 return, basically follow the same routine listed above, try and make them print off another copy of your tax return (it is on their computer) and give it to you. If no return was filed, your tax preparer should offer to fix the problem for you. If they don't, demand that they print enough copies of the return to send to all of your taxing authorities (federal, state?, Local? and one for you). Then you just mail in the 2008 return yourself to the various agencies. Your state tax office might be able to help you a lot with that.
Also, you should look around your house for your 2006 papers. Most of the national tax preparation companies will give the client a folder with copies of everything needed for the return in the folder. If you can find the folders, you'll be a much better position.
It's up to you whether you want to sue the preparer in small claims court. It sounds like they messed up enough that you have a chance on winning a settlement. However fixing your 2006 taxes should be your first priority. The IRS will be adding interest and penalties to your tax bill every day. You also probably need to charm the companies into giving them the papers you need (hopefully) and you can't charm them when your suing them.
I hope these suggestions help. Please let me know if you would like me to provide any
additional information or if I keep to clarify a point for you. Thank you
Hello again. I have just reread my original answer and I'm sorry to see that I made a number of typos that I didn't catch. Let me correct my original answer and then we'll continue from there. If H&R Block made a mistake on the return that they prepared, they will create an amended return for you with no charge for correcting their mistake. They should not fight with you if they made a mistake. If the office manager of the office you worked with is reluctant to amend the return for you, then ask to speak to the district office and the district manager.
H&R Block keeps computer files of all tax returns that they prepare. Unless there was an unusual situation, the H&R Block office that you worked with in 2006 (which year's taxes were incorrectly prepared, 2006 or 2007?) will have a copy of the original tax return that was filed with the IRS. If H&R Block made the error in your 2006 return, they will amend your 2006 return to correct the error for free. The only records you may need to correct your 2006 return would be related to the error. If you tell me what the error was, I may be able to tell you whether you need to get other paperwork and where to get it. If the H&R Block office manager doesn't think that the error was caused by H&R Block, they will still have the original paperwork and they will still help you fix your return, but there may be fees associated with the amended return.
Was the return for last year's taxes ever filed with the IRS or did your tax preparer send you the forms to file by mail? If the tax return for last year was never filed, then you should contact your employers and any other organization that sent you tax information that you gave to your tax person and see if they can send you another copy of last year's information. If you can get your employer to give you additional copies of your W-2s, then you can have another tax preparer prepare last year's return again and you can file it with the IRS. As long as you didn't owe any money to the IRS, there won't be penalties for the return being filed late. If you did owe, then you will have to pay penalties and interest to the IRS on the money you didn't pay them last year. Either way, you want to file last year's tax return as soon as possible if it wasn't filed.
If you can't get copies of your income papers from your employer(s), you can get an income statement for last year from your local Social Security office and a tax preparer can make a substitute W-2 form from the earnings statement.
The first thing you need to do is to contact the H&R Block office that prepared the incorrect tax return and work with them to amend that return and fix the problem. If they don't have the original return that needs corrected, they can explain to you how to get a copy of that return from the IRS. Also, talk to last year's tax preparer and see if any return was filed for you last year. If no return was filed, contact your employers and see if you can get copies of last year's W-2s. If you can't, contact your local social security office and tell them that you need an earnings statement for next year. Once you have either the W-2s or the earnings statement, then contact a new tax preparer (I would still recommend H&R Block) to prepare a new return for last year.
I hope this helps clarify things. I apologize for the typos in my previous answer (I must have been more tired than I realized). Let me know if you need more information and if you give me more specifics on the error made in your previous return, I may be able to tell you where to get replacement documentation if needed. | http://www.justanswer.com/tax/2nj0f-tax-preparer-taxes-last-year-found.html | CC-MAIN-2015-06 | refinedweb | 1,426 | 75.03 |
One of the most important things to understand about React is that it is fundamentally JavaScript. This means that the better you are at JavaScript, the more successful you will be with React.
Let's break down the 7 essential concepts that you should know about JavaScript to master React.
And when I say these concepts are essential, I mean that they are used in every single application that a React developer makes, with little to no exceptions.
Learning these concepts is one of the most valuable things you can do to accelerate your ability to make React projects and become a skilled React developer, so let's get started.
Want your own copy of this guide?
Download the cheatsheet in PDF format here (it takes 5 seconds).
1. Function Declarations and Arrow Functions
The basis of any React application is the component. In React, components are defined with both JavaScript functions and classes.
But unlike JavaScript functions, React components return JSX elements that are used to structure our application interface.
// JavaScript function: returns any valid JavaScript type function javascriptFunction() { return "Hello world"; } // React function component: returns JSX function ReactComponent(props) { return <h1>{props.content}</h1> }
Note the different casing between the names of JavaScript functions and React function components. JavaScript functions are named in camel casing, while React function components are written with pascal casing (in which all words are capitalized).
There are two different ways to write a function in JavaScript: the traditional way, using the
function keyword, called a function declaration, and as an arrow function, which was introduced in ES6.
Both function declarations and arrow functions can be used to write function components in React.
The primary benefit of arrow functions is their succinctness. We can use several shorthands in order to write our functions to remove unnecessary boilerplate, such that we can even write it all on a single line.
// Function declaration syntax function MyComponent(props) { return <div>{props.content}</div>; } // Arrow function syntax const MyComponent = (props) => { return <div>{props.content}</div>; } // Arrow function syntax (shorthand) const MyComponent = props => <div>{props.content}</div>; /* In the last example we are using several shorthands that arrow functions allow: 1. No parentheses around a single parameter 2. Implicit return (as compared to using the "return" keyword) 3. No curly braces for function body */
One small benefit of using function declarations over arrow functions is that you don't have to worry about problems with hoisting.
Due to the JavaScript behavior of hoisting, you can use multiple function components made with function declarations in a single file in whichever order you like.
Function components made with arrow functions, however, cannot be ordered whichever way you like. Because JavaScript variables are hoisted, arrow function components must be declared before they are used:
function App() { return ( <> {/* Valid! FunctionDeclaration is hoisted */} <FunctionDeclaration /> {/* Invalid! ArrowFunction is NOT hoisted. Therefore, it must be declared before it is used */} <ArrowFunction /> </> } function FunctionDeclaration() { return <div>Hello React!</div>; } function ArrowFunction() { return <div>Hello React, again!</div>; }
Another small difference in using the function declaration syntax is that you can immediately export a component from a file using
export default or
export before the function is declared. You can only use the
export keyword before arrow functions (default exports must be placed on a line below the component).
// Function declaration syntax can be immediately exported with export default or export export default function App() { return <div>Hello React</div>; } // Arrow function syntax must use export only export const App = () => { return <div>Hello React</div>; }
2. Template Literals
JavaScript has a clumsy history of working with strings, particularly if you want to concatenate or connect multiple strings together. Before the arrival of ES6, to add strings together you needed to use the
+ operator to add each string segment to one another.
With the addition of ES6, we were given a newer form of string called a template literal, which consists of two back ticks
`` instead of single or double quotes.
Instead of having to use the
+ operator, we can connect strings by putting a JavaScript expression (such as a variable) within a special
${} syntax:
/* Concatenating strings prior to ES6. Notice the awkward space after the word Hello? */ function sayHello(text) { return 'Hello ' + text + '!'; } sayHello('React'); // Hello React! /* Concatenating strings using template literals. See how much more readable and predictable this code is? */ function sayHelloAgain(text) { return `Hello again, ${text}!`; } sayHelloAgain('React'); // Hello again, React!
What's powerful about template literals is their ability to use any JavaScript expression (that is, anything in JavaScript that resolves to a value) within the
${} syntax.
We can even include conditional logic using the ternary operator, which is perfect for conditionally adding or removing a class or style rule to a given JSX element:
/* Go to react.new and paste this code in to see it work! */ import React from "react"; function App() { const [isRedColor, setRedColor] = React.useState(false); const toggleColor = () => setRedColor((prev) => !prev); return ( <button onClick={toggleColor} style={{ background: isRedColor ? "red" : "black", color: 'white' }} > Button is {isRedColor ? "red" : "not red"} </button> ); } export default App;
In short, template literals are great for React whenever we need to dynamically create strings. For example, when we use string values that can change in our head or body elements in our site:
import React from 'react'; import Head from './Head'; function Layout(props) { // Shows site name (i.e. Reed Barger) at end of page title const title = `${props.title} | Reed Barger`; return ( <> <Head> <title>{title}</title> </Head> <main> {props.children} </main> </> ); }
3. Short Conditionals: &&, ||, Ternary Operator
Considering that React is just JavaScript, it is very easy to conditionally show (or hide) JSX elements using simple if statements and sometimes switch statements.
import React from "react"; function App() { const isLoggedIn = true; if (isLoggedIn) { // Shows: Welcome back! return <div>Welcome back!</div>; } return <div>Who are you?</div>; } export default App;
With the help of some essential JavaScript operators, we cut down on repetition and make our code more concise.
We can transform the if statement above into the following, using the ternary operator. The ternary operator functions exactly the same as an if-statement, but it is shorter, it is an expression (not a statement), and can be inserted within JSX:
import React from "react"; function App() { const isLoggedIn = true; // Shows: Welcome back! return isLoggedIn ? <div>Welcome back!</div> : <div>Who are you?</div> } export default App;
Ternary operators can also be used inside curly braces (again, since it is an expression):
import React from "react"; function App() { const isLoggedIn = true; // Shows: Welcome back! return <div>{isLoggedIn ? "Welcome back!" : "Who are you?"</div>; } export default App;
If we were to change the example above and only wanted to show text if the user was logged in (if
isLoggedIn is true), this would be a great use case for the
&& (and) operator.
If the first value (operand) in the conditional is true, the
&& operator displays the second operand. Otherwise it returns the first operand. And since it is falsy (is a value automatically converted to the boolean
false by JavaScript), it is not rendered by JSX:
import React from "react"; function App() { const isLoggedIn = true; // If true: Welcome back!, if false: nothing return <div>{isLoggedIn && "Welcome back!"}</div>; } export default App;
Let's say that we want the reverse of what we're doing now: to only say "Who are you?" if
isLoggedIn is false. If it's true, we won't show anything.
For this logic, we can use the
|| (or) operator. It essentially works opposite to the
&& operator. If the first operand is true, the first (falsy) operand is returned. If the first operand is false, the second operand is returned.
import React from "react"; function App() { const isLoggedIn = true; // If true: nothing, if false: Who are you? return <div>{isLoggedIn || "Who are you?"}</div>; } export default App;
4. Three Array Methods: .map(), .filter(), .reduce()
Inserting primitive values into JSX elements is easy – just use curly braces.
We can insert any valid expressions, including variables that contain primitive values (strings, numbers, booleans, and so on) as well as object properties that contain primitive values.
import React from "react"; function App() { const name = "Reed"; const bio = { age: 28, isEnglishSpeaker: true }; return ( <> <h1>{name}</h1> <h2>I am {bio.age} years old</h2> <p>Speaks English: {bio.isEnglishSpeaker}</p> </> ); } export default App;
What if we have an array and we want to iterate over that array to show each array element within an individual JSX element?
For this, we can use the
.map() method. It allows us to transform each element in our array in the way we specify with the inner function.
Note that it is especially concise when used in combination with an arrow function.
/* Note that this isn't exactly the same as the normal JavaScript .map() method, but is very similar. */ import React from "react"; function App() { const programmers = ["Reed", "John", "Jane"]; return ( <ul> {programmers.map(programmer => <li>{programmer}</li>)} </ul> ); } export default App;
There are other flavors of the .map() method that perform related tasks and are important to know because they can be chained in combination with one another.
Why? Because
.map(), like many array methods, returns a shallow copy of the array that it has iterated over. This enables its returned array to be passed onto the next method in the chain.
.filter(), as its name indicates, allows us to filter certain elements out of our array. For example, if we wanted to remove all names of programmers that started with "J", we could do so with
.filter():
import React from "react"; function App() { const programmers = ["Reed", "John", "Jane"]; return ( <ul> {/* Returns 'Reed' */} {programmers .filter(programmer => !programmer.startsWith("J")) .map(programmer => <li>{programmer}</li>)} </ul> ); } export default App;
It's important to understand that both
.map() and
.filter() are just different variations of the
.reduce() array method, which is capable of transforming array values into virtually any data type, even non-array values.
Here's
.reduce() performing the same operation as our
.filter() method above:
import React from "react"; function App() { const programmers = ["Reed", "John", "Jane"]; return ( <ul> {/* Returns 'Reed' */} {programmers .reduce((acc, programmer) => { if (!programmer.startsWith("J")) { return acc.concat(programmer); } else { return acc; } }, []) .map((programmer) => ( <li>{programmer}</li> ))} </ul> ); } export default App;
5. Object Tricks: Property Shorthand, Destructuring, Spread Operator
Like arrays, objects are a data structure that you need to be comfortable with when using React.
Since objects exist for the sake of organized key-value storage, unlike arrays, you're going to need to be very comfortable accessing and manipulating object properties.
To add properties to an object as you create it, you name the property and its corresponding value. One very simple shorthand to remember is that if the property name is the same as the value, you only have to list the property name.
This is the object property shorthand:
const name = "Reed"; const user = { // instead of name: name, we can use... name }; console.log(user.name); // Reed
The standard way to access properties from an object is using the dot notation. An even more convenient approach, however, is object destructuring. It allows us to extract properties as individual variables of the same name from a given object.
It looks somewhat like you're writing an object in reverse, which is what makes the process intuitive. It's much nicer to use than having to use the object name multiple times to access each time you want to grab a value from it.
const user = { name: "Reed", age: 28, isEnglishSpeaker: true }; // Dot property access const name = user.name; const age = user.age; // Object destructuring const { age, name, isEnglishSpeaker: knowsEnglish } = user; // Use ':' to rename a value as you destructure it console.log(knowsEnglish); // true
Now if you want to create objects from existing ones, you could list properties one-by-one, but that can get very repetitive.
Instead of copying properties manually, you can spread all of an object's properties into another object (as you create it) using the object spread operator:
const user = { name: "Reed", age: 28, isEnglishSpeaker: true }; const firstUser = { name: user.name, age: user.age, isEnglishSpeaker: user.isEnglishSpeaker }; // Copy all of user's properties into secondUser const secondUser = { ...user };
What is great about the object spread is that you can spread in as many objects into a new one as you like, and you can order them like properties. But be aware that properties that come later with the same name will overwrite previous properties:
const user = { name: "Reed", age: 28 }; const moreUserInfo = { age: 70, country: "USA" }; // Copy all of user's properties into secondUser const secondUser = { ...user, ...moreUserInfo, computer: "MacBook Pro" }; console.log(secondUser); // { name: "Reed", age: 70, country: "USA", computer: "Macbook Pro" }
6: Promises + Async/Await Syntax
Virtually every React application consists of asynchronous code – code that takes an indefinite amount of time to be executed. Particularly if you need to get or change data from an external API using browser features like the Fetch API or the third-party library axios.
Promises are used to resolve asynchronous code to make it resolve like normal, synchronous code, which we can read from top to bottom.
Promises traditionally use callbacks to resolve our asynchronous code. We use the
.then() callback to resolve successfully resolved promises, while we use the
.catch() callback to resolve promises that respond with an error.
Here is a real example of using React to fetch data from my GitHub API using the Fetch API to show my profile image. The data is resolved using promises:
/* Go to react.new and paste this code in to see it work! */ import React from 'react'; const App = () => { const [avatar, setAvatar] = React.useState(''); React.useEffect(() => { /* The first .then() lets us get JSON data from the response. The second .then() gets the url to my avatar and puts it in state. */ fetch('') .then(response => response.json()) .then(data => setAvatar(data.avatar_url)) .catch(error => console.error("Error fetching data: ", error); }, []); return ( <img src={avatar} ); }; export default App;
Instead of always needing to use callbacks to resolve our data from a promise, we can use a cleaned syntax that looks identical to synchronous code, called the async/await syntax.
The async and await keywords are only used with functions (normal JavaScript functions, not React function components).
To use them, we need to make sure our asynchronous code is in a function prepended with the keyword
async. Any promise's value can then be resolved by placing the keyword
await before it.
/* Go to react.new and paste this code in to see it work! */ import React from "react"; const App = () => { const [avatar, setAvatar] = React.useState(""); React.useEffect(() => { /* Note that because the function passed to useEffect cannot be async, we must create a separate function for our promise to be resolved in (fetchAvatar) */ async function fetchAvatar() { const response = await fetch(""); const data = await response.json(); setAvatar(data.avatar_url); } fetchAvatar(); }, []); return <img src={avatar}; }; export default App;
We use the
.catch() callback to handle errors within traditional promises, but how do you catch errors with async/await?
We still use
.catch() and when we hit an error, such as when we have a response from our API that is in the 200 or 300 status range:
/* Go to react.new and paste this code in to see it work! */ import React from "react"; const App = () => { const [avatar, setAvatar] = React.useState(""); React.useEffect(() => { async function fetchAvatar() { /* Using an invalid user to create a 404 (not found) error */ const response = await fetch(""); if (!response.ok) { const message = `An error has occured: ${response.status}`; /* In development, you'll see this error message displayed on your screen */ throw new Error(message); } const data = await response.json(); setAvatar(data.avatar_url); } fetchAvatar(); }, []); return <img src={avatar}; }; export default App;
7. ES Modules + Import / Export syntax
ES6 gave us the ability to easily share code between our own JavaScript files as well as third-party libraries using ES modules.
Also, when we leverage tools like Webpack, we can import assets like images and svgs, as well as CSS files and use them as dynamic values in our code.
/* We're bringing into our file a library (React), a png image, and CSS styles */ import React from 'react'; import logo from '../img/site-logo.png'; import '../styles/app.css'; function App() { return ( <div> Welcome! <img src={logo} </div> ); } export default App;
The idea behind ES modules is to be able to split up our JavaScript code into different files, to make it modular or reusable across our app.
As far as JavaScript code goes, we can import and export variables and functions. There are two ways of importing and exporting, as named imports/exports and as default imports/exports.
There can only be one thing we make a default import or export per file and we can make as many things named imports/export as we like. For example:
// constants.js export const name = "Reed"; export const age = 28; export default function getName() { return name; } // app.js // Notice that named exports are imported between curly braces import getName, { name, age } from '../constants.js'; console.log(name, age, getName());
We can also write all of the exports at the end of the file instead of next to each variable or function:
// constants.js const name = "Reed"; const age = 28; function getName() { return name; } export { name, age }; export default getName; // app.js import getName, { name, age } from '../constants.js'; console.log(name, age, getName());
You can also alias or rename what you are importing using the
as keyword for named imports. The benefit of default exports is that they can be named to whatever you like.
// constants.js const name = "Reed"; const age = 28; function getName() { return name; } export { name, age }; export default getName; // app.js import getMyName, { name as myName, age as myAge } from '../constants.js'; console.log(myName, myAge, getMyName());
In the time it takes to watch your favorite TV show, you can start a $100,000 / year career with React.
In this premium React training course, you can unlock the knowledge, skills, and confidence that deliver life-changing results in real dollars.
Gain the insider information hundreds of developers have already used to master React, find their dream jobs, and take control of their future:
| https://www.freecodecamp.org/news/javascript-skills-you-need-for-react-practical-examples/ | CC-MAIN-2021-21 | refinedweb | 3,032 | 55.84 |
On 07/02/2010 06:54 AM, Chris Lalancette wrote: >> Should virDomainDefNamespaceHref take a void* argument... >> >>> + if (def->namespaceData && def->ns.href) >>> + virBufferVSprintf(&buf, " %s", (def->ns.href)()); >> >> and pass def->namespaceData through to that function? I'm a little bit >> nervous about callback functions that cannot be extended, and passing a >> (unused, for now) void* pointer gives us some room for growth without >> changing the API, if need be. > > We could. It's an internal API, though, so we are free to change it at > will later. Fair enough, since it is not exported. >>> static virDomainDefPtr virDomainDefParseXML(virCapsPtr caps, >>> - xmlXPathContextPtr ctxt, int flags) >>> + xmlDocPtr xml, >>> + xmlNodePtr root, >>> + xmlXPathContextPtr ctxt, >>> + int flags) >> >> As long as we are changing this API, should we change flags to unsigned >> int? And should we add a virCheckFlags(VIR_DOMAIN_XML_INACTIVE..., NULL)? > > Again, an internal API, so I guess I could change the flags. Minor change, > though. As far as virCheckFlags() is concerned, my take on it (and it's usage > in the tree up to this point) is always at driver entry points, not > internal API's. While we could add it here, passing bogus flags here is a > programming error, not a user error. Good point - there's a difference between a static function used only internally (we can check all callers in the same file) and a driver callback (where the interface is public, and we can't control the behavior of external programs that link to our library and pass arbitrary flags). So, with my questions addressed, ACK. -- Eric Blake eblake redhat com +1-801-349-2682 Libvirt virtualization library
Attachment:
signature.asc
Description: OpenPGP digital signature | https://www.redhat.com/archives/libvir-list/2010-July/msg00054.html | CC-MAIN-2017-26 | refinedweb | 274 | 64.91 |
How can I show in the screen 3D Render
I'm new to Qt 3D, I want to render a 3D model (OBJ file) in the screen I read in Qt Documentation that I can use Viewport and Mesh to load the file. But I did not find how to send to screen my current Mesh.
Bellow a sample of my code. Let me know your suggestions.
Thanks!
import QtQuick 2.7 as QQ2 //import QtQuick.Controls 2.0 //import QtQuick.Layouts 1.3 import Qt3D.Core 2.0 import Qt3D.Render 2.0 import Qt3D.Input 2.0 //import Qt3D.Logic 2.0 import Qt3D.Extras 2.0 //import Qt3D.Animation 2.0 Viewport { id: root Mesh{ id: mesh source: "braz.obj" } } | https://forum.qt.io/topic/80768/how-can-i-show-in-the-screen-3d-render | CC-MAIN-2017-39 | refinedweb | 123 | 80.88 |
#include <CGAL/Straight_skeleton_builder_2.h>
The implemented algorithm is closely based on [FO98] with the addition of vertex events as described in [EE98].
It simulates a grassfire propagation of moving polygon edges as they move inward at constant
and equal speed. That is, the continuous inward offsetting of the polygon.
Since edges move at equal speed their movement can be characterized in a simpler setup as the movement of vertices. Vertices move along the angular bisector of adjacent edges.
The trace of a moving vertex is described by the algorithm as a bisector. Every position along a bisector corresponds to the vertex between two offset (moved) edges. Since edges move at constant speed, every position along a bisector also corresponds to the distance those two edges moved so far.
From the perspective of a dynamic system of moving edges, such a distance can be regarded as an instant (in time). Therefore, every distinct position along a bisector corresponds to a distinct instant in the offsetting process.
As they move inward, edges can expand or contract w.r.t to the endpoints sharing a vertex. If a vertex has an internal angle , its incident edges will contract but if its internal angle , they will expand. The movement of the edges, along with their extent change, result in collisions between non-adjacent edges. These collisions are called events, and they occur when the colliding edges have moved a certain distance, that is, at certain instants.
If non-consecutive edges E(j),E(k) move while edge E(i) contracts, they can collide at the point when E(i) shrinks to nothing (that is, the three edges might meet at a certain offset). This introduces a topological change in the polygon: Edges E(j),E(k) are now adjacent, edge E(i) disappears, and a new vertex appears. This topological change is called an edge event.
Similarly, consecutive expanding edges E(i),E(i+1) sharing a reflex vertex (internal angle ) might collide with any edge E(j) on the rest of the same connected component of the polygon boundary (even far away from the initial edge's position). This also introduces a topological change: E(j) gets split in two edges and the connected component having E(i),E(i+1) and E(j) is split in two unconnected parts: one having E(i) and the corresponding subsegment of E(j) and the other with E(i+1) and the rest of E(j). This is called a split event.
If a reflex vertex hits not an edge E(j) but another reflex vertex E(j),E(j+1), and vice-versa (the reflex vertex V(j) hits V(i)), there is no actual split and the two unconnected parts have E(i),E(j) and E(i+1),E(j+1) (or E(i),E(j+1) and E(i+1),E(j)). This topological change is called a vertex event. Although similar to a split event in the sense that two new unconnected contours emerge introducing two new contour vertices, in the case of a vertex event one of the new contour vertices might be reflex; that is, a vertex event may result in one of the offset polygons having a reflex contour vertex which was not in the original polygon.
Edges movement is described by vertices movement, and these by bisectors. Therefore, the collision between edges E(j),E(i),E(k) (all in the same connected component) occurs when the moving vertices E(j)->E(i) and E(i)->E(k) meet ; that is, when the two bisectors describing the moving vertices
intersect (Note: as the edges move inward and events occur, a vertex between edges A and B might exist even if A and B are not consecutive; that is, j and k are not necessarily i-1 and i+1 respectively, although initially they are).
Similarly, the collision between E(i),E(i+1) with E(j) (all in the same connected component) occurs when the bisector corresponding to the moving vertex E(i)->E(i+1) hits the moving edge E(j).
Since each event changes the topology of the moving polygon, it is not possible or practical to foresee all events at once. Rather, the algorithm starts by estimating an initial set of potential events and from there it computes one next event at a time based on the previous one. The chaining of events is governed by their relative instants: events that occur first are processed first.
An initial set of potential split events is first computed independently (the computation of a potential split event is based solely on a reflex vertex and all other edges in the same connected component); and an initial set of potential edge events between initially consecutive bisectors is first computed independently (based solely on each bisector pair under consideration).
Events occur at certain instants and the algorithm must be able to order them accordingly. The correctness of the algorithm is uniquely and directly governed by the correct computation and ordering of the events. Any potential event might no longer be applicable after the topological change introduced by a prior event.
A grassfire propagation picks the next unprocessed event (starting from the first) and if it is still applicable processes it. Processing an event involves connecting edges, adding a new skeleton vertex (which corresponds the a contour vertex of the offset polygon) and calculating one new potential future event (which can be either an edge event or a split event -because of a prior vertex event-), based on the topological change just introduced. The propagation finishes when there are no new future events. | https://doc.cgal.org/Manual/3.4/doc_html/cgal_manual/Straight_skeleton_2_ref/Class_Straight_skeleton_builder_2.html | CC-MAIN-2019-13 | refinedweb | 944 | 56.18 |
Code is below I keep getting error that it returns "Hy lok Wrds!" instead of "Hy lk Wrds!" why is it leaving that other "o" in look.
def anti_vowel(text):
unvoweled = []
for letter in text:
unvoweled.append(letter)
ind = 0
voweled = unvoweled
for charac in voweled:
if charac in "aeiouAEIOU":
unvoweled.pop(ind)
ind = ind + 1
else:
ind = ind + 1
return "".join(unvoweled)
It is simpler to loop over your string with:
for letter in text:
and append any letter that isn't a vowel, to an array.
There is a difficulty with your solution. lets say i have a really simple string:
print anti_vowel("book")
b is at index 0, your first o at index 1, second o at index 2 and the k on index 3. The moment the moment the first o is encountered index is 1, it pops the o. then the index increases (now your index is 2), but because of the pop, the second o of book has shift to index 1, and won't be removed. Removing like you do here, is an really difficult thing to do, because of what i just explained
o
@stetim94, @datarockstar20306,So would it be sufficientto leave outind = ind + 1after the pop ??
ind = ind + 1
pop
no, it is not. ind doesn't control the index, the for loop is:
for charac in voweled:
ind is only the same as the index of the for loop because it increased by one each time the for loop runs (same as the loop)
found on stackoverflow:for <var> in <iterable> merely runs the loop body with the <var> taking each value available from the iterable. Changing the <var> will have no effect on the ensuing iterations, so you can't, you would have to use a while loop of sort, give me a second to look at it
for <var> in <iterable>
<var>
@datarockstar20306 and @leonhard.wettengmx.n it is possible to make a solution with a pop, but it involve you use a range, rather then for charac in voweled:, plus, you would need a while loop (to remove one or more vowels if there are two or more vowels in a row), which will cause a index error if you have two vowels in a row, so you would need a try except to catch the index error. So yes, i can post the solution, but datarockstar is still working on the problem, so, no fun just getting the program. Datarockstar, i don't recommend the pop method, it is quit complicated
I have a different code but similar issue.
vowel = 'aeiouAEIOU'
x = list(vowel)
def anti_vowel(text):
y = list(text)
for i in y:
if i in x:
y.remove(i)
return ''.join(y)
print anti_vowel("Hey look Words!")
It keeps returning "Hy lk Words!". What should I fix in my code? I can't seem to fix it...
Did you read my answer? remove and pop are very similar, it is really difficult to pull this off. you would first off need a try except to catch your indexerror you are going to get:
def anti_vowel(text):
y = list(text)
try:
for i in y:
if i in x:
y.remove(i)
return ''.join(y)
except IndexError:
return ''.join(y)
then, you would really need to use numbers rather then letters, otherwise you are never going to get there:
def anti_vowel(text):
y = list(text)
try:
for i in range(0,len(y)):
if y[i] in x:
y.remove(y[i])
return ''.join(y)
except IndexError:
return ''.join(y)
then you would need to construct a while loop rather then a if statement to catch any two consecutive (or more) vowels. Which is really tricky, it is much easier to just append all consonants to a list
@janey_lee,You are making the same mistakeas mentioned in the prior Posts.As you use the remove() Method on the underlying-list of your FOR-IN loop.
You are disrupting the =internal index-count= of the FOR-IN loop.
Have a look at the length of y ( 12 )and the count of the iteration ( 7 )and the count of the found ( 5 )
def anti_vowel(text):
vowel = 'aeiouAEIOU'
x = list(vowel)
y = list(text)
y_count = 0
f_count = 0
txt_len = str(len(y))
for i in y:
y_count += 1
print "======="+txt_len
print i + " y-count-" + str(y_count)
if i in x:
f_count += 1
print str(f_count) +"-Found " + i
print y
y.remove(i)
print y
return ''.join(y)
#print anti_vowel("Hey look Words!")
print anti_vowel("!aeiouAEIOU!")
Thank you, I don't completely understand the issue other than it's really hard to do this with remove or pop...but I tried with a different code and it seems to work fine in codecademy lab but not in the actual anti_vowel lesson window.
Oops, hit reply too soon, here's the new code:
vowel = 'aeiouAEIOU'
p = []
def anti_vowel(text):
for character in text:
if character not in vowel:
p.append(character)
return ''.join(p)
print anti_vowel ('Hey look Words!')
Error Msg in the lesson window: Your function fails on anti_vowel("Hey look Words!"). It returns "Hy lk Wrds!bcdHy lk Wrds!" when it should return "Hy lk Wrds!".
@janey_lee,
As Python is strongly dependend on the proper indentationyou will have to re-edit your Post.....
indentation
Please re-edit your Post
Your code will then be in a pre-code stateand you will be able to make/present the proper indentations.
or even better use=[extra's]
It could also be.... ++++ reset of session ****************
@leonhard.wettengmx.n, i formatted the code, i also get an error message, but the output looks good, any idea? | https://discuss.codecademy.com/t/anti-vowel/26798/12 | CC-MAIN-2017-22 | refinedweb | 944 | 70.43 |
dirent.h - format of directory entries
#include <dirent.h>
The internal format of directories is unspecified.
The <dirent.h> header shall define the following type:
- DIR
- A type representing a directory stream.
It shall also define the structure dirent which shall include the following members:[XSI]
ino_t d_ino File serial number.ino_t d_ino File serial number.
char d_name[] Name of entry.char d_name[] Name of entry.
[XSI]
The type ino_t shall be defined as described in <sys/types.h> *); [TSF]
int readdir_r(DIR *restrict, struct dirent *restrict, struct dirent **restrict);int readdir_r(DIR *restrict, struct dirent *restrict, struct dirent **restrict);
void rewinddir(DIR *); [XSI]void rewinddir(DIR *); [XSI]
void seekdir(DIR *, long); long telldir(DIR *);void seekdir(DIR *, long); long telldir(DIR *);
None..
None.
<sys/types.h>, the System Interfaces volume of IEEE Std 1003.1-2001, closedir(), opendir(), readdir(), readdir_r(), rewinddir(), seekdir(), telldir()
First released in Issue 2.
The DESCRIPTION is updated for alignment with the POSIX Threads Extension.
The Open Group Corrigendum U026/7 is applied, correcting the prototype for readdir_r().
The restrict keyword is added to the prototype for readdir_r(). | http://www.opengroup.org/onlinepubs/009695399/basedefs/dirent.h.html | crawl-002 | refinedweb | 183 | 59.9 |
1. A little about Eclipse
Eclipse has been around for years now as an extremely popular IDE for multiple programming languages. With its excellent plugin based architecture, Eclipse is quite a good tool to ease the development tasks. To be the most utilized IDE in today’s world, it takes a lot of efforts and tools. Eclipse is a combination of numerous plugins put together for the same purpose. In this tutorial, I would cover the major pre-packaged components of the Eclipse User Interface and help you get started with using Eclipse as an IDE.
Table Of Contents
- 1. A little about Eclipse
- 2. Installing Eclipse
- 3. Welcome to Eclipse IDE
- 3.1. Important terminologies for Eclipse
- 3.2 Eclipse User Interface
- 3.3 Creating first project
- 3.4 Modifying files and running the project
- 3.5 Debugging an application in Eclipse
- 3.6 Customising and Extending the abilities of Eclipse
- 3.7 Switching Eclipse Perspective
- 3.8 Save custom perspective
- 3.9 Various Explorers for Files
- 3.10 Search Functionality in Eclipse
- 3.11 Managing Working Sets
- 3.12 Managing Code Templates
- 3.13 Creating new code templates
- 3.14 Refactoring
- 4. Conclusion
2. Installing Eclipse
2.1 Prerequisites
The latest Eclipse IDE installer requires Java version 8 or later installed on your system. Hence, it is a pre-requisite to setup Java 8 or later before getting started with installation.
2.2 Installing Eclipse
Installing Eclipse has got quite simple these days with a single setup file irrespective of the programming language you are interested in. As you would see further, the setup when executed, it allows you to choose the IDE version that you need depending on your choice for programming language. Once selected, it takes care of the rest. To download the eclipse installer, head over to this link.
Once the setup has been download, execute the file. The setup process is almost similar for all the operating systems. Hence, I would cover the same using Mac OS here. On opening up the setup, it was show options for variable available Eclipse IDE. Choose the Java IDE as shown below.
3. Welcome to Eclipse IDE
Once installed, it’s time to get started using Eclipse IDE. There is a potential challenge that you might face while trying to run Eclipse. This challenge is an error showing Unable to start Java Virtual Machine. If at all you encounter such an error, there are two possible reasons for the same:
- Missing Java Home Environment variable: If you installed JDK/JRE using portable versions of the same, there are chances that you missed to declare JAVA_HOME environment variable. Eclipse is not able to find JVM because of this reason.
- Missing JDK/JRE: To check whether JRE or JDK is installed on your system, simply open up terminal/command prompt and enter
java -version. If the JDK/JRE is installed, the corresponding version will be displayed. If the version shows up, then Eclipse probably did not find it.
Ultimately, there is a common solution to it. The solution is too add the path to the VM in eclipse.ini file. Once added, Eclipse will income JVM from the mentioned path. The file can be found in different ways in Mac OS and Linux or Windows.
In case of MacOS, generally you won’t need to do this. However, if required, you could open up the Eclipse.app package and navigate to Contents->Eclipse->eclipse.ini.
In case of Linux or Windows OS, the file could be found in the installation directly of Eclipse easily.
The VM path can be added in the first two lines as shown below:
eclipse.ini
-vm /usr/bin/ -startup ../Eclipse/plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar --launcher.library ../Eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.550.v20170928-1359 -product org.eclipse.epp.package.jee.product -showsplash org.eclipse.epp.package.common --launcher.defaultAction openFile --launcher.defaultAction openFile --launcher.appendVmargs -vmargs -Dosgi.requiredJavaVersion=1.8 -Dosgi.instance.area.default=@user.home/eclipse-workspace -XX:+UseG1GC -XX:+UseStringDeduplication --add-modules=ALL-SYSTEM -XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts -Dosgi.requiredJavaVersion=1.8 -Xms256m -Xmx1024m --add-modules=ALL-SYSTEM -Xdock:icon=../Resources/Eclipse.icns -XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts
Alright, now that you’ve got Eclipse started. Let us proceed to understand about the Eclipse Terminologies and User Interface.
3.1 Important terminologies for Eclipse
Before proceeding to the understanding of Eclipse user Interface, it is important to understand a few terms related to Eclipse that we would be using day-in day-out.
Workspace: As soon as you launch eclipse, it asks you to select a workspace unless you mark the checkout “Do not ask again” in the selection window. A workspace in Eclipse is the location where all the projects and files being created will be stored. Thus, we can call workspace to be a collection of projects grouped into a folder.
Views: Every small and big window in Eclipse is a view. Eclipse allows you to customize the size and position of every view as per your requirement.
Perspective: Eclipse has a smart grouping of windows as required for every purpose. Eclipse uses the term Perspective for the same. A perspective is available for almost every purpose, for instance, Java, Debug, Java EE, Javascript, Plug-in Development and others. It is also possible to customize each of these as per user’s need.
Action Set: Eclipse displays set of buttons in the form of toolbar. The collection of such buttons for an action set. Each action, for instance, run a program, debug, search and others, have their set of buttons defined. These sets can be moved along the toolbar and arranged as per user convenience.
Plugin: Eclipse is popular for its plug-in based architecture. Eclipse can be extended with a set of plug-ins available easily in the market. These plugin sit in the eclipse directory and provide support within the Eclipse UI. For instance, a versioning extension EGit can be added to Eclipse to enable easy file versioning within Eclipse itself. Such extensions are known as plugins.
3.2 Eclipse User Interface
On opening up Eclipse IDE for the first time, you would be asked to select a workspace location. Choose a convenient folder to store your projects. It can be changed later if needed. Once the workspace location is selected, click OK and Eclipse would take a while to get started. Once started, you should see a welcome screen as shown below.
It present you with certain good links to get started. However, we would right away proceed to get acquainted with the user interface. On clicking the x icon on the Welcome tab, it would close the tab. You should be able to see the screen below given that you have installed Java IDE.
There are some group of buttons annotated with colorful rectangles. They will be discussed further in the article. However, prior to that let us understand how Eclipse is structured.
Eclipse user interface contains multiple tabbed windows with the application window. Each tab is called view. A collection of views form a perspective. Eclipse IDE supports any numbers of perspectives as per your need. You could configure the tabs to be shown or hidden based on the perspective selection. To show a particular view, you need to navigate to Window -> Show View and then choose the window you would like to see. For instance, let us select Console. A console tab shows up as shown below.
In order to save the perspective, simply navigate to Window -> Perspective -> Save Perspective. In case you do not wish to play with default perspectives, you could choose Save Perspective As and create a custom perspective for your use.
Moving further, lets discuss about what those group of buttons are and how do we manage them.
- Red box: The buttons enclosed in red are the file menu options. It allows you to performs operations like New File, New Project, Save file & Save all. Eclipse has an elaborate list of project and file types predefined to provide you with basic templates of the relevant files.
- Green box: The green box encloses the buttons related to code debug. The first button in the box allows to open the console to check logs for application debugs. The second button allows to skip the breakpoints during debug. Rest of the button form the set of play, pause and other related debug features like skipping to cursor, moving to next statement or moving into a statement.
- Yellow box: The yellow box encloses buttons related to running the code in various modes. Eclipse IDE supports execution of code in multiple modes namely Debug Mode, Normal run, Profiler mode and Custom mode.
- Blue box: The blue box encloses the buttons used to move the cursor logically forward or backward. For instance, eclipse provides link to files in Java classes. When we press Ctrl+ Click on the classname, eclipse automatically takes us to the class. Now suppose we wish to return back to the actual position from where the click took place, the back button here would help. Similarly, the forward button takes to the next position where the cursor was.
These set of buttons could be easily moved around and placed in an order as per your preference. It is also possible to add other set of buttons as required. This shall be discussed in the further sections
3.3 Creating first project
Here we would proceed with a sample Java application to understand the creation of projects in Eclipse. To create first project in Eclipse, go to the File->New menu(Shortcut: Cmd/Ctrl+N) or press the down arrow in the first button in the set of buttons. This will open up a list of project types that could be created.
Depending upon your usage these options dynamically keep changing. Let us select Other and choose Java Project from the window that opens up.
The next window that opens up will ask you to input the project name and choose the JRE to be used for the particular java project. Click Next and in the next window click Finish. The first project has been created successfully. Let us proceed with the creation of a demo Java file.
Open up the project and select the src folder shown in the project. This is a default folder that gets created. Now, right click the folder and navigate to New -> Class file. This will open up a small window and ask for the classname, package and superclasses. There are also some other options to generate code based on template. Check the first checkbox as shown in figure below to generate the main function. Keep the package and class name as shown in image below to keep up with this tutorial.
On clicking Finish, you would be able to see that eclipse automatically creates the package directory as mentioned in the above image and a java file with some basic code in it including the
public static void main function. In this manner, whenever you create a specific type of file, Eclipse IDE tries to provide certain amount of template code for you to start with. To understand this better, let us create an HTML file in the same way.
On creation of HTML file, you would be able to see that the HTML file contains a template code as shown in image above. This is not really a relevant file. Hence, let us now delete it. To delete the file, there are two possible ways:
- Right click the file and choose to delete the file.
- Select the file and press delete on your keyboard – Does not work on Macbook due to lack of Backspace
3.4 Modifying files and running the project
Now, let us proceed with putting in some code into the created Java file. Copy the below code and paste it into the Java file created by you.
FirstClass.java
package com.javacodegeeks; public class FirstClass { public static void main(String[] args) { System.out.println("Hello There! Welcome to JavaCodeGeeks") } }
The code below contains a minor error of a missing semicolon in the code. Hence, when you paste the code in your java file, you would be seeing a red mark on the line containing the error. To know more about the error, simply click on the red cross shown on the left side of editor window. A tooltip will show up as shown below.
To resolve the error, simply put a semicolon at the end of the statement. This should resolve the error. Once you put the semicolon, you should see the Save buttons shine out indicating that there are unsaved files. Moreover, the package explorer also shows a * on the file.
The red mark on the file does not go off until the file has been saved. To save the file, click the second icon or the third icon. The second icon basically saves just the file(Shortcut: Cmd/Ctrl + S) which is selected while the third icon does the job of saving all the files(Shortcut: Cmd/Ctrl + Shift + S). On saving the file, Eclipse automatically compiles the file and checks for any possible errors. Let us now run the project. There are several ways to run the file. However, for this tutorial, we’ll keep it simple. We’ll be using the green coloured button which appears similar to a play button.
Press the icon to run the file. You should be able to see the console window with the output
Hello There! Welcome to JavaCodeGeeks. With this, you have your first application running successfully.
3.5 Debugging an application in Eclipse
This is an important process for every developer creating lengthy codes. Eclipse IDE allows you to debug the code line by line.
In order to understand debug better, we will create one more class with the code shown below. We would also explore an excellent feature that Eclipse IDE provides. While typing the below code, type syso and press Ctrl+Space. Eclipse will generate list of suggestion that you would like to do. Just double click sysout and you will see Eclipse IDE automatically generates the code for it. This feature comes in handy when one needs to code at a rapid pace.
SecondClass.java
package com.javacodegeeks; public class SecondClass { public void sayHello() { System.out.println("Hello from Second Class"); } }
Now, modify the first java file as shown below:
FirstClass.java
package com.javacodegeeks; public class FirstClass { public static void main(String[] args) { System.out.println("Hello There! Welcome to JavaCodeGeeks"); SecondClass s = new SecondClass(); s.sayHello(); } }
The code basically calls the function
sayHello from the class
SecondClass. We would add a debug point to the statement
SecondClass s = new SecondClass();. To add a breakpoint, simply double click the line number on the left side. It should show a small blue dot indicating a debug point. Now, click the bug icon just to the left of the Run button used before. Eclipse will ask whether you wish to open a Debug Perspective. As discussed earlier, Eclipse has a predefined set of windows for every task. Hence, it automatically asks whether you would like to open the Debug related windows. Click Yes and you should be able to see the line with debug point highlighted.
To move to the next line, there are two ways.
- Click the icon marked with Blue box in image below.
- Use the default shortcut key – F6
This will take you to the next line. Now, you are at the line where the function from
SecondClass is called. It is possible to go into the function using the icon marked using red box or using the shortcut key F5. Try to Step into the call and you will be taken directly to the first line in the function. At any point of time, you can get the code to run until next breakpoint by pressing the green play button to the left of these buttons. To stop the debugging and execution of the code altogether, you could use the red button similar to a stop icon.
3.6 Customising and Extending the abilities of Eclipse
Eclipse has no limit to its capabilities. New functionalities can easily be added using Eclipse plugins and the UI can be easily configured to suit your requirements. To customise the visual appearance, you could easily drag the windows around, add windows or remove as needed. It is also possible to customise the set of buttons that show up in the top bar.
To add some more button sets to the toolset as per your need, navigate to Window -> Perspective -> Customize Perspective. It should open up a window as shown below. You could select various toolbars and features to display in the toolbar as per your need.
In order to extend the abilities of Eclipse, it is possible to install extensions or plugins using various update sites and also the market place. Eclipse has an elaborate list of extensions that can be installed. You could checkout the Eclipse plugin marketplace here. In order to understand how to install extensions to Eclipse, checkout the Section 2 of this article.
3.7 Switching Eclipse Perspective
As discussed in the terminologies, it is easily possible to switch between different perspectives. After the debug in the previous section, your Eclipse windows should be appearing quite disarranged. To get them into order for development, you need to switch to Java perspective back again. This can be done in two ways.
- Look for an icon on the top right corner of the Eclipse. One of them should have a tooltip Java. Click the button to switch back to Java perspective.
- In case you are unable to find the button, you could navigate to Window ->Perspective -> Open Perspective -> Java
3.8 Save custom perspective
You would have noticed that there are certain windows like Tasks, Outline or Problems windows which you might not use frequently. Thus, you would prefer not to see them in the Java perspective. This is possible by overwriting the Java perspective. To do so, close the windows which appear to be extra.
Once you have closed the unnecessary windows, navigate to Window -> Perspective -> Save Perspective as.
Enter Java when prompted for the perspective name. This will generate a warning confirming whether you wish to overwrite the current settings of the perspective. On confirming, the Java perspective gets overwritten. This can be verified by switching the perspective to debug and switching back to Java.
3.9 Various Explorers for Files
Eclipse provides 3 different explorers to view the files and folder structure in different ways. The explorers are:
- Project Explorer
- Package Explorer
- Navigator
Project Explorer displays the project specific view. It varies depending on the project type. Currently for Java Project, you would find project and package explorer to be quite similar. It is only project specific items that get added to Project Explorer as the projects change.
Navigator is a detailed view of the complete workspace directly. Navigator view displays every folder in the directory separately.
3.10 Search Functionality in Eclipse
Eclipse also provides a diverse search functionality with a bunch of filtering options. The image below shows the search window that can be opened by clicking the small rocket like icon on the toolbar.
The first type, Remote Search, is used to find a specific word from any file in the selected folder. Eclipse is able to read every plain text as well as binary file and look for the specific word in those files.
The second type, File Search, is dedicated to search specific text or pattern from the files in the workspace or working set.
The third type, Task Search, is used to find a task with specific ID and user relation with the task. It is possible to select the user relation among Owner, Reporter, Cc, Comments or a QA contact.
The next search, Git Search, is specific to search file content in Git repository.
The next search type, Java Search, is the most important for Java developers. It has an extensive list of filters which allow you to select what exactly do you wish to find – Method, object, class, field and others.
The sixth type, Javascript search, is quite similar to Java search discussed above. It automatically filters the files to check only for JS files.
The last type of search is the Plugin Search. As discussed in the terminology section, eclipse allows you to have plugins. With this type of search you could manage to search for plugins within the workspace or working set.
3.11 Managing Working Sets
A workset in Eclipse is the set of projects in the project that you wish to work with at any point of time. Generally, when you build an enterprise level web application, you distribute the files across multiple projects to modularize it as per the functionality. The image below shows a bunch of projects in the workspace. These are just copies of the first project created to demonstrate Working Set management.
Managing working set is basically limiting the number of projects that are being shown in the explorer. It also allows you to deploy a selected set of projects when creating web applications. In order to manage the working set, click the small downward arrow annotated with a red circle in the image below. In the pop-down menu that opens up, click Select Working Set. It should open up a small window asking for the type of working set. In order to manage the list of project, select Selected working set and click the New button. In case you had any previous working set created, they should be pre-listed in the white box.
In the New Window, depending upon your type of projects, you could select the Type of working set you need. Here we would proceed by selecting Java.
Now, you would be able to see a list of Java projects on the left hand side. Select the projects you wish to see when this working set is active. After selecting the project, click Add to move the projects to the right and click Finish.
Once done, you should be able to see just 4 projects or the selected projects in the package explorer window. This can be changed by repressing the down pointing arrow and clicking Deselect Working Set as shown in image below. You can also create different working sets and select another as and when required.
3.12 Managing Code Templates
Code templating is one of the amazing features that Eclipse provides. To try it out, in your class, just type main and press Ctrl+Space. This is a default shortcut for getting suggestions for auto complete. You should see a suggestion main method as shown in the image below.
On double clicking the suggestion, it would automatically create the code shown in the grey box above. This is made possible by Code templates. To find out the code templates and create some of your own, navigate to Eclipse -> Preferences in case of MacOS. For Windows & Linux, you should find the Preferences menu link in the Window menu. It opens up a preferences window. In the search box on the left, type Template as shown below.
As you select Code Templates for a specific language (selected for Javascript as shown above), you should be able to find code templates here. However, there is one more section containing some default code templates. This section is the Editor->Templates section for every language listed in preferences. As it can be clearly seen, the main method is available in this list of templates. It can be easily edited by double clicking on the same. For instance, I have edited the method template as shown below.
The same could be verified by checking the suggestion box in the editor again as discussed above.
3.13 Creating new code templates
In large scale projects, developers often waste time in writing few lines of code that are common in each method. To avoid this, Eclipse allow you to create pre-defined code templates that can be created and saved with an alias. For instance, let us create a method that prints some log at the starting and end of method.
- Click new in the window shown above. It will open up a dialog box as shown below.
Fill in the details as shown in the image above. Here ${return_type} & ${field} are variables. They will be used to simplify method creation as shown further.
- Click OK, press Apply & Close in the parent window. Now, in the Eclipse editor window, type
mymethodand press Ctrl+Space to use Content assist for applying the method template
- On pressing the shortcut combination, you should be able to see the suggestion as shown below.
- Double click the suggestion highlighted above. It will generate the code as shown in the window above. There will be borders surrounding
return_typeand
field. The cursor should automatically be present at the
return_type. Update the return type as per your need and press Tab. On pressing the tab key, the cursor shifts to the next box,
field. Now, as you change the method name, you would see that the same is impacted in the
System.outstatements also where the
fieldvariable name is used. In this manner, a method with two logging statements is created by just few clicks.
3.14 Refactoring
Refactoring is an extremely important feature of Eclipse. In a large project, when you plan to change the name of a variable, method or a class, there are numerous places where the changes might be required. It is not an easy task to find and replace each occurrence of the keyword. Find and Replace all feature does solve the issue sometimes. However, it is not able to distinguish between words containing similar text. With refactor, it is possible to automatically replace all the occurrences within the context of that keyword.
To refactor a variable, method or class name, simply select the word and click Ctrl/Cmd+Alt + R. Now, just like the boxes in the above method stub generation, you would see bordered boxes around the word wherever it is present. Just change the word to something different. It will replace the change on every occurrence.
4. Conclusion
The article has elaborately discussed the basic operations you would need to do in Eclipse. However, this is not the end. There are numerous features of Eclipse you could explore and several extensions that would make your life easier while coding. Eclipse by far has kept up the pace with the technologies and hence it is the best choice for an open-source IDE with its extensive plugin library and customizable interface.
Hi,
This is much-needed information for every java learner, I found that installing Eclipse IDE is pretty much easy. Thanks. | https://www.javacodegeeks.com/2018/04/eclipse-ide-tutorial.html | CC-MAIN-2022-40 | refinedweb | 4,489 | 66.23 |
Webpack is an open source JavaScript framework especially for module bundling, in short Webpack is a module bundler. When working with web application project you would be creating lots of JavaScript(.js) files, CSharp(.cs) files, html files and images files like jpg, png etc. And in project these created files may be dependent on each other to complete project task.With many such small individual dependent components or files with which a web application is composed of we cannot go on server to publish web application. It will lead to handling issue with all individual files or components when hosting on server. In order to get rid of it Webpackis one of the solutions for it where all the individual dependent files are bundled together. These bundling are done by looking at dependencies of files on each other and Webpack creates static asset out of it which avoids rather than dealing with many files with a single bundle.
Let us try to understand with the help of small practical example and its demonstration. Consider the following image where we have Customer.js, Address.js and Phone.js. Here Customer can have multiple addresses, Customer’s addresses can have multiple Phone numbers so in short Customer is dependent on Address and Address is dependent on Phone.
Now all these single Customer.js, Address.js and Phone.js file will be bundled into single file using Webpack. Before bundling it Webpack will check for dependencies and then bundling will be done accordingly.
In order to do this practical sample we have used Visual Studio Code in this article. For that go the project folder and then open three new notepads save it withTypeScript(.ts) extension with name Customer.ts, Address.ts and Phone.ts. Now open each .ts file one by one and write the below mentioned code respective in each .ts file.
import {Address} from "./Address"
class Customer{
a: Address = new Address();
Addresses: Array = new Array();
}
First line of the code is to get“Address” file which is available in the project folder. Next is to create class “Customer” and first create variable “a” and then under it create Array “Address” to store multiple addresses.
import {Phone} from "./Phone"
export class Address{
b: Phone = new Phone();
Phones: Array = new Array();
}
export class Phone{
}
Once the (.ts)files are created next is to Build the project at the end this TypeScript(.ts) will converted to JavaScript (.js). To “Build” the project, press “ctrl+shift+B” on the keyboard. If you see this mark “/” at the bottom revolving then it means project “Build” is processing as shown in the image below.
Or in case if you see error on top of “No task runner configured” when clicked on ctrl+shift+B then configure it by clicking on the button “Configure Task Runner” available at the right as shown in the image down below
Select Task Runner as “Grunt” which will create .vscode folder under that tasks.json file will be created.
Next is to configure “tasks.json” fileby doing the following changes into it so that it can be used to “Build” the project.
{
// See
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "grunt",
"isShellCommand": true,
"args": ["—no-color"],
"showOutput": "always"
}
{
// See
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-p","."],
"showOutput": "silent",
"problemMatcher": "$tsc"
}
After “tasks.json” file is configured you will now be able to “Build” the project.
After successful “Build” is created it means that project is running proper at the client side. And also it will create .js and .map file for each .ts file within “wwwroot” folder. So three simple files now have created after compiling six more files. If these project files now gets published or hosted on the server directly will have to work individually on each files as each of them are dependent on each other. This will lead to huge file management issue to tackle this situation. It would be very much helpful if all these individual files gets single bundled which exactly Webpack does for us.
As the name says Webpack,it packs alllogically dependent multiple web files into single bundled JavaScript file under the web development environment. So the next question arises that how does Webpack comes to know about which files is dependent on whom? Dependency of the modules can be defined by any JavaScript modular specification like common.js, (Asynchronous Module Definition)AMD or (Universal Module Definition)UMD.
Here inorderto identify the dependencies we have used common.js specification in our project. This common.js specification gets available in the .js file which is generated when compilation of .ts file is done along with .map file.If you browse folderwise, then this .js file is located in the project folder of “Webpack”. So the path to get this file is Webpack > wwwroot > compiled-js.
Similarly under VS code you can get these .js files just by expanding the project folder. When these .js files are opened under VS code you will find two keywords “exports”and “require” and by looking at these keywords Webpack decide dependencies where “export” is exportsvariable and “require” is used by the consuming class. When Webpack works it checks for the first file on the web page which gets loaded which is “Customer.js” and internally it is dependent on “Address.js” and finally when Webpack goes to “Address.js” it is gets “require” keyword which means it dependent on “Phone.js” as shown in the image down below. In this way dependencies are identified by Webpack and then one bundled .js file is created.
Installing Webpack is also going to be same likewise we do installation. Let us repeat incase if you do not remember go to Start Menu program search for “node.js” and click on “Node.js command prompt” as shown in the image down below. Once clicked on it will open command prompt window on that type the following command “npm install –g webpack” with this installation process of Webpack will initiate and complete the installation successfully.
After the Webpack is installed next step is to create a single bundle pack of three interdependent .js file.
For that on the command prompt change default path “c:” to project path “e:” here is the complete link of the path with the command to change drive
“cd E:\Webpack\Webpack\wwwroot\compiled-js”
Once the path is changed next we have to give the starting .js file name i.e. “Customer.js” with which Webpack can go and start identifying the dependencies on the basis of “require” and “export”. To create single bundle file from individual .js file, here is the command
“webpack "Customer.js" "SingleBundle.js"”
Where “Customer.js” is the starting .js file where “Webpack” will start with and the name of the single generated .js file by Webpack is “SingleBundle.js”.
After the command is written press enter and wait for a while till the time Webpack complete its work of converting individual .js file to single bundle .js file. Once Webpack completes its execution you will see the successful message on command prompt as shown in the image down below.
You can also go and check it under VS code for newly created .js file with name “SingleBundle.js”.
Please note: If you do not see newly created .js file then click on refresh to see the file under Explorer
After you click on the single bundle file which we have named “SingleBundle.js” under this you will see all the three individual files bundled together as shown in the image down below.
By doing this with single bundling all the files our deployment life becomes very easy.
Webpack production is also done in similar way just by using text in the command with “–p” after writing webpack keyword then followed by first name of individual .js file i.e. “Customer.js” with which Webpack will start bundling file following dependency of each file and create bundle with name “SingleBundle.js”.
Now under VS code if you see then you will find that “SingleBundle.js” is compressed by removing all comments and other not necessary part from it. And by looking to the following image you will find that file is compressed and only the important required part for the production is now available.
In real world projects are not going to simpler there would be many modules under one project. Then how to handle such situation where we have multiple modules consider the following scenario diagram where we have two modules one is of “Customer” and while other is “Invoice” module. And also their bundling needs to be done separately for both”.
Below is the image screenshot which shows two modules Customer Module and Invoice Module, each module has individual .js also they dependency on each other.
Next using Webpackwe will create two separate bundles one named “CustomerBundle.js” and other bundle is named as “InvoiceBundle.js. So how to create two separate bundles for each module in a single command of “webpack” on command prompt.
Answer to this is by creating config.json file with which we can resolve this issue. Below is the image which shows config file created for two bundles with name “webpack.config.json” in the project folder.
There are three parameters which need to be set for each bundle. First provide “name”, then “entry” location where the .js file is located and finally “output” where we have to give suitable file name to the bundle.
Once the config file is created now it will be very easy to create two separate bundle files using Webpack. Same steps we have to follow as we did earlier to create bundle. Go to node.js command prompt and execute the “webpack.config.json” file from the project folder where this .json file is created and saved.
Following is the command which will be used on command prompt and press enter
E:\Webpack\Webpack>webpack
After the command is executed you will see two separate bundles created one for “CustomerBundle.js” and other is “InvoiceBundle.js”. Under “CustomerBundle.js” it will have “Address.js”, “Phone.js” and “Customer.js” individual files. While under “InvoiceBundle.js” it will bundle “InvoiceItem.js”, “Tax.js”, and “Invoice.js”.
With the help of Webpackworking on module approach to create bundle makes life very easy to go to production.
Hope that above article on Webpack is clearly understood by the reader. Suggesting reader if you are new learner then go through below video on step by step Angular2: -
Latest Articles
Latest Articles from Ahteshamax
Login to post response | http://www.dotnetfunda.com/articles/show/3481/webpack-in-angular2 | CC-MAIN-2018-22 | refinedweb | 1,781 | 67.25 |
Red Hat Bugzilla – Bug 428384
mkmf.rb requires libruby-static.a
Last modified: 2010-01-13 20:25:28 EST
Description of problem:
The mkmf.rb always requires libruby-static.a to do
"have_library("libname"), but it fails because ruby-devel
packages does NOT have libruby-static.a.
Version-Release number of selected component (if applicable):
ruby-1.8.6.111-3
How reproducible:
$ sudo yum install ruby ruby-devel rpm-devel db4-devel popt-devel
$ rpm -i /path/to/ruby-rpm-1.2.3-3.fc9.src.rpm
$ rpmbuild -bb /path/to/src/rpm/SPECS/ruby-rpm.spec
Actual results:
BUILD/ruby-rpm-1.2.3/ext/rpm/mkmf.log said:
have_header: checking for popt.h... -------------------- yes
"gcc -E -I/usr/lib/ruby/1.8/i386-linux-gnu -I/usr/lib/ruby/1.8/i386-linux-gnu
-I/usr/inclu
de/rpm -O0 -g -pipe -m32 -march=i386 -mtune=pentium4 -Wall -fPIC conftest.c
-o conftest
.i"
checked program was:
/* begin */
#include <popt.h>
/* end */
--------------------
have_library: checking for main() in -lpopt... -------------------- no
() { main(); return 0; }
/* end */
() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
/* end */
--------------------
reverted the change in 1.8.6.111-7.fc9. libruby-static.a is back now.
Changing version to '9' as part of upcoming Fedora 9 GA.
More information and reason for this action is here:
In that case, the link against static ruby is checked when -lpopt
is checked, however it is not used for the final link. So this
approach seems buggy to me. In my opinion have_library should be
more clever and try the link with shared libs only before trying with
static libs. Or, alternatively, in fedora, #$LIBRUBYARG_STATIC
should be removed from Config::CONFIG in link_command.
This package has changed ownership in the Fedora Package Database. Reassigning to the new owner of this component.
For ruby-1.9.1, I'm thinking about shipping the static library in a -static subpackage to comply with packaging guidelines, would that help?
That's the objective, but as long as the issue I explained (maybe confusingly) in Comment #3 is still there, it cannot be done. Or the -devel package should require the static subpackage.
(In reply to comment #6)
> It cannot be done, or the -devel package should
> require the static subpackage.
That's what I've done ;-)
(In reply to comment #7)
> (In reply to comment #6)
> > It cannot be done, or the -devel package should
> > require the static subpackage.
>
> That's what I've done ;-)
In that case we don't gain much. The bug in linking command issued should be fixed such that the static library is never used in the rebased to rawhide, assuming, from the comments that the issue wasn't fixed.
This bug appears to have been reported against 'rawhide' during the Fedora 12 development cycle.
Changing version to '12'.
More information and reason for this action is here:
*** Bug 545548 has been marked as a duplicate of this bug. ***
The problem is that as Patrice said in comment 3, when trying
$ ruby -e "require 'mkmf' ; have_library 'z'"
link_command() (called by have_library() in the end) always tries
to use libruby-static.a as:
========================================================
268 def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
269 conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote,
270 'src' => CONFTEST_C,
271 'INCFLAGS' => $INCFLAGS,
272 'CPPFLAGS' => $CPPFLAGS,
273 'CFLAGS' => "#$CFLAGS",
274 'ARCH_FLAG' => "#$ARCH_FLAG",
275 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
276 'LIBPATH' => libpathflag(libpath),
277 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
278 'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS")
279 Config::expand(TRY_LINK.dup, conf)
280 end
========================================================
This should be okay with LIBRUBYARG_SHARED. Note that
changing to LIBRUBYARG_SHARED requires some more hacks when building
ruby itself.
Modified on 1.8.6.383-5
Once closing as the last modification seems to be working.
ruby-1.8.6.383-6.fc12 has been pushed to the Fedora 12 stable repository. If problems still persist, please make note of it in this bug report.
ruby-1.8.6.383-6.fc11 has been pushed to the Fedora 11 stable repository. If problems still persist, please make note of it in this bug report. | https://bugzilla.redhat.com/show_bug.cgi?id=428384 | CC-MAIN-2016-22 | refinedweb | 677 | 58.99 |
SystemUiProgressState
Since: BlackBerry 10.0.0
#include <bb/system/SystemUiProgressState>
To link against this class, add the following line to your .pro file: LIBS += -lbbsystem
The possible states the progress of a task can have when shown to the user.
Overview
Public Types Index
Public Types
The possible states the progress of a task can have when shown to the user.
BlackBerry 10.0.0
- Active 0
The task's progress is ongoing.
- Inactive 1
The task's progress has stopped.Since:
BlackBerry 10.0.0
- Error 2
The task whose progress is being monitored has encountered an error.Since:
BlackBerry 10.0.0
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/cascades/bb__system__systemuiprogressstate.html | CC-MAIN-2017-39 | refinedweb | 120 | 71 |
What Future for Python 2.x¶
Python 2.7 is bpo').
The
unittest module also automatically reenables deprecation warnings
when running tests.
Python 3.1 Features¶
withstatement.
-
xis shorter in many cases: it’s now based on the shortest decimal string that’s guaranteed to round back to
x. As in previous versions of Python, it’s guaranteed that
float(repr(x))recovers
x.
- Float-to-string and string-to-float conversions are correctly rounded. The
round()function is also now correctly rounded.
- The
PyCapsuletype, that causes warnings about using classic division with integers and long integers.
PEP 372: Adding an Ordered Dictionary to collections¶
ConfigParsermodule uses them by default, meaning that configuration files can now be read, modified, and then written back in their original order.
- The
_asdict()method for
collections.namedtuple()now returns an ordered dictionary with the values appearing in the same order as the underlying tuple indices.
- The
jsonmodule’s
JSONDecoderclass constructor was extended with an object_pairs_hook parameter to allow
OrderedDictinstances to be built by the decoder. Support was also added for third-party tools like PyYAML.
PEP 378: Format Specifier for Thousands Separator¶.
PEP 389: The argparse Module for Parsing Command Lines¶’sp.
PEP 391: Dictionary-Based Configuration For Logging¶. For more information see Configuration functions.': 1000000},
SysLogHandlerclass gained an
isEnabledFor()method that takes a level and returns whether the underlying logger would process a message of that level of importance.
PEP 3106: Dictionary Views¶.
PEP 3137: The memoryview Object¶') >>>
Other Language Changes¶; bpo; bpo-2333.
The
with; bpo; bpo-3166.)
Integer division is also more accurate in its rounding behaviours. (Also implemented by Mark Dickinson; bpo-1811.)
Implicit coercion for complex numbers has been removed; the interpreter will no longer ever attempt to call a
__coerce__()method on complex objects. (Removed by Meador Inge and Mark Dickinson; bpo-5211.)
The
str.format()method now supports automatic numbering of the replacement fields. This makes using
str.format()more closely resemble using
%sformatting:
>>> '{}:{}:{}'; bpooutput. (Contributed by Eric Smith; bpo-1588 and bpo-7988.)
The ‘F’ format code now always formats its output using uppercase characters, so it will now produce ‘INF’ and ‘NAN’. (Contributed by Eric Smith; bpo-3382.)
A low-level change: the
object.__format__()method now triggers a
PendingDeprecationWarningif it’s passed a format string, because the
__format__()method for
objectconverts; bpo-7994.)
The
int()and
long()types gained a
bit_lengthmethod; bpo-3439.)
The
importstatement will no longer try an absolute import if a relative import (e.g.
from .os import sep) fails. This fixes a bug, but could possibly break certain
importstatements that were only working by accident. (Fixed by Meador Inge; bpo-7902.)
It’s now possible for a subclass of the built-in
unicodetype to override the
__unicode__()method. (Implemented by Victor Stinner; bpo-1583863.)
The
bytearraytype’s
translate()method now accepts
Noneas its first argument. (Fixed by Georg Brandl; bpo-4759.)
When using
@classmethodand
@staticmethodto wrap methods as class or static methods, the wrapper object now exposes the wrapped function as their
__func__attribute. (Contributed by Amaury Forgeot d’Arc, after a suggestion by George Sakkis; bpo-5982.)
When a restricted set of attributes were set using
__slots__, deleting an unset attribute would not raise
AttributeErroras you would expect. Fixed by Benjamin Peterson; bpo bpo-1616979; CP858 contributed by Tim Hatch in bpo-8016.)
The
fileobject will now set the
filenameattribute on the
IOErrorexception when trying to open a directory on POSIX platforms (noted by Jan Kaliszewski; bpo-4764), and now explicitly checks for and forbids writing to read-only file objects instead of trusting the C library to catch and report the error (fixed by Stefan Krah; bpo; bpo-7362.)
It’s now possible to create weak references to old-style class objects. New-style classes were always weak-referenceable. (Fixed by Antoine Pitrou; bpo-8268.)
When a module object is garbage-collected, the module’s dictionary is now only cleared if no one else is holding a reference to the dictionary (bpo-7140).
Interpreter Changes¶
A new environment variable,
PYTHONWARNINGS,
allows controlling warnings. It should be set to a string
containing warning settings, equivalent to those
used with the
-W switch, separated by commas.
(Contributed by Brian Curtin; bpo-7301.)
For example, the following setting will print warnings every time
they occur, but turn warnings from the
Cookie module into an
error. (The exact syntax for setting an environment variable varies
across operating systems and shells.)
export PYTHONWARNINGS=all,error:::Cookie:0
Optimizations¶
Several performance enhancements have been added:
A new opcode was added to perform the initial setup for
withstatements,; bpo; bpo-digitsthat can be used to override this default.
Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there’s a new structseq
sys.long_infothat provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:
>>> import sys >>> sys.long_info sys.long_info(bits_per_digit=30, sizeof_digit=4)
(Contributed by Mark Dickinson; bpo-4258.)
Another set of changes made long objects a few bytes smaller: 2 bytes smaller on 32-bit systems and 6 bytes on 64-bit. (Contributed by Mark Dickinson; bpo; bpo-5512.) Bitwise operations are also significantly faster (initial patch by Gregory Smith; bpo-1087418).
The implementation of
%checks for the left-side operand being a Python string and special-cases it; this results in a 1–3% performance increase for applications that frequently use
%with strings, such as templating libraries. (Implemented by Collin Winter; bpo-5176.)
List comprehensions with an
ifcondition are compiled into faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey Yasskin; bpo-4715.)
Converting an integer or long integer to a decimal string was made faster by special-casing base 10 instead of using a generalized conversion function that supports arbitrary bases. (Patch by Gawain Bolton; bpo-6713.)
The
split(),
replace(),
rindex(),
rpartition(), and
rsplit()methods of string-like types (strings, Unicode strings, and
bytearrayobjects) now use a fast reverse-search algorithm instead of a character-by-character scan. This is sometimes faster by a factor of 10. (Added by Florent Xicluna; bpo-7462 and bpo-7622.)
The
pickleand
cPicklemodules now automatically intern the strings used for attribute names, reducing memory usage of the objects resulting from unpickling. (Contributed by Jake McGuire; bpo-5084.)
The
cPicklemodule now special-cases dictionaries, nearly halving the time required to pickle them. (Contributed by Collin Winter; bpo-5670.)
New and Improved Modules¶module’s base debugging class
Bdbgained; bpo-5142.)
The
binasciimodule now supports the buffer API, so it can be used with
memoryviewinstances and other similar buffer objects. (Backported from 3.x by Florent Xicluna; bpo-7703.)
Updated module: the
bsddbmodule; bpo-8156. The pybsddb changelog can be read at.)
The
bz2module’s
BZ2Filenow supports the context management protocol, so you can write
with bz2.BZ2File(...) as f:. (Contributed by Hagen Fürstenau; bpo-3860.)
New class: the
Counterclass in the
collectionsmodule is useful for tallying data.
Counterinstancesmethods.; bpo-1696199.
New class:
OrderedDict; bpo-1818.)
Finally, the
Mappingabstract base class now returns
NotImplementedif a mapping is compared to another type that isn’t a
Mapping. (Fixed by Daniel Stutzbach; bpo-8729.)
Constructors for the parsing classes in the
ConfigParsermodule now take; bpo-7005.)
Deprecated function:
contextlib.nested(), which allows handling more than one context manager with a single
withstatement, has been deprecated, because the
withstatement now supports multiple context managers.
The
cookielibmodule now ignores cookies that have an invalid version field, one that doesn’t contain an integer value. (Fixed by John J. Lee; bpo-3924.)
The
copymodule’s
deepcopy()function will now correctly copy bound instance methods. (Implemented by Robert Collins; bpo-1515.)
The
ctypesmodule now always converts
Noneto a C NULL pointer for arguments declared as pointers. (Changed by Thomas Heller; bpo-4606.) The underlying libffi library has been updated to version 3.0.9, containing various fixes for different platforms. (Updated by Matthias Klose; bpo-8142.)
New method: the
datetimemodule’s
timedeltaclass gained a
total_seconds()method that returns the number of seconds in the duration. (Contributed by Brian Quinlan; bpo-5788.)
New method: the
Decimalclass; bpo-4796.)
Comparing instances of
Decimal; bpo-2531.)
The constructor for
Decimalnow accepts floating-point numbers (added by Raymond Hettinger; bpo-8257) and non-European Unicode characters such as Arabic-Indic digits (contributed by Mark Dickinson; bpo-6595).
Most of the methods of the
Contextclass now accept integers as well as
Decimalinstances; the only exceptions are the
canonical()and
is_canonical()methods. (Patch by Juan José Conti; bpo-7633.)
When using
Decimalinstances with a string’s
format()method, the default alignment was previously left-alignment. This has been changed to right-alignment, which is more sensible for numeric
difflibmodule now produces output that is more compatible with modern diff/patch tools through one small change, using a tab character instead of spaces as a separator in the header giving the filename. (Fixed by Anatoly Techtonik; bpo-7585.)
The Distutils
sdistcommand now always regenerates the
MANIFESTfile, since even if the
MANIFEST.inor
setup.pyfiles haven’t been modified, the user might have created some new files that should be included. (Fixed by Tarek Ziadé; bpo-8688.)
The
doctestmodule’s
IGNORE_EXCEPTION_DETAILflag will now ignore the name of the module containing the exception being tested. (Patch by Lennart Regebro; bpo-7490.)
The
Messageclass will now accept a Unicode-valued payload, automatically converting the payload to the encoding specified by
output_charset. (Added by R. David Murray; bpo-1368247.)
The
Fractionclass now accepts a single float or
Decimalinstance, or two rational numbers, as arguments to its constructor. (Implemented by Mark Dickinson; rationals added in bpo-5812, and float/decimal in bpo-8294.)
Ordering comparisons (
<,
<=,
>,
>=) between fractions and complex numbers now raise a
TypeError. This fixes an oversight, making the
Fractionmatch the other numeric types.
New class:
FTP_TLSin the
ftplibmodule provides secure FTP connections using TLS encapsulation of authentication as well as subsequent control and data transfers. (Contributed by Giampaolo Rodola; bpo-2054.)
The
storbinary()method for binary uploads can now restart uploads thanks to an added rest parameter (patch by Pablo Mouzo; bpo-6845.)
New class decorator:
total_ordering()in the
functoolsmodule; bpomodule’s
is_tracked()returns true if a given instance is tracked by the garbage collector, false otherwise. (Contributed by Antoine Pitrou; bpo-4688.)
The
gzipmodule’s
GzipFilenow supports the context management protocol, so you can write
with gzip.GzipFile(...) as f:(contributed by Hagen Fürstenau; bpo-3860), and it now implements the
io.BufferedIOBaseABC, so you can wrap it with
io.BufferedReaderfor faster processing (contributed by Nir Aides; bpo-7471). It’s also now possible to override the modification time recorded in a gzipped file by providing an optional timestamp to the constructor. (Contributed by Jacques Frechet; bpo-4272.)
Files in gzip format can be padded with trailing zero bytes; the
gzipmodule will now consume these trailing bytes. (Fixed by Tadek Pietraszek and Brian Curtin; bpo; bpo-7418.)
The default
HTTPResponseclass used by the
httplibmodule now supports buffering, resulting in much faster reading of HTTP responses. (Contributed by Kristján Valur Jónsson; bpo-4879.)
The
HTTPConnectionand
HTTPSConnectionclasses now support a source_address parameter, a
(host, port)2-tuple giving the source address that will be used for the connection. (Contributed by Eldon Ziegler; bpo; bpo-1655.)
New function: the
inspectmodule; bpo-3135.
Updated module: The passed an invalid file descriptor. (Implemented by Benjamin Peterson; bpo-4991.) The
truncate()method now preserves the file position; previously it would change the file position to the end of the new file. (Fixed by Pascal Chambon; bpoinstances. (Implemented by Raymond Hettinger; bpo-5032.)
itertools.combinations()and
itertools.product()previously raised
ValueErrorfor values of r larger than the input iterable. This was deemed a specification error, so they now return an empty iterator. (Fixed by Raymond Hettinger; bpo-4816.)
Updated module: The
jsonmodule was upgraded to version 2.0.9 of the simplejson package, which includes a C extension that makes encoding and decoding faster. (Contributed by Bob Ippolito; bpo-4136.)
To support the new
collections.OrderedDicttype,
json.load()now has an optional object_pairs_hook parameter that will be called with any object literal that decodes to a list of pairs. (Contributed by Raymond Hettinger; bpo-5381.)
The
mailboxmodule’s
Maildirclass now records the timestamp on the directories it reads, and only re-reads them if the modification time has subsequently changed. This improves performance by avoiding unneeded directory scans. (Fixed by A.M. Kuchling and Antoine Pitrou; bpo-1607951, bpo-6896.)
New functions: the
math; bpo-3366.)
The
multiprocessingmodule’s
Manager*classes can now be passed a callable that will be called whenever a subprocess is started, along with a set of arguments that will be passed to the callable. (Contributed by lekma; bpo; bpo-6963.)
The
nntplibmodule now supports IPv6 addresses. (Contributed by Derek Morr; bpo-1664.)
New functions: the
osmodule.; bpo-6508. Support for initgroups added by Jean-Paul Calderone; bpo-7333.)
The
os.fork()function now re-initializes the import lock in the child process; this fixes problems on Solaris when
fork()is called from a thread. (Fixed by Zsolt Cserna; bpo-7242.)
In the
os.pathmodule, the
normpath()and
abspath()functions now preserve Unicode; if their input path is a Unicode string, the return value is also a Unicode string. (
normpath()fixed by Matt Giuca in bpo-5827;
abspath()fixed by Ezio Melotti in bpo-3426.)
The
pydocmodule now has help for the various symbols that Python uses. You can now do
help('<<')or
help('@'), for example. (Contributed by David Laban; bpo; bpo-6816.)
New function: in the
shutilmodule,
make_archive()takes a filename, archive type (zip or tar-format), and a directory path, and creates an archive containing the directory’s contents. (Added by Tarek Ziadé.)
shutil’s; bpo-3002.)
The
signalmodule no longer re-installs the signal handler unless this is truly necessary, which fixes a bug that could make it impossible to catch the EINTR signal robustly. (Fixed by Charles-Francois Natali; bpo-8354.)
New functions: in the
sitemodule,environment variable, giving the path to a directory that can be used to store data. (Contributed by Tarek Ziadé; bpo-6693.)
The
sitemodule now reports exceptions occurring when the
sitecustomizemodule is imported, and will no longer catch and swallow the
KeyboardInterruptexception. (Fixed by Victor Stinner; bpo-3137.)
The
create_connection()function gained a source_address parameter, a
(host, port)2-tuple giving the source address that will be used for the connection. (Contributed by Eldon Ziegler; bpo-3972.)
The
recv_into()and
recvfrom_into()methods will now write into objects that support the buffer API, most usefully the
bytearrayand
memoryviewobjects. (Implemented by Antoine Pitrou; bpo attribute can hold a timeout in seconds that will be applied to the request socket; if no request is received within that time,
handle_timeout()will be called and
handle_request()will return. (Contributed by Kristján Valur Jónsson; bpo-6192 and bpo-6267.)
Updated module: the
sqlite3modulemodule’s
SSLSocketobjects now support the buffer API, which fixed a test suite failure (fix by Antoine Pitrou; bpo-7133) and automatically set OpenSSL’s
SSL_MODE_AUTO_RETRY, which will prevent an error code being returned from
recv()operations that trigger an SSL renegotiation (fix by Antoine Pitrou; bpo-8222).
The
ssl.wrap_socket()constructor function now takes a ciphers argument that’s a string listing the encryption algorithms to be allowed; the format of the string is described in the OpenSSL documentation. (Added by Antoine Pitrou; bpo; bpo-8484.)
The version of OpenSSL being used is now available as the module attributes
ssl.OPENSSL_VERSION(a string),
ssl.OPENSSL_VERSION_INFO(a 5-tuple), and
ssl.OPENSSL_VERSION_NUMBER(an integer). (Added by Antoine Pitrou; bpo-8321.)
The
structmodule will no longer silently ignore overflow errors when a value is too large for a particular integer format code (one of
bBhHiIlLqQ); it now always raises a
struct.errorexception. (Changed by Mark Dickinson; bpo-1523.) The
pack()function will also attempt to use
__index__()to convert and pack non-integers before trying the
__int__()method or reporting an error. (Changed by Mark Dickinson; bpo bpo; bpo-8451.)
The
sys.version_infovalue is now a named tuple, with attributes named
major,
minor,
micro,
releaselevel, and
serial. (Contributed by Ross Light; bpo-4285.)
sys.getwindowsversion()also returns a named tuple, with attributes named
major,
minor,
build,
platform,
service_pack,
service_pack_major,
service_pack_minor,
suite_mask, and
product_type. (Contributed by Brian Curtin; bpo-7766.).)
tarfilenow supports filtering the
TarInfoobjects being added to a tar file. When you call
add(), you may supply an optional filter argument that’s a callable. The filter callable will be passed the
TarInfofor every file being added, and can modify and return it. If the callable returns
None, the file will be excluded from the resulting archive. This is more powerful than the existing exclude argument, which has therefore been deprecated. (Added by Lars Gustäbel; bpo-6856.) The
TarFileclass also now supports the context management protocol. (Added by Lars Gustäbel; bpo-7232.)
The
wait()method of the
threading.Eventclass now returns the internal flag on exit. This means the method will usually return true because
wait()is supposed to block until the internal flag becomes true. The return value will only be false if a timeout was provided and the operation timed out. (Contributed by Tim Lesher; bpo-1674032.)
The Unicode database provided by the
unicodedatamodule is now used internally to determine which characters are numeric, whitespace, or represent line breaks. The database also includes information from the
Unihan.txtdata file (patch by Anders Chrigström and Amaury Forgeot d’Arc; bpo-1571184) and has been updated to version 5.2.0 (updated by Florent Xicluna; bpo-8024).module also supports IPv6 literal addresses as defined by RFC 2732 (contributed by Senthil Kumaran; bpo-2987).
>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo') ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]', path='/foo', params='', query='', fragment='')
New class: the
WeakSetclass in the
weakrefmodule; bpo-2746.)
The XML-RPC client and server, provided by the
xmlrpcl; bpo-6267.)
The
zipfilemodule’s
ZipFilenow supports the context management protocol, so you can write
with zipfile.ZipFile(...) as f:. (Contributed by Brian Curtin; bpo-5511.)
zipfilenow also supports archiving empty directories and extracts them correctly. (Fixed by Kuba Wieczorek; bpo-4710.) Reading files out of an archive is faster, and interleaving
read()and
readline()now works correctly. (Contributed by Nir Aides; bpo-7610.)
The
is_zipfile()function now accepts a file object, in addition to the path names accepted in earlier versions. (Contributed by Gabriel Genellina; bpo-4756.)
The
writestr()method now has an optional compress_type parameter that lets you override the default compression method specified in the
ZipFileconstructor. (Contributed by Ronald Oussoren; bpo-6003.)
New module: importlib¶.
New module: sysconfig¶:
get_config_var()returns variables from Python’s Makefile and the
pyconfig.hfile.
get_config_vars()returns a dictionary containing all of the configuration variables.
get_path()returns the configured path for a particular type of module: the standard library, site-specific modules, platform-specific modules, etc.
is_python_build()returns true if you’re running a binary from a Python source tree, and false otherwise.tk: Themed Widgets for Tk¶
bpo-2983. An alternate version called
Tile.py, written by
Martin Franklin and maintained by Kevin Walzer, was proposed for
inclusion in bpo-2618, but the authors argued that Guilherme
Polo’s work was more comprehensive.
Updated module: unittest¶ bpo-6001.)
The
main() function supports some other new options:
-bor
--bufferwill buffer the standard output and standard error streams during each test. If the test passes, any resulting output will be discarded; on failure, the buffered output will be displayed.
-cor
--catchwill.
-for
--failfastmakes test execution stop immediately when a test fails instead of continuing to execute further tests. (Suggested by Cliff Dyer and implemented by Michael Foord; bpo-8074.)
The progress messages now show ‘x’ for expected failures and ‘u’ for unexpected successes when run in verbose mode. (Contributed by Benjamin Peterson.)
Test cases can raise the
SkipTest exception to skip a
test (bpo; bpo-5663.)
The
assertRaises() method now
returns a context handler when called without providing a callable
object to run. For example, you can write this:
with self.assertRaises(KeyError): {}['foo']
(Implemented by Antoine Pitrou; bpo
(bpo.
assertIsNone()and
assertIsNotNone()take one expression and verify that the result is or is not
None.
assertIs()and
assertIsNot()take two values and check whether the two values evaluate to the same object or not. (Added by Michael Foord; bpo-2578.)
assertIsInstance()and
assertNotIsInstance()check whether the resulting object is an instance of a particular class, or of one of a tuple of classes. (Added by Georg Brandl; bpo-7031.)
assertGreater(),
assertGreaterEqual(),
assertLess(), and
assertLessEqual()compare two quantities.
assertMultiLineEqual()compares two strings, and if they’re not equal, displays a helpful comparison that highlights the differences in the two strings. This comparison is now used by default when Unicode strings are compared with
assertEqual().
assertRegexpMatches()and
assertNotRegexpMatches()checks whether the first argument is a string matching or not matching the regular expression provided as the second argument (bpo-8038).
assertRaisesRegexp()checks whether a particular exception is raised, and then also checks that the string representation of the exception matches the provided regular expression.
assertIn()and
assertNotIn()tests whether first is or is not in second.
assertItemsEqual()tests whether two provided sequences contain the same elements.
assertSetEqual()compares whether two sets are equal, and only reports the differences between the sets in case of error.
- Similarly,
assertListEqual()and
assertTupleEqual()compare the specified types and explain any differences without necessarily printing their full values; these methods are now used by default when comparing lists and tuples using
assertEqual(). More generally,
assertSequenceEqual()compares two sequences and can optionally check whether both sequences are of a particular type.
assertDictEqual()compares two dictionaries and reports the differences; it’s now used by default when you compare two dictionaries using
assertEqual().
assertDictContainsSubset()checks whether all of the key/value pairs in first are found in second.
assertAlmostEqual()and
assertNotAlmostEqual()test whether first and second are approximately equal. This method can either round their difference to an optionally-specified number of places (the default is 7) and compare it to zero, or require the difference to be smaller than a supplied delta value.
loadTestsFromName()properly honors the
suiteClassattribute of the
TestLoader. (Fixed by Mark Roddy; bpo-6866.)
- A new hook lets you extend the
assertEqual()method to handle new data types. The
addTypeEqualityFunc()method takes a type object and a function. The function will be used when both of the objects being compared are of the specified type. This function should compare the two objects and raise an exception if they don’t match; it’s a good idea for the function to provide additional information about why the two objects aren’t matching, much as the new sequence comparison methods do.
unittest.main() now takes an optional
exit argument. If
false,
main() doesn’t call
sys.exit(), allowing
main() to be used from the interactive interpreter.
(Contributed by J. Pablo Fernández; bpo-3379.)
TestResult has new
startTestRun() and
stopTestRun() methods that are called immediately before
and after a test run. (Contributed by Robert Collins; bpo-5728.)
With all these changes, the
unittest.py was becoming awkwardly
large, so the module was turned into a package and the code split into
several files (by Benjamin Peterson). This doesn’t affect how the
module is imported or used.
See also
-
- Describes the new features, how to use them, and the rationale for various design decisions. (By Michael Foord.)
Updated module: ElementTree 1.3¶
The version of the ElementTree library included with Python was updated to version 1.3. Some of the new features are:
The various parsing functions now take a parser keyword argument giving an
XMLParser bpo-6472.)
Build and C API Changes¶
Changes to Python’s build process and to the C API include:
The latest release of the GNU Debugger, GDB 7, can be scripted using Python. When you begin debugging an executable program P, GDB will look for a file named
P-gdb.py bpo-8032.)
If you use the
.gdbinitfile provided with Python, the “pyo” macro in the 2.7 version now works correctly when the thread being debugged doesn’t hold the GIL; the macro now acquires it before printing. (Contributed by Victor Stinner; bpo-3632.)
Py_AddPendingCall()is now thread-safe, letting any worker thread submit notifications to the main Python thread. This is particularly useful for asynchronous IO operations. (Contributed by Kristján Valur Jónsson; bpo; bpoor
long long. If the number is too large to fit into the output type, an overflow flag is set and returned to the caller. (Contributed by Case Van Horsen; bpo-7528 and bpoand can optionally update
sys.pathto bpo; bpo-5793.)
Removed function:
PyEval_CallObjectis now only available as a macro. A function version was being kept around to preserve ABI linking compatibility, but that was in 1997; it can certainly be deleted by now. (Removed by Antoine Pitrou; bpo-8276.)
New format codes: the
PyFormat_FromString(),
PyFormat_FromStringV(), and
PyErr_Format()functions now accept
%lldand
%lluformat codes for displaying C’s
long longtypes. (Contributed by Mark Dickinson; bpomodule. C extension modules that have internal locks, or that call
fork()themselves, will not benefit from this clean-up.
(Fixed by Thomas Wouters; bpo-1590864.)
The
Py_Finalize()function now calls the internal
threading._shutdown()function; this prevents some exceptions from being raised when an interpreter shuts down. (Patch by Adam Olsen; bpo-1722344.)
When using the
PyMemberDefstructure to define attributes of a type, Python will no longer let you try to delete or set a
T_STRING_INPLACEattribute.
Global symbols defined by the
ctypesmodule are now prefixed with
Py, or with
_ctypes. (Implemented by Thomas Heller; bpo-3102.)
New configure option: the
--with-system-expatswitch allows building the
pyexpatmodule to use the system Expat library. (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-7609.)
New configure option: the
--with-valgrindoption will now disable the pymalloc allocator, which is difficult for the Valgrind memory-error detector to analyze correctly. Valgrind will therefore be better at detecting memory leaks and overruns. (Contributed by James Henstridge; bpo-2422.)
New configure option: you can now supply an empty string to
--with-dbmliborder=in order to disable all of the various DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis; bpo-6491.)
The configure script now checks for floating-point rounding bugs on certain 32-bit Intel chips and defines a
X87_DOUBLE_ROUNDINGpreprocessor definition. No code currently uses this definition, but it’s available if anyone wishes to use it. (Added by Mark Dickinson; bpo-2937.)
configure also now sets a
LDCXXSHAREDMakefile variable for supporting C++ linking. (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-1222585.)
The build process now creates the necessary files for pkg-config support. (Contributed by Clinton Roy; bpo-3585.)
The build process now supports Subversion 1.7. (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-6094.)
Capsules¶ bpo-5630.
Port-Specific Changes: Windows¶
- The
msvcrtmodule now contains some constants from the
crtassem.hheader file:
CRT_ASSEMBLY_VERSION,
VC_ASSEMBLY_PUBLICKEYTOKEN, and
LIBRARIES_ASSEMBLY_NAME_PREFIX. (Contributed by David Cournapeau; bpo-4365.)
- The
_winregmodule: bpo-7347.)
- The new
_beginthreadex()API is used to start threads, and the native thread-local storage functions are now used. (Contributed by Kristján Valur Jónsson; bpo; bpo-1220212.)
- The
os.listdir()function now correctly fails for an empty path. (Fixed by Hirokazu Yamamoto; bpo-5913.)
- The
mimelibmodule will now read the MIME database from the Windows registry when initializing. (Patch by Gabriel Genellina; bpo-4969.)
Port-Specific Changes: Mac OS X¶
The path
/Library/Python/2.7/site-packagesis now appended to
sys.path, in order to share added packages between the system installation and a user-installed copy of the same version. (Changed by Ronald Oussoren; bpo-4865.)
Changed in version 2.7.13: As of 2.7.13, this change was removed.
/Library/Python/2.7/site-packages, the site-packages directory used by the Apple-supplied system Python 2.7 is no longer appended to
sys.pathfor user-installed Pythons such as from the python.org installers. As of macOS 10.12, Apple changed how the system site-packages directory is configured, which could cause installation of pip components, like setuptools, to fail. Packages installed for the system Python will no longer be shared with user-installed Pythons. (bpo-28440)
Other Changes and Fixes¶
- Two benchmark scripts,
iobenchand
ccbench, were added to the
Toolsdirectory.
iobenchmeasures the speed of the built-in file I/O objects returned by
open()while performing various operations, and
ccbenchis a concurrency benchmark that tries to measure computing throughput, thread switching latency, and IO processing bandwidth when performing several tasks using a varying number of threads.
- The
Tools/i18n/msgfmt.pyscript now understands plural forms in
.pofiles. (Fixed by Martin von Löwis; bpo-5464.)
- When importing a module from a
.pycor
.pyofile with an existing
.pycounterpart, the
co_filenameattributes of the resulting code objects are overwritten when the original filename is obsolete. This can happen if the file has been renamed, moved, or is accessed through different paths. (Patch by Ziga Seilnacht and Jean-Paul Calderone; bpo-1180193.)
- The
regrtest.pyscript now takes a
--randseed=switch that takes an integer that will be used as the random seed for the
-roption that executes tests in random order. The
-roption also reports the seed that was used (Added by Collin Winter.)
- Another
regrtest.pyswitch is
-j, which takes an integer specifying how many tests run in parallel. This allows reducing the total runtime on multi-core machines. This option is compatible with several other options, including the
-Rswitch which is known to produce long runtimes. (Added by Antoine Pitrou, bpo-6152.) This can also be used with a new
-Fswitch that runs selected tests in a loop until they fail. (Added by Antoine Pitrou; bpo-7312.)
- When executed as a script, the
py_compile.pymodule now accepts
'-'as an argument, which will read standard input for the list of filenames to be compiled. (Contributed by Piotr Ożarowski; bpo; bpo-1533.)
- The string
format()method changed the default precision used for floating-point and complex numbers from 6 decimal places to 12, which matches the precision used by
str(). (Changed by Eric Smith; bpo-5920.)
- Because of an optimization for the
withstatement, the special methods
__enter__()and
__exit__()must belong to the object’s type, and cannot be directly attached to the object’s instance. This affects new-style classes (derived from
object) and C extension types. (bpo; bpo-7853.)
- When a restricted set of attributes were set using
__slots__, deleting an unset attribute would not raise
AttributeErroras you would expect. Fixed by Benjamin Peterson; bpo-7604.)
In the standard library:
Operations with
datetimeinstances; bpo-7150.)
When using
Decimalinstances; bpo-2746.)
The
readline()method of
StringIOobjects now does nothing when a negative length is requested, as other file-like objects do. (bpo-7348).
The
syslogmodule will now use the value of
sys.argv[0]as the identifier instead of the previous default value of
'python'. (Changed by Sean Reifschneider; bpo-8451.):
- C extensions that use integer format codes with the
PyArg_Parse*family of functions will now raise a
TypeErrorexception instead of triggering a
DeprecationWarning(bpo.
Two new environment variables for debug mode¶
In debug mode, the
[xxx refs] statistic is not written by default, the
PYTHONSHOWREFCOUNT environment variable now must also be set.
(Contributed by Victor Stinner; bpo-31733.)
When Python is compiled with
COUNT_ALLOC defined, allocation counts are no
longer dumped by default anymore: the
PYTHONSHOWALLOCCOUNT environment
variable must now also be set. Moreover, allocation counts are now dumped into
stderr, rather than stdout. (Contributed by Victor Stinner; bpo-31692.)
New in version 2.7.15.; bpo-21306.)
- OpenSSL 1.0.1g was upgraded in the official Windows installers published on python.org. (Contributed by Zachary Ware; bpo; bpo-21304.)
- OpenSSL 1.0.1h was upgraded for the official Windows installers published on python.org. (contributed by Zachary Ware in bpo-21671 for CVE-2014-0224)
PEP 466 related features added in Python 2.7.9:
Most of Python 3.4’s
sslmodule was backported. This means
sslnow supports Server Name Indication, TLS1.x settings, access to the platform certificate store, the
SSLContextclass, and other features. (Contributed by Alex Gaynor and David Reid; bpo-21308.)
Refer to the “Version added: 2.7.9” notes in the module documentation for specific details.
os.urandom()was changed to cache a file descriptor to
/dev/urandominstead of reopening
/dev/urandomon every call. (Contributed by Alex Gaynor; bpo-21305.)
hashlib.algorithms_guaranteedand
hashlib.algorithms_availablewere backported from Python 3 to make it easier for Python 2 applications to select the strongest available hash algorithm. (Contributed by Alex Gaynor in bpo-21307)
PEP 477: Backport ensurepip (PEP 453) to Python 2.7¶
PEP 477 approves the inclusion of the PEP 453 ensurepip module and the improved documentation that was enabled by it in the Python 2.7 maintenance releases, appearing first in the Python 2.7.9 release.
Bootstrapping pip By Default¶
The new
ensurepip module (defined in PEP 453) provides a standard
cross-platform mechanism to bootstrap the pip installer into Python
installations. The version of
pip included with Python 2.7.9 is
pip
1.5.6, and future 2.7.x maintenance releases will update the bundled version to
the latest version of
pip that is available at the time of creating the
release candidate.
By default, the commands
pip,
pipX and
pipX.Y will be installed on
all platforms (where X.Y stands for the version of the Python installation),
along with the
pip Python package and its dependencies.
For CPython source builds on POSIX systems,
the
make install and
make altinstall commands do not76: Enabling certificate verification by default for stdlib http clients¶
PEP 476 updated
httplib and modules which use it, such as
urllib2 and
xmlrpclib, to now verify that the server
presents a certificate which is signed by a Certificate Authority in the
platform trust store and whose hostname matches the hostname being requested
by default, significantly improving security for many applications. This
change was made in the Python 2.7.9 release.
For applications which require the old previous behavior, they can pass an alternate context:
import urllib22.urlopen("", context=context)
PEP 493: HTTPS verification migration tools for Python 2.7¶
PEP 493 provides additional migration tools to support a more incremental infrastructure upgrade process for environments containing applications and services relying on the historically permissive processing of server certificates when establishing client HTTPS connections. These additions were made in the Python 2.7.12 release.
These tools are intended for use in cases where affected applications and services can’t be modified to explicitly pass a more permissive SSL context when establishing the connection.
For applications and services which can’t be modified at all, the new
PYTHONHTTPSVERIFY environment variable may be set to
0 to revert an
entire Python process back to the default permissive behaviour of Python 2.7.8
and earlier.
For cases where the connection establishment code can’t be modified, but the
overall application can be, the new
ssl._https_verify_certificates()
function can be used to adjust the default behaviour at runtime. 2.7.14. 2.7.14. | https://docs.python.org/2/whatsnew/2.7.html | CC-MAIN-2018-47 | refinedweb | 5,841 | 50.63 |
Creating User Interfaces
Forms
Forms are the pages of your Anvil app. They have a visual design that describes how they look, and a Python class that describes how they behave.
The Form with the
symbol next to it is the startup Form. This is the first page displayed when your Anvil app is opened.
The Anvil Editor shows a list of Forms in the App Browser. You can click on each Form and view it in either Design view or Code view:
In Design view, you can move components around on your Form and drop components into it.
In Code view, you can see that each Form is represented by a Python class. Its attributes and methods define how the app behaves. You can create and manipulate components in code as well.
The following code is auto-generated by the Anvil Editor when you add a new Form to your app:
from anvil import * class Form1(Form1Template): def __init__(self, **properties): # Set Form properties and Data Bindings. self.init_components(**properties) # Any code you write here will run when the form opens.
Creating a component
To add a new component to your page, go to Design view and drag its icon from the Toolbox into the Form Editor. The highlighted line shows you where your new component will be created:
Video: Creating a button<<
Editing a property of a Button component
The Properties Panel is grouped into sections, and you can click the “More” link to see more properties:
More properties
Component names
Each component has a name (e.g.
self.button_1). This lets you refer to this component as an instance attribute in your Form class.
Container properties
Components are typically placed inside containers. You can set container properties that configure how the component is displayed in its container. For example, if a component is placed inside an
XYPanel, the container properties set the X and Y coordinates of the component within the
XYPanel.
Dragging handles
When you select some components, you will see draggable handles that let you adjust the size of the component. (For example, there is a handle to set the height of an
Image component.) This is a visual way of editing the value of a property (e.g. the
height property of an
Image component).
Component events
If you scroll to the bottom of the Properties Panel, you can find a list of events that the selected component can raise.
Events
Next to each event, you can enter the name of a Python method. That method will be called when the event occurs.
Click the blue arrow button to go to the method that runs when the event occurs. If an appropriate method doesn’t exist already, it will be created. (If there is no method name in the box, an appropriate name will be chosen using the name of the component and the event: e.g.
button_1_click.)
Component visual layout
Components are laid out from top to bottom on a page. A component’s width is determined by its container. A component’s height is determined by its own properties.
Everything is Code
Everything that you can do in Design view of the Form Editor can also be done by writing some Python code in Code View. This is because each component that you drag-and-drop onto your Form is represented as a Python object that you can interact with directly.
For example, you can add components to your Form or change a component’s properties by writing code in your Form’s
__init__ method.
We’ll explore this in more detail in the coming sections, but here are some examples:
- You can add a component by creating an instance of the component class (e.g.) | https://anvil.works/docs/client/ui | CC-MAIN-2019-51 | refinedweb | 624 | 61.87 |
![if !(IE 9)]> <![endif]>
The analyzer has detected a constructor that doesn't initialize some of the class members. Here's a simple synthetic example:
struct MyPoint { int m_x, m_y; MyPoint() { m_x = 0; } void Print() { cout << m_x << " " << m_y; } }; MyPoint Point; Point.Print();
When creating the Point object, a constructor will be called that won't initialize the 'm_y' member. Accordingly, when calling the Print function, an uninitialized variable will be used. The consequences of this are unpredictable.
The correct version of the constructor should look like this:
MyPoint() { m_x = 0; m_y = 0; }
We have discussed a simple synthetic example, where a bug can be easily spotted. However, in real-life code, things may be much more complicated. Search of uninitialized class members is implemented through a set of empirical algorithms. Firstly, class members can be initialized in a large variety of ways, and it's sometimes difficult for the analyzer to figure out whether or not a class member has been initialized. Secondly, not all the members should be initialized all the time, and the analyzer may output false positive warnings as it doesn't know the programmer's intentions.
Search of uninitialized class members is a difficult and thankless task. This matter is discussed in more detail in the article "In search of uninitialized class members". So please be understanding when you get false positives and use the false positive suppression mechanisms the analyzer provides.
You can suppress a warning by marking the constructor with the comment "//-V730". Another way is to use a special database for false positives. As a last resort, when there are too many of them, consider disabling the V730 diagnostic altogether.
But these are extreme measures. In practice, it might make sense to exclude from analysis individual structure members that don't need to be initialized in the constructor. Here's another synthetic example:
const size_t MAX_STACK_SIZE = 100; class Stack { size_t m_size; int m_array[MAX_STACK_SIZE]; public: Stack() : m_size(0) {} void Push(int value) { if (m_size == MAX_STACK_SIZE) throw std::exception("overflow"); m_array[m_size++] = value; } int Pop() { if (m_size == 0) throw std::exception("underflow"); return m_array[--m_size]; } };
This class implements a stack. The 'm_array' array is not initialized in the constructor, and that's correct because the stack is considered originally empty.
The analyzer will output warning V730 as it can't figure out how this class works. You can help it by marking the 'm_array' member with the comment "//-V730_NOINIT" to specify that the 'm_array' array doesn't need to be necessarily initialized.
From that point on, the analyzer won't produce the warning when analyzing this code:
class Stack { size_t m_size; int m_array[MAX_STACK_SIZE]; //-V730_NOINIT public: Stack() : m_size(0) {} ..... };
There is a way to disable V730 warnings for all class fields of a certain type.
Let's consider the example:
class Field { public: int f; }; class Test { public: Test() {} Field field; };
The following warning will be issued for this code fragment: V730 Not all members of a class are initialized inside the constructor. Consider inspecting: field.
To exclude all warnings of a class field of the type 'Field', one has to add the following comment in the code or settings file:
//+V730:SUPPRESS_FIELD_TYPE, class:Field
The format of the comment:
//+V730:SUPPRESS_FIELD_TYPE, class:className, namespace:nsName
or
//+V730:SUPPRESS_FIELD_TYPE, class:className.NestedClassName, namespace:nsName: ... | https://www.viva64.com/en/w/v730/ | CC-MAIN-2020-05 | refinedweb | 550 | 52.09 |
-validating parsers aren't required to retrieve external DTDs or entities, although the parser should at least warn applications that this is happening. While reconstructing an XML document with exactly the same logical structure and content is possible, guaranteeing that it will match the original in a byte-by-byte comparison generally is not.
XML Canonicalization defines a more consistent form of XML and a process for producing it that permits a much higher degree of predictability in reconstructing a document from its logical model. For details, see. a parser reports documents as you want, and not just the minimum required by the XML specification, is to check its documentation and configure (or choose) the parser accordingly .
DTDs come in two forms: internal and external and sometimes both. The XML specification requires all parsers to read the internal DTD subset. Validation requires reading the external DTD subset (if any); but if you don't validate, this is optional. Reading the external DTD subset takes extra time, especially if the DTD is large and/or stored on a remote network host, so you may not want to load it if you're not validating. Most parsers provide options to specify whether the external DTD subset and other external entities should be resolved. If validation were all a DTD did, then the decision of whether to load the DTD would be easy. Unfortunately, DTDs also augment a document's infoset with several important properties, including:
Entity definitions
Default attribute values
Whether boundary whitespace is ignorable
At the extreme, since a document with a malformed DTD is itself malformed , a DTD can make a document readable or unreadable. This means whether a parser reads the external DTD subset or not can have a significant impact on what the parser reports. For maximum interoperability documents should be served without external DTD subsets. In this case parser behavior is deterministic and reproducible, regardless of configuration. On the flip side a consumer of XML documents should attempt to read any external DTD subset the document references if they want to be sure of receiving what the sender intended. Be conservative in what you send (don't use external DTD subsets) and liberal in what you accept (do read any external DTD subsets for documents you receive).
How parsers treat whitespace is one of the most commonly misunderstood areas of XML processing. There are four basic rules you need to remember:
All whitespace in element content is always reported .
Whitespace in attribute values is normalized .
Whitespace in the prolog and epilog and within tags but outside attribute values is not reported.
All non-escaped line breaks (carriage returns, line feeds, carriage return-line feed pairs, and, in XML 1.1, NEL and line separator) are converted to line feeds.
Consider Example 18-2.
<?xml version="1.0"?> <!DOCTYPE person SYSTEM "person.dtd "> <person source="Alan Turing: the Enigma, Andrew Hodges, 1983"> <name> <first>Alan</first> <last>Turing</last> </name> <profession id="p1" value="computer scientist " source="" /> <profession id="p2" value="mathematician"/> <profession id="p3" value="cryptographer"/> </person>
When a parser reads this document, it will report all the whitespace in the element content to the client application. This includes boundary whitespace like that between the <name> and <first> start-tags and the </last> and </name> end-tags. If the DTD says that the name element cannot contain mixed content, the whitespace is considered to be whitespace in element content , also called ignorable whitespace . However, the parser still reports it. The client application receiving the content from the parser may choose to ignore boundary whitespace, whether it's ignorable or not, interpreting it as purely for the purpose of pretty printing; but that's up to the client application. The parser always reports it all.
The parser does not report the line breaks and other whitespace in the prolog and epilog. Nor does it report the line breaks and whitespace in the tags such as that between the id and value attributes in the profession elements. Nothing in your program should depend on this.
The parser will normalize all the whitespace in attribute values. At a minimum, this means it will turn line breaks like those in the source attribute into spaces. If the DTD says the attribute has type CDATA or does not declare it, or if the DTD has not been read or does not exist, then that's all. However, if the attribute has any other type such as ID , NMTOKENS , or an enumeration, then the parser will strip all leading and trailing whitespace from the attribute and compress all remaining runs of whitespace to a single space each. However, normalization is only performed on literal whitespace. Spaces, tabs, line feeds, and carriage returns embedded with character or entity references are converted to their replacement text and then retained. They are not normalized like literal whitespace.
There are three kinds of references in XML instance documents (plus another couple in the DTD we can ignore for the moment):
Numeric character references, such as and
The five predefined entity references, & , > , " , ' , and <
General entity references defined by the DTD, such as &chapter1; and
The first two kinds are easy to handle. The parser always resolves them and never tells you anything about them. As a parser client, you can simply ignore these and the right thing will happen. The parser will report the replacement text in the same way it reports regular text. It won't ever tell you that these entity references were used. On rare occasion you may be able to set a special property on the parser to have it tell you about these things, but you almost never want to do that. The only case where that might make sense is if you're writing an XML editor that tries to round-trip the source form of a document.
The third case is trickier. These entity references may refer to external files on remote sites you don't necessarily want to connect to for reasons of performance, availability, or security. Even if they're internal entities, they may be defined in the external DTD subset in a remote document. Parsers vary in whether they load such entities by default. Most parsers and APIs do provide a means of specifying whether external entities should or should not be loaded, although this is not universal. For instance, XOM always resolves external entities, while the XML parser in Mozilla never resolves them. Parsers that do not resolve an external entity should nevertheless notify the client application that the entity was not loadedfor instance, calling skippedEntity( ) in SAX or inserting an EntityReference object into the tree in DOM. How the program responds to such notifications is a question that must be answered in the context of each application. Sometimes it's a fatal problem. Other times it's something you can work around or even ignore, but do be aware that you need to consider this possibility unless the parser is configured to always resolve external entities.
Recently, a few parser vendors have become concerned about the so-called billion laugh attacks. In brief, it works by defining entity references that progressively double in size , especially in the internal DTD subset where the entities must be resolved:
<!ENTITY ha1 "Ha! "> <!ENTITY ha2 "&ha1; &ha1;"> <!ENTITY ha3 "&ha2; &ha2;"> <!ENTITY ha4 "&ha3; &ha3;"> <!ENTITY ha5 "&ha4; &ha4;"> <!ENTITY ha6 "&ha5; &ha5;"> ... <!ENTITY ha31 "&ha30; &ha30;"> <!ENTITY ha32 "&ha31; &ha31;"> ... <root>&ha32;</root>
So far this attack is purely theoretical. Nonetheless, some parser vendors have started adding options to their parsers not to resolve entities defined in the internal DTD subset either (which is non-conformant to the XML Recommendation). Other palliatives include setting maximum limits on entity size or recursion depth in entity reference. In general these options are not turned on by default, because they are nonconformant.
The golden rule of handling CDATA sections is this: ignore them. When writing code to process XML, pretend CDATA sections do not exist, and everything will work just fine. The content of a CDATA section is plain text. It will be reported to your application as plain text, just like any other text, whether enclosed in a CDATA section, escaped with character references, or typed out literally when escaping is not necessary. For example, these two example elements are exactly the same as far as anything in your code should know or care:
<example><![CDATA[<?xml version="1.0"?> <root> Hello! </root>]]></example> <example><?xml version="1.0"?> <root> Hello! </root></example>
Do not write programs or XML documents that depend on knowing the difference between the two. Parsers rarely (and never reliably) inform you of the difference. Furthermore, passing such documents through a processing chain often removes the CDATA sections completely, leaving only the content intact but represented differentlyfor instance, with numeric character references representing the unserializable characters . CDATA sections are a minor convenience for human authors, nothing more. Do not treat them as markup.
This also means you should not attempt to nest one XML (or HTML) document inside another using CDATA sections. XML documents are not designed to nest inside one another. The correct solution to this problem is to use namespaces to sort out which markup is which, rather than trying to treat a document as an envelope for other documents. Similarly do not use CDATA sections to escape malformed markup such as is found in many HTML systems. Instead, use a tool such as Tidy to correct the malformed HTML before embedding it in an XML document. document.-stylesheet type="text/css" href="test.css"?>
An XML-aware application, such as Internet Explorer 6.0, would be capable of recognizing the XML author's intention to display the document using the test.css stylesheet. This processing instruction can also be used to link to XSLT stylesheets or other kinds of stylesheets not yet developed, although the client application needs to understand how to process them to make this work. Applications that do not understand the processing instructions can still parse and use the information in the XML document while ignoring the unfamiliar processing instruction.
The furniture example from Chapter 21 (see Figure 21the XML name immediately after the <? with a notation, as described in the next sectionbut although they are a feature available to applications, they are also rarely used. | https://flylib.com/books/en/1.132.1.153/1/ | CC-MAIN-2018-26 | refinedweb | 1,725 | 53.51 |
NAME
add-term-annot.pl
SYNOPSIS
add-term-annot.pl --host somewhere.edu --dbname biosql
DESCRIPTION
ARGUMENTS
The arguments after the named options constitute the filelist. If there are no such files, input is read from stdin. Mandatory options are marked by (M). Default values for each parameter are shown in square brackets.
- --host $URL
the host name or IP address incl. port [localhost]
- --dbname $db_name
the name of the schema [biosql]
- --dbuser $username
database username [root]
- --dbpass $password
password [undef]
- --driver $driver
the DBI driver name for the RDBMS e.g., mysql, Pg, or Oracle [mysql]
- --namespace $namesp
The namespace, i.e., name of the ontology, for the terms to be associated.
- --testonly
don't commit anything, rollback at the end
- --logchunk
If supplied with an integer argument n greater than zero, progress will be logged to stderr every n entries of the input file(s). Default is no progress logging.
- -u, -z, or --uncompress
Uncompress the input file(s) on-the-fly by piping them through gunzip. Gunzip must be in your path for this option to work.
- more args
The remaining arguments will be treated as files to parse and load. If there are no additional arguments, input is expected to come from standard input.
Authors
Hilmar Lapp <hlapp at gmx.net>
_report_progress
Title : _report_progress Usage : Function: Reports the progress to STDERR. Example : Returns : The new stopped time to be passed to the next call Args : - the time at which progress was reported last - every how many entries progress is reported
_find_or_create_ont
Title : _find_or_create_ont Usage : Function: Find or create the ontology entry with the given name. Example : Returns : A persistent Bio::Ontology::OntologyI object Args : - the persistence adaptor factory (the $db handle) - the name of the ontology | https://metacpan.org/pod/distribution/BioPerl-DB/scripts/biosql/terms/add-term-annot.pl | CC-MAIN-2016-50 | refinedweb | 290 | 57.57 |
Insert time only as hh:mm:ss
I have a need to insert just the time as hh:mm:ss (no date or AM/PM) + a space or - at the start of a line to record the exact time when I entered the text, so I can sync it up with pictures I took at the same time.
I have already tried to create a macro that inserts the short format Date & Time as 8:12 AM 2/9/2016 using TextFx Insert, and then back spacing to erase the date. But apparently the backspace code executes before the full date gets written, ending up with only 2-3 characters of the insert. Even if it worked I would only get hh:mm and not hh:mm:ss.
By using 2 shortcut keys, one for time/date, the other for backspaces, I can at least get hh:mm, but not a single key macro with seconds.
How do I create a macro shortcut key that will only insert hh:mm:ss+space or -?
Thanks, Ron
- Claudia Frank last edited by Claudia Frank
I would use python script plugin and code like
import datetime editor.appendText(datetime.datetime.today().strftime("%H:%M:%S"))
to solve this. If you want to install this plugin I would recommend to use
msi instead of
plugin manager
Cheers
Claudia | https://community.notepad-plus-plus.org/topic/11270/insert-time-only-as-hh-mm-ss | CC-MAIN-2021-39 | refinedweb | 224 | 74.42 |
wsdl.exe helps create ASP.NET web services and proxies for their clients. The most common usage of wsdl.exe is to generate proxy classes for Web services:
wsdl /language:language /namespace:namespace /out:output /protocol:protocol path
The path parameter is a local path to a service-description file or URI where the SDL file can be retrieved. The language parameter specifies the language for the output-proxy source file. It can be C#, VB, JS or VJS. The generated class will be in the specified namespace. The output source file is controlled by the output option. The protocol controls which protocol the proxy will use to communicate with the Web Service. The choices of protocols provided by the .NET Framework are SOAP, SOAP12, HttpGet, and HttpPost. You can also have your own protocol here if you've extended the WebClientProtocol or HttpWebClientProtocol class.
For short names options, use the following:
wsdl /l:language /n:namespace /o:output /protocol:protocol path
The rest of the syntax can be obtained with wsdl /?. | https://etutorials.org/Programming/.NET+Framework+Essentials/Appendix+D.+Common+Utilities/D.13+Web+Service+Utility+wsdl.exe/ | CC-MAIN-2022-21 | refinedweb | 172 | 59.09 |
ayub aliPro Student 723 Points
i need someone to clarify for me four things
what is instance variable; class instance; what is class variables;
2 Answers
Zac Mazza5,867 Points
An instance is defined by the class, method, or conditional statement. Scope is what is between the two curly braces. Class variables are variables defined in the scope, and instance variables are those defined in the class, method, or conditional statement. For example:
public class InstanceExample { //This is a class instance, and everything in this instance is between the curly braces. //class variables go here. public InstanceExample() { // constructor code goes here } public void printHello() { String message = "Hello"; // This is an instance variable, defined within the method. } }
Hope this helps!
Thanks,
Zac
ayub aliPro Student 723 Points
ayub aliPro Student 723 Points
alright the curly braces you are talkinga about; is't between open and closed curly braces like this {instance variable} or like this: {instance variable {, clarify please, you said everthing in the two curly braces is the instance variable | https://teamtreehouse.com/community/i-need-someone-to-clarify-for-me-four-things | CC-MAIN-2020-45 | refinedweb | 170 | 67.08 |
.iOS 7.2.2.39 on a Mac, I'm running into a crash while running my app on the simulator. I was able to come up with a small test case (attached) - basically this:
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
}
public class MyClass
{
public static readonly MyStruct StructInstance = new MyStruct();
}
Running a program that tries to create an instance of MyClass, using the Debug|iPhoneSimulator or Release|iPhoneSimulator configurations will crash with the following error:
* Assertion at ../../../../../mono/mono/mini/method-to-ir.c:10339, condition `addr' not met
The full stack trace is attached.
Adding a property to the struct causes the error go away, as does removing the explicit StructLayout(LayoutKind.Sequential) attribute.
The app runs fine on an actual iPad device (Release|iPhone configuration).
The error looks somewhat similar to Xamarin Bug 18963:
Created attachment 6980 [details]
Test Case for crash (Xamarin iOS project)
Created attachment 6981 [details]
Full stack trace / crash details
I have checked this issue and able to reproduce it. I have created a new project and added the code from 'Appdelegate.cs' page given in comment 1 Attachment 'Test Case for crash (Xamarin iOS project)' in new created project. I added the breakpoint to debug this application and it crashed when it initiating a class with a static reference.
Screencast for same :
Supplement Info :
Build Log :
Application Output Log :
IDE Log :
Environment Info :
=== Xamarin Studio ===
Version 5.0 (build 878)
Installation UUID: 1151d3d9-29c1-4339-b53c-a54856b47901
Runtime:
Mono 3.4.0 ((no/c3fc3ba)
GTK+ 2.24.23 (Raleigh theme)
Package version: 304000204
=== Xamarin.Android ===
Version: 4.12.4 (Enterprise Edition)
Android SDK: /Users/shruti_55"
Java(TM) SE Runtime Environment (build 1.7.0_55-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.55-b03, mixed mode)
=== Apple Developer Tools ===
Xcode 5.1 (5084)
Build 5B130a
=== Xamarin.iOS ===
Version: 7.2.3.39 (Enterprise Edition)
Hash: fc6f56b
Branch:
Build date: 2014-05-19 19:10:29-0400
=== Xamarin.Mac ===
Xamarin.Mac: Not Installed
===
Darwin Shrutis-Mac-mini.local 13.1.0 Darwin Kernel Version 13.1.0
Thu Jan 16 19:40:37 PST 2014
root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64
Looks like a JIT/runtime issue. Zoltan can you have a look ?
Fixed in mono master 2aa7af58636bc7c5499d4c150c64f51bf73b30c3.
Very quick turnaround for this one, thanks.
Any idea what version of Xamarin.iOS the fix will make it into? | https://bugzilla.xamarin.com/show_bug.cgi?id=20349 | CC-MAIN-2019-04 | refinedweb | 399 | 60.31 |
Hard Python question
I am trying to do something which is, I think, pretty cool, in python.
However, I like showing things working, and I am having troubles with the last final step on what I am trying to achieve.
Since I know a few better python programmers read this...
Suppose I have this:
def fun(self,x): pass class C: pass C.a=fun C.b=fun
What code should be in fun() so that it figures out if it has been called as C.a or as C.b?
I am thinking something like reading the higher step in a backtrace, but I don't know enough python to figure out how to do that.
I don't think this is possible, as the "method" name you are using to call the function doesn't make it on to the call stack. You can get stack frames using sys._getframe, but I doubt the method name will appear in there (it's just a key/value pair in the class dict). If you really must get this kind of info you're better off doing something like:
def fun(self, callname): blah
C.a = lambda self: fun(self, 'a')
C.b = lambda self: fun(self, 'b')
but it really must be asked what you're trying to do :)
Blah, I only get a '?' as function name :-P
Looks like it *is* feasible!
Thanks taj for that _getframe , because googling for it just lead me here:
Have a look at my extremely simplistic interface to the DCOP command line app, it does something very similar: | https://ralsina.me/weblog/posts/P200.html | CC-MAIN-2021-17 | refinedweb | 266 | 80.31 |
One of the tricky things about writing React components meant for public consumption is making them compatible with various styling approaches used by the community. The problem exists because application styling isn't considered as a first-class citizen by React and it doesn't provide a strong opinion on how to solve it. As a result, the amount of available approaches has exploded.
Jan-Felix Schwarz noticed the same problem. As a result substyle was born.. :)
substyle is a utility for authors of open source React component libraries. It tries to make it easier to build components in a way that allows users to customize styles of every single element rendered by a component. Users will be able to do that through CSS, CSS Modules, many css-in-js libraries, or using inline styles. This way, the component integrates well into applications using any styling approach, without forcing an opinion about tooling.
substyle provides a higher-order component that preprocesses whichever props the user passes for styling purposes so that they become more comfortable to consume. It injects a single, special
style prop, which is used in the wrapped component's render function to derive the right styling props to forward to each of the rendered elements.
For example, a universally stylable
<Popover /> component could be written like this:
import substyle from "substyle"; const Popover = substyle(({ style, children }) => ( <div {...style}> <button {...style("close")}>x</button> {children} </div> ));
Now, users of the
<Popover /> component can pass their custom
className, which will be used to derive classes for all the elements rendered by the component:
// JSX // Rendered HTML <Popover className="popover"> // <div class="popover"> <span>Hello world!</span> // <button class="popover__close"> </Popover> // x // </button> // <span>Hello world!</span> // </div>
If they want to pass some custom inline styles, they can do so by supplying a nested
style object:
// JSX // Rendered HTML <Popover style={{ // <div style="background: white;"> background: 'white', // <button style="right: 0;">x</button> close: { right: 0 }, // <span>Hello world!</span> }}> // </div> <span>Hello world!</span> </Popover>
If they use css modules or some css-in-js lib, they will want to pass the unique, auto-generated classes to assign to the elements. They can do so via the
classNames prop that is handled by substyle:
// JSX // Rendered HTML <Popover classNames={{ // <div class="1n3n1g"> popover: '1n3n1g', // <button class="ew339k">x</button> popover__close: 'ew339k', // <span>Hello world!</span> }}> // </div> <span>Hello world!</span> </Popover>
I know of one other solution addressing the same problem called react-themeable. The general idea behind both, react-themeable and substyle, is the same. However, during the development of a component library at Signavio I had to solve some additional practical challenges:
Exploring solutions to these problems I finally ended up writing my utility.
I got the initial idea for it while developing an open source React mentions input. As I was aiming to let users style this input widget with css and inline styles, I had to add quite a bit of code to my components just for this purpose. To keep my code DRY and the render functions clean, I extracted this repetitive styling logic into a helper function.
Later I realized that I could quickly add support for styling through css modules and css-in-js libraries, just by changing this helper function and without having to touch any of the components. And this is basically how substyle came to be.
I hope that the idea of supporting universal styling takes hold in the React community and that we can establish some best practices for writing reusable components. It would make app developers' lives better as they would not have to study docs, examples, or source code of every single component library to find out how to override styles of particular elements. Instead, they could just use the same familiar styling API for any open source component.
substyle is just my take on a universal styling API for React components and it demonstrates that it is quite easy to implement this. So I don't know if substyle as a library will have a future, but I hope that we will continue the discussion about the styling of reusable components.
For web development in general, I see much more fundamental trends: One hot topic is the shift from frameworks to compilers. I believe this idea has enormous potential and it's exciting to see projects like Prepack and svelte pushing forward this frontier.
Another development I expect for the next years is that the architectural boundary between client and server will become more and more blurry as server rendering and GraphQL APIs become the norm. We will be able to share much more code between front and back ends, up to a point, where this distinction is rendered useless.
Be more passionate about what you are building than how you are making it. Don't choose libraries and frameworks just because they are hyped, but because they promise to solve a particular problem that you are feeling.
I think this helps to embrace that there is so much choice in the JavaScript ecosystem, rather than feeling overwhelmed by it. Also, don't be intimidated by unfamiliar, complex-sounding jargon. Usually, it's just fancy names for simple concepts.
I dig the stuff Brent Jackson (@jxnblk) is building. He's both, a great programmer and designer, and his work is right at the intersection of both disciplines.
Thanks for the interview Jan-Felix! substyle looks like an excellent fit for anyone wanting to write robust React components that are easy to consume.
You can find substyle on GitHub. See also Jan-Felix's presentation (16 mins) on the topic. | https://survivejs.com/blog/substyle-interview/ | CC-MAIN-2019-18 | refinedweb | 945 | 60.65 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.