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
This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues. Part of umbrella issue 177274. Less indexes => less IO => better performance. Tomas, when we have implemented index repository for C++ we have made due diligence and our conclusion was: it is very slow to have index per file in our case we have index file per namespace => less indexes => you can try to merge indexes per package >it is very slow to have index per file Currently we have an index per source root not for file (package). Which seems to be the best choice, unfortunately there are too many indexes (java - original one, javascript, tasklist, fileindex, ...). The opening of index takes some time and go to type needs to consult all indexers (except of fileindexer and tasklist). The goal of this issue is to put all documents for given root into single index.
https://bz.apache.org/netbeans/show_bug.cgi?id=177465
CC-MAIN-2020-24
refinedweb
162
59.64
Overview Atlassian SourceTree is a free Git and Mercurial client for Windows. Atlassian SourceTree is a free Git and Mercurial client for Mac. Pyfig: A simple config file parser for python Information: - Project by Alec Henriksen <alecwh@gmail.com> - License: GNU GPL - Website: - Version: 2.0 (09/27/2009) - Development: Features - Easy to use (straightforward, simple) - Supports categories/sections in the config file - Supports comments - Very robust in terms of parsing - One file, no package Installation Simply drop pyfig.py inside your working directory, or somewhere in your python search path. Pyfig doesn't have any dependencies. Licensing Pyfig is released under the GNU GPL (General Public License). See LICENSE for more information. Example and Usage The `EXAMPLE_CONFIG` file can be used to test/play with Pyfig. First, you need to import Pyfig into your program: import pyfig Next, you need to create the Pyfig object. In order to do this, you need to pass the filepath of the config file you want to parse. I'll use the EXAMPLE_CONFIG included. config = pyfig.Pyfig("EXAMPLE_CONFIG") That's it. You've just created a Pyfig instance which contains all the data in EXAMPLE_CONFIG. Pyfig organizes config values by category, so in order to access player_name under category general, you would do this: print config.general.player_name 'toaster_phun' There is also an age value in that category. We can access that like this: print config.general.age 19 You can also iterate through categories! This is useful when you don't know what or how many config values exist in a given category. You iterate like this: - for x, y in config.general: - print "%s ---> %s" % (x, y) age ---> 19 player_name ---> toaster_phun The entire config object is also an iterable. It will return a tuple for each category; the name of the category and the actual object: - for x, y in config: - print "%s: %s" % (x, y) bank: <pyfig.ConfigCategory object at 0xb7d8692c> connection: <pyfig.ConfigCategory object at 0xb7d8990c> general: <pyfig.ConfigCategory object at 0xb7d867ec> Pyfig and Type Detection Pyfig does not automatically detect types. If you would like Pyfig to turn a value into something other than a string (the default type for values), it must be specified in the config file. By default, the following value, 19, will be a string: player_age = 19 If you want 19 to be an integer inside your config object, you must add this: player_age/int = 19 Or a float: player_age/float = 19 Or a boolean: apply_advanced_graphics/bool = True ### Warning ### Boolean values should only be "True" or "False". Anything besides False will be returned as True. (So don't misspell False!) API Changes since 1.x Pyfig has undergone a major API re-design since the 1.x series. To get a full documentation, see the Example and Usage section above. Config values are now stored as objects in category objects. You grab a value by: >>> print Pyfig.general.age 16 Config categories are also iterables. You can do this: >>> for x, y in Pyfig.general ... print x, y age 19 player_name toaster_phun Contribute, Contact All development happens at. Branches and patches are always appreciated. To contact me, email me (alecwh{at}gmail[dot]com) or see my
https://bitbucket.org/alecwh/pyfig
CC-MAIN-2017-04
refinedweb
533
50.43
- Training Library - Containers - Courses - Deploying A Cloud Native Application into Kubernetes K8s Cluster DNS Resolution Testing'll quickly demonstrate how DNS works internally within the Cluster. And, as an example, how we can test DNS resolution for the registered services deployed as part of our sample application. For starters, let's view the system pods within the cluster which are used for DNS. Within the terminal, I'll run the following command: kubectl get pods --namespace= kube-system -l, for label, k8s- app=kube-dns. Now, this results in the following two CoreDNS pods which are used for DNS and have been deployed in the kube-system namespace. Next, I'll launch the following pod for DNS testing purposes which is based on the tutum/dnsutils image. This will give us the ability to run the dig utility which allows us to resolve various DNS names currently registered within our cluster. Okay, we'll now attempt to resolve the mongo.cloudacademy.svc.cluster.local service name using the dig utility like so. Here, we can see that this results in the answer section containing the following three A records, one for each of the mongo pods where the IP address is the address assigned to the pod. This is designed like so, since the mongo service was deployed as a headless service where the ClusterIP property was set to None. Next, we'll attempt to resolve the api.cloudacademy.svc.cluster.local service record. And here we can see that it resolves differently. In this case, the answer section contains a single A record containing the VIP address, 10.101.151.37 which the cluster registered and assigned to the API service when it was deployed. And finally, we'll query and resolve the frontend.cloudacademy.svc.cluster.local service record. And again, we can see that the answer section contains a single A record containing the VIP address, 10.107.216.59, which the cluster registered and assigned to the frontend service when it was deployed. Let's now exit this testing pod and run a quick check on the services that are currently deployed within the cloudacademy namespace. I'll run the command: kubectl get svc, for service. And as expected the frontend and api services have the ClusterIP addresses that we've just seen when we performed DNS resolution on the cluster-registered service names. And finally, notice how the ClusterIP is set to None for the mongo service. It is this property that makes it a headless service and changes the behavior of DNS for the equivalent service record as seen earlier. Okay that concludes this brief DNS review and testing demonstration. The key takeaway from this lecture is knowing how to query and resolve DNS names within the cluster. >.
https://cloudacademy.com/course/deploying-cloud-native-app-into-kubernetes/k8s-cluster-dns-resolution-testing/
CC-MAIN-2021-17
refinedweb
464
63.8
Web Development with Django Table Of Contents 2. Why do you want to use Django? 2.4. Maintainable 4. Sending the request to the right view (urls.py) 5. Handling the requests (views.py) 6. Creating data models {models.py} 7. Querying Data {Views.py} 8. Rendering Data {HTML Templates} 9. Coding Your First Django App - Voting App 9.1. Creating A Project 9.2. Django Server 9.3. Creating Voting App 9.4. Write Your First View Function 9.5. Path() Function 9.5.1 path() argument: route 9.5.2 path() argument: view 9.5.3 path() argument: kwargs 9.5.4 path() argument: name 9.6 Creating Models 9.8 Python Shell 9.9 Creating An Admin User 9.10 Making Votings App Editable In Admin Panel 9.11 Writing More Views 9.12 Writing Some Meaningful View Function 9.13 Templates For Other View Functions 9.14 Removing HardCore URLs 9.15 NameSpace Names 9.16 Writing Simple Form 9.17 Writing Simple Form 9.18 Customizing Admin Panel 9.19 Adding Related Objects 9.20 Style Sheet (style.css) What is Django? Django is a high-level Python Web framework. It helps to create websites with ease. Django takes care of most of the irritating parts in Web Development. It is free and open source Web framework with an excellent documentation. Why do you want to use Django? Secure Django helps developers avoid many security mistakes. Django developed the framework to do the right things by the protecting the website automatically. For example, Django provides a secure way to manage user accounts and passwords. Django enables protection against most of the website vulnerabilities by default. It includes SQL Injection, cross-site scripting, cross-site request forgery, and clickjacking and even more. Versatile Django can be used to build almost any type of websites like content management, news sites, e-commerce sites, social network sites, wikis, etc.., Django works with different format files like HTML, CSS, JS, JSON, XML, etc.., You can almost create any site using Django with less effort. Portable Django is written in Python. You don't have to bother about the platform while developing apps in Django. Python runs on any platform like Linux, Windows, Mac OS X. Maintainable Django code is written using principles that push users to create maintainable and reusable code. Django reduces the code for websites by providing some useful block of codes for different types of areas like forms, admin management system, etc.., Django follows a pattern called Model View Controller (MVC). Django Code Style Django Web application URLs A URL mapper is used to redirect the HTTP requests to appropriate view based on the request URL. It also matches the particular patterns of strings or digits that appear in the URL and passes these to the view functions as a data. View A View is a request handler function, which receives HTTP requests and returns the HTTP responses. Views access the data needed to satisfy requests via models and formatting the responses to templates. Model Models are the Python objects that define the structures of application's data. It provides to manage (Create, Update, Read, Delete) application's data into the database. Templates A Template is a text file defining the layout of a file. A view can dynamically create an HTML page using an HTML template, populating it with data from a model. A template can be used to define the structure of any type of file; it doesn't have to be HTML. Till now you have seen the Definition, Features and Main Parts of Django. Now, you are going to learn how the main parts of Django are looking like. Let's start..... Sending the request to the right view (urls.py) A URL mapper in the Django project is urls.py. In the below example, the mapper called as urlpatterns defines different types of url patterns and corresponding view function. If an HTTP request is received that has a URL matching in the urlpatterns invokes the corresponding view function and passes that request. from django.contrib import admin from django.urls import urls, include urlpatterns = [ path('admin/', admin.site.urls), path('question<int:id>/', views.question_detail, name = 'question_detail'), path('questions', include('questions.urls')), ] The urlpatterns object is a Python list with items path(). The first argument that the path() takes is the pattern(Route) that will be matched. path() methods use angle brackets (<>) to capture the data from the URL and passes to the view function as a named argument(s). For example, if you have10 question and the url looks like this 'questions/1', then the <> takes the id, i.e., 1 from the URL to display corresponding content in the pages. You will see this in detail in coming Voting App Tutorial With Django. The second argument is another function that invokes corresponding functions when the URL is matched. The notation views.question_detail indicates that the function is called question_detail(). This can be found in the views module (views.py). A third argument name is an option which can be used to shorten the URL. You will learn about it later in this article. urls are usually stored in a file called urls.py Handling the requests (views.py) Views are the heart of the Django applications. They are responsible for the HTTP requests and HTTP responses. In between they perform some activities like database operations, rendering HTML templates, etc., The example below shows a minimal view function index(). It receives the HttpRequest as a parameter request and returns the HttpResponse object. In this example we don't do anything with a request, we simply return a string. # filename: views.py from django.http import HttpResponse def index(request): # Get a HttpRequest - request # perfoms operations according to the request # Returning a HttpResponse return HttpResponse("Simple Django HttpReponse") Views are usually stored in a file called views.py Creating data models {models.py} The code below shows how to create a simple model in Django. from django.db import models class Question(models.Model): question_text = ChatField(max_length = 200) Querying Data {Views.py} Django provides a simple Data query API for the database. The code is shown below, how to select all the questions from the Question model. # filename: views.py from django.shortcuts import render from .models import Question def index(request): all_questions = Question.objects.all(); return render(request, 'templates/index.html', {'all_questions' : all_questions}) The function render() is the shortcut method to create a HttpResponse that is sent back to the browser. It creates an HTML file by combining the corresponding template and data we inserted, i.e., the variable 'all_questions'. It inserts the data that we provided in the HTML file. You can learn more in the later tutorial. Rendering Data {HTML Templates} Templates allow you to specify the structure of the output document. Templates are often used to create HTML documents. You can also create other types of documents also if needed like CSS, JS, XML, JSON, etc.., Django has its own template system. If you want you can also use the popular Python library called Jinja2 for template system. The code shown below is the HTML template file. It is called by the function render(). You have to write the python code in between {% %} pounds, so that Django recognizes that it is a Python code. And to display the variable in HTML template, you have to use {{ }}. Write a variable that you have to display in between 2 curly braces. You have to close the for loop and if questions by writing end(here for or if). See the example... It will display all the question(s) that are present in questions list in HTML template. # filename: index.html <!DOCTYPE html> <html lang='en'> <head> <title> Index </title> </head> <body> <div id='question'> {% for question in questions %} {{ question }} {% endfor %} </div> </body> </html> Till now you have learned some keywords and methods in the Django framework. Now, let's learn by creating a simple Voting app in Django. Let's start learning by doing... Coding Your First Django App - Voting App Now, You will learn how to create projects and apps in Django. Note - I strictly recommend you to follow this tutorial by doing. To develop a Voting app, you need to have basic knowledge of HTML, CSS, and Python. A little bit of JS will boost your Site. 2 Main parts to develop the Voting app:- - A public site that people can and interact with it. - An Admin Site to modify the content which includes Updation, Deletion, and Insertion. First of all, install the Django in your development environment. It is best practice to make a development environment for Python projects. If you don't know how to create virtual environments for Python projects, check here. To install Django Simply run the following code in your terminal or cmd. pip install django If you have any installation problems, refer here. After installing Django start creating the project. Creating A Project Open the command line and go to your project directory, where you have to build it. Run the following command. $ django-admin startproject first_site This will create a first_site directory in the current directory. You have to work in the first_site. Let's what the first_site directory contains. first_site/ manage.py first_site/ __init__.py settings.py urls.py wsgi.py What are those files for? - The outer first_site/ is just for the project files. Its name doesn't require to Django. You can rename it to anything you like. - manage.py: A command line utility to interact with the Django in various ways. You can read all the details about manage.py at django-manage. - The inner first_site/ directory is the actual Python package container for your project. - first_site/_init__.py: It's an empty file that tells Python that this directory should be considered as a Python package. If you want to read more about Python packages, go to Python Packages Official Docs. - first_site/settings.py: It helps to configure the Django. You can learn more about at django settings. - first_site/urls.py: This is the Django declaration for your project. You can read all the documentation at django urls. - first_site/wsgi.py: It helps while you're uploading your website to the servers. See How to Serve With WSGI for more information. Django Server Let's run the Django server to check whether it's working or not. To run the server go to the outer first_site directory and run the following command. $ python manage.py runserver You'll see the following output in the command line. Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work correctly until you apply the migrations for an app(s): admin, auth, content types, sessions. Run 'python manage.py migrate' to apply them. August 10, 2018 - 19:54:23 Django version 2.1, using settings 'polls_site.settings' Starting development server at Quit the server with CTRL-BREAK. You started the Django server. Django server was written in Python. Let's check it by visiting the url or in your browser. You will see the following page in your browser. To change the port of the server just add port number at the end of the command. $ python manage.py runserver 8111 Now, it will serve port at 8111. You don't need to restart the Django server when you make changes in your project. It will automatically load all the changes you make in the project. Creating The Voting App Now, your project is ready to develop apps. All the websites contain some apps like user login system, news feed, etc.., based on the type of website. You can simply create apps in Django project. Django automatically generates the basic structure for your apps. To create your app, make sure that you are in the same directory as manage.py, i.e., change the directory to outer first_site. Type the following command to create an app inside your project. $ python manage.py startapp votings That'll create an app called votings in the outer first_site directory. The structure of the file is... votings/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py This directory contains all the files related to votings app. Write Your First View Function Let's write the first view function. Open the file votings/views.py and write the following code. # filename: first_site/votings/views.py from django.http import HttpResponse def index(request): return HttpResponse("Wow! Writing First Web App In Django!") This is the most straightforward view you have in Django. To call the view functions, you need to map it to the URL. For this, you need to create a URLconf file called urls.py in the votings directory. After creating the urls.py file your votings directory will look like... votings/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py In the votings/urls.py file write the following code. Don't copy: # filename: first_site/votings/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Now, you have to include the votings.urls in the root URLconf, i.e., first_site/urls.py. In the first_site/urls.py, add an import for django.urls.include and insert an include() with the string argument votings.urls int the urlpatterns list. Your file will look like this... # filename: first_site/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('votings/', include('votings.urls')), path('admin/', admin.site.urls), ] The include() function allows referencing other URLconfs. Whenever Django encounters an include(), it sends a string that matches to the included URLconf("votings.urls") for the further processing. You can also change the " votings" url to anything you like "voting_app", " votings_site", etc.., You should always use include() the when you want to add other URL patterns. admin.site.urls is the only exception to it. You have now all connected the index to the URLconf. Let's verify whether it's working are not, run the following command: Note: You always be sure that the directory is outer first_site while running the commands. Run the Django server with the following command. $ python manage.py runserver Go to in your browser. You will see the text "Wow! Writing First Web App In Django!", which you defined in the index view. If you are getting an error check that you are going to and not Path() Function You have to know about the path() function. It will help you in future in this tutorial. The path() function takes 4 arguments in which, 2 required and 2 optional. Required arguments are route and view. Optional arguments are kwargs and name. Let's see all arguments in brief... path() argument: route route is a string that contains a URL pattern. While processing a request, Django starts at urlpatterns and goes a ways down the list until it matches a pattern. For example, in a request to "" the URLconf will look for "votings/". path() argument: view When Django finds a matching pattern, it calls a specified view function with HttpRequest as the first argument and captured data as the keyword arguments, i.e., "kwargs". path() argument: kwargs Keywords can be passed through the dictionary to the target view. path() argument: name Naming your URL helps you to minimize the link url. Especially when you're working with the templates, it helps a lot. You will see this later while developing the app. Learn more about path if you want. Creating Models Now we'll define models - models used to layout the database, with the additional metadata. In this simple app, we'll create 2 models Question and Choice. A Question has a question and a publication date. An Choice has a text field and vote count. Each Choice is related to a Question. These can be implemented in Python using classes. Write the following code in votings/models.py file. # filename: first_site/votings/models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length = 200) pub_date = models.DateTimeField('Published date') class Choice(models.Model): question = models.ForeignKey(Question, no_delete = models.CASCADE) choice_text = models.CharField(max_length = 200) votes = models.IntegerField(default = 0) Each model is represented by a class that subclasses django.db.models.Model. Each Model has a number of variables which represents a database field in a model. Each field is a represented as an instance of Field class ex:- CharField for the characters, IntegerField for integers input, DateTimeField for date times, etc., This tells Django to keep the corresponding field. The name of each Field instance, e.g., choice_text, pub_date, etc.., You will use this value in your Python code, and your database will use this as a column. Some Feild classes have required arguments. For, example CharField requires a max_length argument. A Field can also have various optional arguments, in this case, we have set default value 0. ForeignKey used to define a relationship. This tells Django that each Choice is related to a single Question. Django supports all database relations like many-to-many, many-to-one, one-to-one. Activating Models A small bit of code gives extensive information to Django. With Models, Django can be able: - To create a database schema (CREATE TABLE questions) for your app - To create a Python database-access API for accessing Question and Choice objects You need to tell the Django that you have created a new app for your project. To include your app, you need to add a reference to its configuration class INSTALLED_APPS setting. The VotingsConfig class is in the votings/apps.py file, so the path of that file is "votings.apps.VotingsConfig". Now, add that path in the first_site/settings.py file in the INSTALLED_APPS section. The file will look like this after you added the path. # filename: first_site/settings.py INSTALLED_APPS = [ 'votings.apps.VotingsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Now, Django knows that you have created an app. Let's run the following command. $ python manage.py makemigrations votings You should see the following text in your command line. Migrations for 'votings': votings\migrations\0001_initial.py - Create model Choice - Create model Question - Add field question to choice By running the makemigrations command, you're telling Django that you have made some changes to your models and you had like the changes to be stored as migrations. You can also read your migration for your new model if you like at 'votings/migrations/0001_initial.py'. But it's not a human-readable format. Don't worry you have a command to display your model as a human-readable code. Run the following sqlmigrate command along with the app name. It returns the SQL $ python manage.py sqlmigrate votings 0001 You should see something similar to the following: BEGIN; -- -- Create model Choice -- CREATE TABLE "votings_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL); -- -- Create model Question -- CREATE TABLE "votings_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL); -- -- Add field question to choice -- ALTER TABLE "votings_choice" RENAME TO "votings_choice__old"; CREATE TABLE "votings_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "votings_question" ("id") DEFERRABLE INITIALLY DEFERRED); INSERT INTO "votings_choice" ("id", "choice_text", "votes", "question_id") SELECT "id", "choice_text", "votes", NULL FROM "votings_choice__old"; DROP TABLE "votings_choice__old"; CREATE INDEX "votings_choice_question_id_3502aac4" ON "votings_choice" ("question_id"); COMMIT; Now, run the migrate command to create those models in your database. $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, content types, votings, sessions Running migrations: Rendering model states... DONE Applying votings.0001_initial... OK The migrate takes all the migrations you have applied and runs them in your database. Migrations are very powerful in Django while developing the apps. This is specialized in upgrading your database live, without losing the data. Whenever you made changes to your models, you have to follow the 2 steps for the migration. - Run the python manage.py makemigrations to create migrations for those changes you made. - Run the python manage.py migrate to apply those changes to the database. Python Shell Now, let's get into the interactive Python shell. To invoke the Python shell run the following code. $ python manage.py shell Once you're in the shell, explore the database API >>> from votings.models import Question, Choice # Importing the model classes >>> Question.objects.all() <QuerySet []> >>> from django.utils import timezone # creating new question >>> s = Question(>> s.pub_date datetime.datetime(2018, 8, 12, 5, 6, 24, 408441, tzinfo=<UTC>) # changing the question text >>> s.>> s.save() >>> s.question_text 'Favourite Language' >>> Question.objects.all() <QuerySet [<Question: Question object (1)>]> Wait for a minute Let's fix that, by modifying the Question model in votings/models.py file and adding a __str__ method to both Question and Choice. # filename: first_site/votings/models.py from django.db import models class Question(models.Model): # other methods def __str__(self): return self.choice_text class Choice(models.Model): # other methods def __str__(self): return self.choice_text Save these changes and run the python manage.py shell again. >>> from votings.models import Question >>> Question.objects.all() # now, you see the choice_text <QuerySet [<Question: Favourite Language>]> Creating An Admin User Django provides a unique user interface for the Admin to manage the site. First of all, you have to create a superuser to use that admin panel provided by the Django. Run the following command to create a superuser. $ python manage.py createsuperuser Enter your username and press enter. Username: admin It asks for an email address, provides if you want or just ignore by pressing enter. The last step is to enter the password. It will ask to enter password the twice for the confirmation. Password (again): ********* Superuser created successfully. Django admin panel is activated by default. To see the admin panel first start the Django server by running the following command. $ python manage.py runserver Now, open a web browser and go to '', you will see the following login form. Now, try to login with your superuser username and password. You will see the Django admin index page once you logged in. You can see the Groups and Users sections. It's a default functionality provided by the Django to modify Users and create Groups if you want. Making Votings App Editable In Admin Panel You need to add the models you have created to the admin panel, in order to change the content. To do so, open the votings/admin.py file, and edit like this. # filename: first_site/votings/admin.py from django.contrib import admin from .models import Question admin.site.register(Question) Now, you have registered the Question. Django will display this, on the index page of the admin panel. Click Question there you will see all the questions that are in the database. Let's you choose one to change it. Click 'Favourite Language' question to edit it. In our votings app, we have the following four views. - Question index page - displays the latest questions - Question detail page - displays detail question with a vote form to vote - Question results page - display results for the particular question - Voting action - handles voting for a specific choice in a particular question Writing More Views Now, let's add a few more views to votings/views.py file. These views are a bit different as they take the arguments. # filename: first_site/votings) Write these new views into the votings/urls.py file by adding the path. # filename: first_site/votings/urls.py from django.urls import path from . import views urlpatterns = [ # ex: /votgins/ path('', views.index, name='index'), # ex: /votings/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /votings/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /votings/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] Take a look in your browser at '/votings/7/'. It'll run the detail() method and displays whatever ID you've provided in the URL. Try '/votings/7/results/' and '/votings/7/vote/', you'll see the respective view method. When somebody requests a page from your website – say, '/votings/7/, Django will load the first_site.urls Python module because it’s pointed to by the ROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the patterns in order. After finding the match at 'votings/', it strips off the matching text ('votings/') and sends the remaining text – '7/' – to the 'votings.urls' URLconf for further processing. There it matches '<int:question_id>/', resulting in a call to the detail() view like so: detail(request = <HttpRequest object>, question_id = 7) The question_id = 7 comes from the <int:question_id>. Using brackets helps to "Captures" a part of URL and sends it as a keyword to the view functions. Writing Some Meaningful View Function Here is the new index() view function, which displays all the questions from the database. # filename: first_site/votings/views.py from django.http import HttpResponse from .models import Question def index(request): question_list = Question.objects.all() output = '-----'.join([s.question_text for s in question_list]) return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged It's tough to see the web pages like that. You have to edit the design of the pages. To do so, you need HTML templates. First, create a directory called templates in your votings directory. Django will look for the templates in there. Within the templates, directory creates another directory called votings. This helps to avoid clashes with another app templates. Now, your directory for the template is 'votings/templates/votings/index.html'. Django will simply look for the 'votings/index.html'. Write the following code into the index template. # filename: first_site/votings/templates/index.html {% if question_list %} <ul> {% for question in question_list %} <li><a href="/votings/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} Now, you have to update the view function to use that template. # filename: first_site/votigns/views.py from django.shortcuts import render from .models import Question def index(request): question_list = Question.objects.all() context = {'question_list': question_list} return render(request, 'votings/index.html', context) The render() function takes the request object as its first argument, a template name as its second argument and a dictionary as its optional third argument. It returns a HttpResponse object of the given template rendered with the given context. Checking for the errors while rendering the template pages. # filename: first_site/votings/views.py from django.shortcuts import get_object_or_404, render from .models import Question # ... def detail(request, question_id): question = get_object_or_404(Question, pk = question_id) return render(request, 'votings/detail.html', {'question': question}) Templates For Other View Functions Back detail() view of our votings app. It will have a question variable. Write the following code into votings/detail.html. # filename: first_site/votings/templates/detail.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul> The template system uses the {{ variable name }} to display the variables. It uses {% code %} for the loops, conditionals, etc.., Read more about templates here. Removing HardCore URLs Hardcore URLs looks like this... <li><a href="/votings/{{ question.id }}/">{{ question.question_text }}</a></li> The problem arises with this when you have to use long URLs. You can avoid this by using the {% url %} tag. <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> The way this works is by looking up the URL definition as specified in the votings.urls module. You can see exactly where the URL name of detail is defined below: path('<int:question_id>/', views.detail, name = 'detail') NameSpace Names This is even more convenient to write the URLs. To use this, you've to define the app_name in the file votings/urls.py. The votings/urls.py file will look like this after adding the name. # filename: first_site/votings/urls.py from django.urls import path from . import views app_name = 'votings' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Change the URLs using the namespace like... <li><a href="{% url 'votings:detail' question.id %}">{{ question.question_text }}</a></li> Writing Simple Form Let's update the detail('votings/detail.html') template and create a form to allow the user to vote. # filename: first_site/votings/templates/detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'votings:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> Brief explanation - 'votings:vote' question.id %}. We set the method to POST. It's essential to set the method to POST to hide the sending data in the URL. - forloop.counter indicates how many times the for tag has through its loop - Since we're creating POST request, you have to take care of Cross Site Request Forgeries. But, simply Django take care of that. You just need to add {% csrf_token %} tag. Let's modify the vote() function to work as a real vote counter. # filename: first_site/votings, 'votings/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('votings:results', args=(question.id,))) Brief explanation - request.POST is a dictionary-like object which allows you to access the submitted data by key name. In this case, request.POST['choice'] returns the ID of selected choice, as a string. request.POST always return a string - Django also provides a request.GET for accessing the GET data in the same way. - request.POST['choice'] would raise a KeyError if the choice wasn't provided in the POST data. The above code checks for the KeyError and redisplays the question form with an error message if the choice isn't given. - After incrementing the choice count, the code returns an HttpResponseRedirect rather than the normal HttpResponse. HttpResponseRedirect takes a single argument: URL to which user redirects. reverse() function in the HttpResponseRedirect, the function helps to avoid the hardcore URLs. Int this case, redirect URL calls the results view to display the final page. To view the results page, you have to write the results view function. Let's write that view function... # filename: first_site/votings/views.py def results(request, question_id): question = get_object_or_404(Question, pk = question_id) return render(request, 'votings/results.html', {'question': question}) Now, create 'votings/results.html' template. # filename: first_site/votings/templates/results.html <h1>{{ question.question_text }}</h1> <ul> {% for chioce in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'votings:detail' question.id %}">Vote again?</a> Customizing App Web apps also need CSS, JS, and Images for the beautiful look. You can call them as static files. First, create a directory called static in your votings app directory. Django will look for static files there, similarly how it find the templates. Within static directory create another directory called votings and within create a file called style.css. Your file directory is votings/static/votings/style.css. Write the following code in style.css # filename: first_site/votings/static/style.css li a { color : green; } Next, add the following link in the top of votings/templates/votings/index.html. # filename: first_site/votings/templates/index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'votings/style.css' %}"> The {% static %} template tag generates an absolute URL of static files. Reload the webpage you will see the styling. If you didn't see any changes. Restart the server and check. You will get it. If you want to insert the images. Create a directory called anything(images) in the votings/static/votings/ directory and use the URL as "{% static 'votings/images/image-name'%}" Customizing Admin Panel You can modify the content in the admin panel. For, that you have to replace the admin.site.register(Question) with the following code: # filename: first_site/votings/admin.py from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fields = ['pub_date', 'question_text'] admin.site.register(Question, QuestionAdmin) The particular change makes the following output in your admin panel. That doesn't give much information about the fields and content. You can use fieldsets to do so. Change the admin code to: # filename: first_site/votings/admin.py from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fieldsets = [ ('Questions', {'fields': ['question_text']}), ('Date Information', {'fields': ['pub_date']}), ] admin.site.register(Question, QuestionAdmin) The first element of each tuple in fieldsets is the title of the fieldset. Here’s what our form looks like now: Adding Related Objects Register the Choice object same as Question. Add the following code in votings/admin.py. # filename: first_site/votings/admin.py from .models import Question, Choice admin.site.register(Choice) Now, choices will be available in the admin panel. Remove the register() for Choice and modify the Question registration code. # filename: first_site/votings/admin.py from django.contrib import admin from .models import Question, Choice class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ ('Questions', {'fields': ['choice_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) This will add Choices and Questions in the same page. By default, the choices have 3 fields. You can also have a choice to add choices. It takes a lot of screen space to display all the fields for entering related Choice objects. For that reason, Django offers a tabular way of displaying inline related objects. You just need to change the ChoiceInline to TabularInline. # filename: first_site/votings/admin.py class ChoiceInline(admin.TabularInline): # code Style Sheet (style.css) * { margin: 0; padding: 0; } body { font-family: sans-serif; } h1 { text-align: center; margin-top: 75px; } ul { margin: 50px; list-style-type: none; } li a { color: green; text-decoration: none; font-size: 25px; } form { margin: 50px 0 0 715px; } form input[type='radio'] { cursor: pointer; } form input[type='submit'] { border: 1px solid orangered; padding: 7px; background: none; font-size: 14px; border-radius: 3px; cursor: pointer; margin:15px 0 0 12px; } EndNote Congratulations! You have successfully completed your first Django App. Hope you enjoyed this tutorial and learned the basics of Django which helps, you to build some complex web apps. This is the first step to start with Web Development in Python. But, this is not the end. Go to the deeper sections of Django with the official documentation at Django. To learn more about Python, check out DataCamp's Intro to Python for Data Science course. It's free!
https://www.datacamp.com/community/tutorials/web-development-django
CC-MAIN-2019-35
refinedweb
5,853
61.43
I'm planning to write something like a soundmanager for my games. There will only be one such a manager and everything that makes noise will use it.What will be the better option variables and functions in a namespace. a class with only static members and functions singleton class What would you do, and why ?Thnx for stopping by;-) Perhaps one day we will find that the human factor is more complicated than space and time (Jean luc Picard)Current project: [Star Trek Project ] Join if you want ;-) Variable and function in a namespace if you want to stick to C++ style,Class and only static things if you wanna make it C style. In ANY case, not a singleton one. Why ? Because it looks awful. If I were doing it in C++ I would go with #1 as it's the case which will allow the best control over the api when mixed with other api's. "Code is like shit - it only smells if it is not yours"Allegro Wiki, full of examples and articles !! If there's one of those patterns that you've not practiced, it may be an opportunity to try. In this case, you can't shoot yourself in the foot : the sound system depends on a unique resource which is your PC's sound output, you are not likely to suddenly need multiple concurrent sound systems. Otherwise, I would use whatever looks the most like the neighboring code.For example if your code is mostly doing allegro5 calls like al_something(), I would prefer to have snd_something(), rather than Sound.Something() For a sound manager, I would probably go with an object, something like this: Focus on the interface you want more than anything else. --AllegroFlare • allegro.cc markdown • Allegro logo It is gonna use allegro anyway..but I need a nicer way of loading and playing sounds than the hard coded mess I have right now. I also need a way to play continues sound (loop) and stop the correct instance at the right moment. Right now I use a sample ID returned from al_play_sound and a bool that tells me if that instance is playing. But when you have a lot of looping sounds that must be stopped at the right moment.. it's not such a nice solution. I also noticed you cannot compare sampleIDs ... ?? Last time I had such need, I linked it the opposite way : If an emitted sound could be cancelled / interrupted later ("Ka-me-ha-me... - Ouch!"), the emitter passed his own identifier.It was a bit long ago, but I think I used the memory address of the calling class instance, stored as a void pointer. The code handling a game character would typically call play_sound("kamehama", this), or if the sound had to run to completion no matter what, it would be play_sound("boom", NULL)
https://www.allegro.cc/forums/thread/616287
CC-MAIN-2019-04
refinedweb
481
69.72
Problem with GridFilters and reopen Grid Problem with GridFilters and reopen Grid I have a Grid with GridFilter and when I show for the first times the grid it's work all fine. If I close the grid and after I reopen it the GridFilter doesn't appears. Why? The code is: WINConsulente_GRID = Ext.extend(Ext.grid.EditorGridPanel, { plugins: [new Ext.ux.grid.GridFilters({ filters:[ {type: 'string',dataIndex: 'cod'}, {type: 'string',dataIndex: 'username'/*,disabled: true*/}, {type: 'string',dataIndex: 'ragione_sociale'}, {type: 'string',dataIndex: 'telefono'}, {type: 'string',dataIndex: 'fax'}, {type: 'string',dataIndex: 'email'}, {type: 'string',dataIndex: 'website'}, {type: 'string',dataIndex: 'ref_nome'}, {type: 'string',dataIndex: 'ref_cognome'}, {type: 'string',dataIndex: 'ref_telefono'}, {type: 'string',dataIndex: 'ref_cellulare'}, {type: 'string',dataIndex: 'ref_email'}, {type: 'string',dataIndex: 'indirizzo'}, {type: 'string',dataIndex: 'cap'}, {type: 'string',dataIndex: 'frazione'}, {type: 'string',dataIndex: 'localita'}, {type: 'string',dataIndex: 'provincia'}, {type: 'string',dataIndex: 'cod_ateco'}, {type: 'string',dataIndex: 'desc_ateco'}, {type: 'string',dataIndex: 'cod_inail'}, {type: 'string',dataIndex: 'sede_inail'}, {type: 'string',dataIndex: 'iscrizione_inail'}, {type: 'string',dataIndex: 'pers1'}, {type: 'string',dataIndex: 'pers2'}, {type: 'numeric',dataIndex: 'pers3'}, /*{type: 'list',dataIndex: 'size',options: ['small', 'medium', 'large', 'extra large'],phpMode: true},*/ {type: 'date',dataIndex: 'data_creazione',beforeText: 'Prima del', afterText: 'Dopo il', onText: 'Il' }, {type: 'boolean',dataIndex: 'attivo'} ] })], I fixed it by myself...thanks for your support Strange behavior: position of filter box affects auto-apply of filter Strange behavior: position of filter box affects auto-apply of filter I noticed something strange... when using a string filter, when clicking drop-down menu in the header to fill in the filter, if the search field is to the right of the drop-down, the filter "auto applies" (ie. there is a slight delay when I finish typing (or press enter) and the filter automatically checks the checkbox and the filter is applied). However, if the column I want to filter is to the right side of the grid, and the filter field is forced to open to the left of the drop-down menu due to space limitations, the filter does NOT auto-apply if I pause typing or even press enter. I must manually check the check-box to have the filter applied. I'm using autoReload:false and local:true in case it matters. Hi there! I'd like to render the filter option list. Instead of having just the text ('small','medium','large',...), I'd like to have an icon first: Wanted code for rendered list: <img src="./smallIcon.gif"> Small <img src="./mediumIcon.gif"> Medium <img src="./largIcon.gif"> Large How to do this? Is it possible? Thanks for your answer Marc Minor bug: If the data associated with a column in a grid had NULL values, you'd get:PHP Code: Error: this.inputItem.getValue() is undefined Source File: Line: 87 Code: return this.inputItem.getValue().length > 0;Code: return (this.inputItem && this.inputItem.getValue() && (this.inputItem.getValue().length > 0)); SOLVED SOLVED I seem to have solved both of my problems... if you try to specify a filter:{ } definition in the defaults:{} config for the column model, it doesn't actually apply correctly. Once I explicitly put the filter:{ type:'string' } for each an every column, everything worked as expected. There is probably a bug somewhere, because it sort of worked before, just some strange behavior as explained. Just wanted to post my findings to help save others the headache of stepping through the code. Link to Grails implementation by Mike Cantrell not valid Link to Grails implementation by Mike Cantrell not valid The link to a Grails implementation (by Mike Cantrell) on the first post of this thread appears to be no longer active. Does anyone have access to or a copy of that code? Hi, I'm using this GridFilter extension with ExtJs 3.2.1. and it's really useful, good work so far. But I'm missing the options to search for <= and >=. Furthermore, it is not possible to specify a filter for "empty" or "not empty" values. For example I would like to see all rows that don't have any value in the filtered column. Are you planning to implement such filteroptions? Or is there anybody who implemented some of them already and would like to share the code? Thanks. how to make list of the grid filter fetch from store/ajax request? how to make list of the grid filter fetch from store/ajax request? Good morning, based on this example : I have difficulty to take "list" type of filters to fetch from store / ajax request, take a look at my script, what is wrong with it? Is there any suggestion master? PHP Code: //initial variable var dataKategori = ''; Ext.Ajax.request({ url: '/CI/ecommerce/getKategoriBarang', success: function(response){ dataKategori = response.responseText; } }); var filters = { ftype: 'filters', encode: true, local: false, filters: [{ type: 'list', dataIndex: 'namaKategori', => options: [dataKategori], phpMode: true }, { type: 'string', dataIndex: 'namaBarang' }, { type: 'numeric', dataIndex: 'harga' }, { type: 'numeric', dataIndex: 'jumlahStock' }, { type: 'numeric', dataIndex: 'sisa' }] }; Number of Filtered rows Number of Filtered rows Hi ! When gridFilter is active, how I can retrieve the number of filtered rows in my store and if a specific record is filtered ? Thank for your help.
http://www.sencha.com/forum/showthread.php?76185-GridFilters-enhanced-filtering-for-grids&p=615188&viewfull=1
CC-MAIN-2014-10
refinedweb
849
54.02
Member 68 Points Jun 06, 2015 09:42 AM|TheNutCracker|LINK VS 2015 shows that type System.Data.Entity.Infrastructure.DbQuery implements IEnumeraable but there is no method signature in the class definition of the DbQuery for the GetEnumerator() method as viewed in Visual Studios metadata representation of the class. Shouldn't the class definition be showing the method signature to give a more accurate representation of the actual definition of the Dbquery class type? Or am I way off base here? Is this information left out by design? Would it be considered duplicate data if the method signature for GetEnumerator() were shown in the class defintion of DbQuery? I am just trying to understand why its not shown. Maybe I am reading something the wrong way. Maybe this could be fixed in a future release or update of Visual Studio to more accurately reflect the class definitions that Visual Studio produces. Edit: Just thinking about this some more. I guess showing method signatures for a known interface could be considered visual clutter. I guess I just don't like the disconnect between what it shows and what it actually is. Maybe the developers could make it a choice to show or not to show? That seems to be a recurring theme of mine. Choice is always such a good thing. Star 14297 Points Jun 06, 2015 02:59 PM|gerrylowry|LINK i've got two related remarks that may or may not answer your question. ONE: carefully consider this tiny program: void Main() { Foo nutCrackerFoo = new Foo { FooInt32 = 666 }; Console.WriteLine (nutCrackerFoo.FooInt32); } The output is: 666 The rest of the code looks like this: public class Foo { public Int32 FooInt32 { get; set; } } if i mouse over nutCrackerFoo.FooInt32, i see only int Foo.FonInt32 which reveals little information. this change is not helpful with regards to what intellisense reveals: public Int32 FooInt32 { get; set; } // a child on planet earth dies of hunger every 10 seconds however, if i preceed the FooInt32 property with an XML comment, thus: /// <summary> /// a child on planet earth dies of hunger every 10 seconds /// </summary> public Int32 FooInt32 { get; set; } intellisense now shows for nutCrackerFoo.FooInt32: int Foo.FonInt32 a child on planet earth dies of hunger every 10 seconds Point: to a very great extent, what you see in the intellisense and in the Object Browser (see below this line) depends on the coder's use of XML comments: public int FooInt32 { set; get; } Member of ConsoleApplication2.Foo Summary: a child on planet earth dies of hunger every 10 seconds TWO: if you really want to know, you must go to the Reference source: EDIT: while it's very evil that children are dying of hunger and hunger related causes while many of the first world middle class waste food, which is one point that i'm making. the point relevant to your thread is that unless the coders are diligent, the intellisense is only as useful as the effort that is taken to make it useful. END EDIT. Member 68 Points Jun 06, 2015 06:29 PM|TheNutCracker|LINK Thank you for your input. It seems maybe I should have been more clear in my question. The metadata I was referring to specifically was the dynamically generated C# code file that gets opened in the editor as though it were an existing code file of your project. But I am thinking your point may still apply to that metadata c# source code file as much as it does the intellisense comments. The general point is that It probably has something to do with how much of the class definition was actually adorned with the proper compiler attributes by the relevant programmer. If the programmer who wrote the class definition didn't put much effort in, then you probably won't get the most accurate representation back out. Star 14297 Points Jun 06, 2015 06:52 PM|gerrylowry|LINK Yes, for all intents and purposes, i think that you are correct. Some of what you hope to see may be controlled by one or more build options, and/or project properties, and/or other properties/options. For example, in the Build page for Project, <your application name> Properties, in the Output section, there is a checkbox for XML documention file. For the application that i created above, here is the XML file; <?xml version="1.0"?> <doc> <assembly> <name>ConsoleApplication2</name> </assembly> <members> <member name="P:ConsoleApplication2.Foo.FooInt32"> <summary> a child on planet earth dies of hunger every 10 seconds </summary> </member> </members> </doc> N.B.: AFAIK, the intellisense and the source code come from the same location ... if the XML documention gets left behind, it is not available elsewhere. When everything is in a single solution, all projects in that solution likely see all of each others' metadata if you really want to know more about this, do read all of the pages that branch off of this one: "XML Documentation Comments (C# Programming Guide)" Star 9555 Points Jun 09, 2015 07:17 PM|Paul Linton|LINK I don't know your particular case but what you describe seems reasonable to me. An instance of DbQuery can be cast to IEnumerable. This does not mean that the class DbQuery implements the IEnumerable interface itself. The implementation of IEnumerable may be provided by a base class that DbQuery derives from. So, I would expect the metadata for the class DbQuery to show the methods that are part of the DbQuery class. Any methods defined in a base class that DbQuery derives from would be shown in the metadata for that base class. 4 replies Last post Jun 09, 2015 07:17 PM by Paul Linton
https://forums.asp.net/t/2054428.aspx?Accuracy+of+Visual+Studio+Class+Definitions+offered+up+to+Developers+using+MetaData
CC-MAIN-2021-25
refinedweb
954
59.94
I attempted to do this using a for loop, but it doesn't seem to be working out well. I can't find my error. This is what I have. - Code: Select all class AIEntity(object): def __init__(self,ID): self.ID = ID #Name for entity self.LArm = 10 #Left Arm Health self.RArm = 100 #Right Arm Health self.LLeg = 100 #Left Leg Health self.RLeg = 10 #Right Leg Health self.Torso = 10 #Torso Health self.Head = 100 #Head Health self.Body = {self.LArm:"Left Arm", self.RArm:"Right Arm", self.LLeg:"Left Leg", self.RLeg:"Right Leg", self.Torso:"Torso", self.Head:"Head"} self.checkBody() def checkBody(self): for value, part in self.Body.iteritems(): if value != 100: print value print part x = AIEntity("Test") The output is only 10 Torso So it is only printing the x.Torso value. Idk why. Any help? Thanks.
http://www.python-forum.org/viewtopic.php?p=15310
CC-MAIN-2016-07
refinedweb
146
64.98
Sunday, August 7, 2016¶ An equivalent of startproject for Lino¶ Once more thanks to Grigorij who reported his problems with the A Local Exchange Trade System. His report made me see the next steps I can do for making the Developer's Guide better. Two immediate changes to the current A Local Exchange Trade System: - Remove the last line from your models.pyfile (the one which says from .ui import *) and rename ui.pyto desktop.py. This is because we now have layout_name. - In your settings.py, change “self.modules” to “self.actors”. (See lino.core.site.Site.actors) Note, Grigorij, that these changes are not related to your problems. Your problems come probably because the tutorial uses somewhat hackerish manage.py and settings.py files. But more importantly, I started to convert this tutorial into an independent project on GitGub so that it can serve as a template for new Lino applications: Lino Algus. TODO: Write a tutorial about how to use Lino Algus. Adapt A Local Exchange Trade System. I had the following error message when doing inv release: error: Upload failed (403): You are not allowed to edit 'lino-algus' package information This was simply because on the first release on PyPI you must say setup.py register instead of setup.py sdist upload. ImportError: No module named appy_renderer¶ This one happened on a production server: Traceback (most recent call last): File "env/repositories/xl/lino_xl/lib/lists/models.py", line 41, in <module> from lino_xl.lib.appypod.mixins import PrintLabelsAction File "env/repositories/xl/lino_xl/lib/appypod/mixins.py", line 34, in <module> from .appy_renderer import AppyRenderer ImportError: No module named appy_renderer The problem is here: $ ls -al env/repositories/xl/lino_xl/lib/appypod total 96 drwxrwxr-x 3 admin www-data 4096 Aug 7 06:25 . drwxrwxr-x 39 admin www-data 4096 Aug 6 09:41 .. -rw-rw---- 1 admin admin 24403 Aug 6 09:40 appy_renderer.py -rw-rw---- 1 root root 18439 Aug 7 06:25 appy_renderer.pyc -rw-rw-r-- 1 admin www-data 3839 Aug 5 21:04 choicelists.py -rw-rw-r-- 1 root root 3903 Aug 7 06:25 choicelists.pyc drwxrwxr-x 2 admin www-data 4096 Aug 5 21:04 config -rw-rw-r-- 1 admin www-data 1853 Aug 5 21:04 __init__.py -rw-rw-r-- 1 www-data www-data 1576 Aug 6 09:41 __init__.pyc -rw-rw-r-- 1 admin www-data 4999 Aug 5 21:04 mixins.py -rw-rw-r-- 1 www-data www-data 5293 Aug 6 09:41 mixins.pyc -rw-rw-r-- 1 admin www-data 1571 Aug 5 21:04 models.py -rw-rw-r-- 1 root root 1147 Aug 7 06:25 models.pyc The directory doesn’t have the SETGID sticky bit set. The cron job which does a daily snapshot (it runs every morning at 6:25) is running as root. While working on this I updated File permissions (which becomes better but it still work in process).
http://luc.lino-framework.org/blog/2016/0807.html
CC-MAIN-2018-05
refinedweb
506
60.21
The following topic discuss difficulties you may encounter with an earlier application and the new run-time libraries. Differences in iostream Implementation Earlier Projects Built with No Default Libraries C++ Exception Handling Must Be Enabled for the Standard C++ Library The old iostream library was removed beginning in Visual C++ .NET 2003. The main difference between the Standard C++ Library and previous run-time libraries is in the iostream library. Details of the iostream implementation have changed, and it may be necessary to rewrite parts of your code that use iostream if you want to link with the Standard C++ Library. You will have to remove any old iostream headers (fstream.h, iomanip.h, ios.h, iostream.h, istream.h, ostream.h, streamb.h, and strstrea.h) you have included in your code and add one or more of the new Standard C++ iostream headers (<fstream>, <iomanip>, <ios>, <iosfwd>, <iostream>, <istream>, <ostream>, <sstream>, <streambuf>, and <strstream>, all without the .h extension). The following list describes behavior in the new Standard C++ iostream library that differs from behavior in the old iostream library. In the new Standard C++ iostream library: open functions do not take a third parameter (the protection parameter). You cannot create streams from file handles. With a couple of exceptions, all names in the new Standard C++ Library are in the std namespace. See Using C++ Library Headers for more information. You cannot open ofstream objects with the ios::out flag alone. The ios::out flag must be combined with another ios enumerator in a logical OR; for example, with ios::in or ios::app. ios::good no longer returns a nonzero value after reaching the end-of-file because the eofbit state is set. ios::setf(_IFlags) should not be used with a flag value of ios::dec, ios::oct, or ios::hex unless you know that none of the base flags are currently set. The formatted input/output functions and operators assume that only one base is set. Instead, use ios_base. For example, setf( ios_base::oct, ios_base::basefield ) clears all base information and sets the base to octal. ios::unsetf returns void instead of the previous value. istream::get( char& _Rch ) does not assign to Rch if there is an error. istream::get( char* _Pch, int _Ncount, char _Delim ) is different in three ways: When nothing is read, failbit is set. An eos is always stored after characters extracted (this happens regardless of the outcome). A value of -1 for _Ncount is an error. istream::seekg with an invalid parameter does not set failbit. The return type streampos is a class with overloaded operators. In functions that return a streampos value (such as istream::tellg, ostream::tellp, strstreambuf::seekoff, and strstreambuf::seekpos), you should cast the return value to the type required: streamoff, fpos_t, or mbstate_t. The first function parameter (_Falloc) in strstreambuf::strstreambuf( _Falloc, _Ffree ) takes a size_t argument, not a long. In addition to the above changes, the following functions, constants, and enumerators that are elements of the old iostream library are not elements of the new iostream library: attach member function of filebuf, fstream ifstream, and ofstream fd member function of filebuf, fstream ifstream, and ofstream filebuf::openprot filebuf::setmode ios::bitalloc ios::nocreate ios::noreplace ios::sync_with_stdio streambuf::out_waiting streambuf::setbuf (use rdbuf -> pubsetbuf for the same behavior) You can build a project without default libraries by selecting /NODEFAULTLIB. If your previous project was built with no default libraries and you want to make iostream calls, you must name one of the new Standard C++ run-time libraries (Libcp.lib, Libcpmt.lib, Msvcprt.lib, and so on) or one of the old iostream run-time libraries (Libci.lib, Libcimt.lib, Msvcirt.lib, and so on) in order to link with the proper library. In previous Visual C++ versions (4.1 and earlier), the run-time library names were Libc.lib, Libcmt.lib, and Msvcrt.lib. These libraries included the old iostream library. The old iostream library has now been removed from these libraries. If you do not choose to ignore default libraries and you include old iostream header files in your code, the old iostream run-time libraries (Libci.lib, Libcimt.lib, Msvcirt.lib, and so on) are linked by default. However, if you have chosen to ignore default libraries and have manually added one of the early run-time libraries, your iostream calls will now break. Any file that uses the Standard C++ Library must be compiled with C++ exception handling enabled. For more information, see /GX.
http://msdn.microsoft.com/en-us/library/8h8eh904.aspx
crawl-002
refinedweb
756
63.09
In this tutorial, I'll show you how to take advantage of the new 2D Tools included in Unity to create a 2D Game. 1. Application Overview In this tutorial, you'll learn how to create a Unity 2D project and create a mobile game using C# and Unity. The objective of the game is to shoot a teleporting ray at the cows before they can reach the safety of the barn. In this project you will learn the following aspects of Unity development: - setting up a 2D project in Unity - becoming familiar with the Unity interface - creating a Prefab - attaching scripts to game objects - working with physics collisions - using timers 2. Create a New Unity Project Open Unity and select New Project from the File menu to open the new project dialog. Select a directory for your project and set Set up defaults for to 2D. 3. Build Settings In the next step, you're presented with Unity's interface. Set the project up for mobile development by choosing Build Settings from the File menu and selecting your platform of choice. Unity can build for iOS, Android, BlackBerry, and Windows Phone 8, which is great if you plan to create a mobile game for multiple platforms. 4. Devices Since we're about to create a 2D game, the first thing we need to do after selecting the platform we're targeting, is choosing the size of the artwork that we'll use in the game. Because Android is an open platform, there are many different And for Widows Phone and BlackBerry: - Blackberry Z10: 720px x 1280px, 355 ppi - Nokia Lumia 520: 400px x 800px, 233 ppi - Nokia Lumia 1520: 1080px x 1920px, 367 ppi Even though we'll be focusing on the iOS platform in this tutorial, the code can be used to target any of the other platforms. 5. Export Graphics Depending on the device you're targeting, you may need to convert the artwork to the recommended size and pixel density. You can do this in your favorite image editor. I've used the Adjust Size... function under the Tools menu in OS X's Preview application. 6. Unity Interface Make sure to click the 2D button in the Scene panel. You can also modify the resolution that's being used to display the scene in the Game panel. 7. Game Interface The user interface of our game will be simple. You can find the artwork for this tutorial in the source files of this tutorial. 8. Language You can use one of three languages in Unity, C#, UnityScript, a language similar to JavaScript in terms of syntax, and Boo. Each language has its pros and cons, but it's up to you to decide which one you prefer. My preference goes to the C# syntax, so that's the language I'll be using in this tutorial. If you decide to use another language, then make sure to take a look at Unity's Script Reference for examples. 9. 2D Graphics Unity has built a name for being a great platform for creating 3D games for various platforms, such as Microsoft Xbox 360, Sony PS3, Nintendo Wii, the web, and various mobile platforms. While it has always been possible to use Unity for 2D game development, it wasn't until the release of Unity 4.3 that it included native 2D support. We'll learn how to work with images as sprites instead of textures in the next steps. 10. Sound Effects I'll use a number of sounds to improve the game experience. The sound effects used in this tutorial can be found at Freesound.org. 11. Import Assets Before we start coding, we need to add our assets to the Unity project. Theres are several ways to do this: - select Import New Asset from the Assets menu - add the items to the assets folder in your project - drag and drop the assets in the project window After completing this step, you should see the assets in your project's Assets folder in the Project panel. 12. Create Scene We're ready to create the scene of our game by dragging objects to the Hierarchy or Scene panel. 13. Background Start by dragging and dropping the background into the Hierarchy panel. It should then appear in the Scene panel. Because the Scene panel is set to display a 2D view, you'll notice selecting the Main Camera in the Hierarchy shows a preview of what the camera is going to display. You can also see this in the game view. To make the entire scene visible, change the Size value of the Main Camera to 1.6 in the Inspector panel. 14. Ship The ship is also a static element the player won't be able to interact with. Position it in the center of the scene. 15. Barn Select the barn from the Assets panel and drag it to the scene. Position it as illustrated in the screenshot below. 16. Barn Collider To make sure the barn is notified when a cow hits it—enters the barn—we need to add a component, a Box Collider 2D to be precise. Select the barn in the scene, open the Inspector panel, and click Add Component. From the list of components, select Box Collider 2D from the Physics 2D section. Make sure to check the Is Trigger box. We want the cow to react when it hits the door of the barn so we need to make the collider a bit smaller. Open the Inspector and change the Size and Center values of the collider to move the box closer to the door of the barn. 17. Barn Collision Script It's time to write some code. We need to add a script so the application can respond to the collision when a cow enters the barn. Select the barn and click the Add Component button in the Inspector panel. Select New Script and name it OnCollision. Remember to change the language to C#. Open the newly created file and add the following code snippet. using UnityEngine; using System.Collections; public class OnCollision : MonoBehaviour { void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.name == "cow(Clone)") { /* Play the save cow sound */ audio.Play(); /* Destroy the cow */ Destroy(other.gameObject); } } } The snippet checks for a collision between the object to which the script is linked, the barn, and an object named cow(Clone), which will be an instance of the cow Prefab that we'll create later. When a collision takes place, a sound is played and the cow object is destroyed. 18. Barn Sound To play a sound when a cow hits the barn, we first need to attach the sound to the barn. Select it from the Hierarchy or Scene view, click the Add Component button in the Inspector panel, and select Audio Source from the Audio section. Uncheck Play on Awake and click the little dot on the right, below the gear icon, to select the barn sound. You can increase the size of the icons in Unity's user interface (gizmos) by clicking Gizmos in the Scene panel and adjusting the position of the slider. 19. Ray Drag the ray graphic from the Assets panel to the scene and add a collider to it. This is necessary to detect a collision with the unlucky cow. Check the Is Trigger option in the Inspector panel. 20. Ray Script Create a new script by repeating the steps I outlined a few moment ago. Name the script Bullet and replace its contents with the following code snippet: using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public AudioClip cowSound; // Use this for initialization void Start() { renderer.enabled = false; /* Makes object invisible */ } // Update is called once per frame void Update() { /* Get main Input */ if (Input.GetButton("Fire1")) { renderer.enabled = true; /* Makes object visible */ /* Play the ray sound */ audio.Play(); } if (renderer.enabled == true) { transform.position += Vector3.down * (Time.deltaTime * 2); } /* Check for out of bounds */ if (this.transform.position.y < -1.5) { transform.position = new Vector2(0.08658695f, 0.1924166f); /* Return bullet to original position */ renderer.enabled = false; } } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.name == "cow(Clone)") { AudioSource.PlayClipAtPoint(cowSound, transform.position); /* Destroy the cow */ Destroy(other.gameObject); transform.position = new Vector2(0.08658695f, 0.1924166f); /* Return bullet to original position */ renderer.enabled = false; } } } That's a lot of code, but it isn't complicated. Let's see what is happening. First, we create an AudioClip instance named cowSound, which we'll use to store an audio file. This is just another technique to play a sound if you don't want to add two audio components to the object. We declare the variable as public so we can access it from the Inspector. Click the little dot on the right of cowSound and select the audio file. We then make the ray invisible by disabling its renderer. We use the same object so we can save resources, which is an important optimization for less powerful devices. We detect touches on the screen, which make the ray visible and play back the ray sound (see below). If the object is visible, it means that it should be going down to hit a cow. There's also code to detect if the ray is outside the scene's bounds. If this is the case, we reposition it, ready to fire again (check the ray's x and y values in the Inspector). The last part checks whether the ray hits a cow. If it does, it plays the cow sound and destroys the cow. The ray is then made invisible and repositioned at its original position, ready to fire again. 21. Ray Audio Source To add the audio for the ray, select it in the Hierarchy or Scene view and click Add Component in the Inspector panel. Select Audio Source from the Audio section. Uncheck Play on Awake and click the little dot on the right to select the sound file. 22. Add a Cow Drag the graphic for the cow from the Assets panel and position it in the scene as shown below. 23. Rigid Body 2D To detect a collision, at least one of the colliding objects needs to have a RigidBody2D component associated with it. As the cow can collide with both the barn and the ray, it's best to add the component to the cow. 24. Cow Collider We also need to add a collider to the cow so we can detect collisions with the barn and the ray. Make sure to check the Is Trigger checkbox in the Inspector. 25. Move Cow Script Add a script component to the cow and replace its contents with the following: using UnityEngine; using System.Collections; public class MoveCow : MonoBehaviour { public Vector3 moveSpeed; public float spawnTime = 2f; public float spawnDelay = 2f; // Use this for initialization void Start() { moveSpeed = Vector3.left * Time.deltaTime; InvokeRepeating("ChangeSpeed", spawnDelay, spawnTime); } void ChangeSpeed() { moveSpeed = new Vector3(Random.Range(-1, -2), 0, 0) * 0.05f; } // Update is called once per frame void Update() { transform.position += moveSpeed; } } The MoveCow class animates the cow across the screen using a variable named moveSpeed. The InvokeRepeating method changes the speed of the cow to make it sprint from the moment it reaches the center of the scene. This makes the game more challenging. 26. Create Cow Prefab With the necessary components added to the cow, it's time to convert it to a Prefab. What is a Prefab? Let's consult the Unity Manual: ." If you're coming from Flash and ActionScript, then this should sound familiar. To convert the cow to a prefab, drag the cow from the Hierarchy panel to the Assets panel. As a result, the name in the Hierarchy will turn blue. Converting the cow to a prefab allows us to reuse it, which is convenient as it already contains the necessary components. 27. Spawner Script The Spawner script is responsible for the cows to appear. Open MonoDevelop—or your favorite C# editor—and create a new script: using UnityEngine; using System.Collections; public class Spawner : MonoBehaviour { public float spawnTime = 2f; public float spawnDelay = 2f; public GameObject cow; // Use this for initialization void Start() { InvokeRepeating("Spawn", spawnDelay, spawnTime); } void Spawn() { /* Instantiate a cow */ GameObject clone = Instantiate(cow, transform.position, transform.rotation) as GameObject; } } We call the InvokeRepeating method to spawn cows using the values set by spawnTime and spawnDelay. The GameObject cow is set to public and is created using the Inspector. Click the little dot on the right and select the cow Prefab. 28. Spawner Game Object To instantiate the cow prefab, we'll use the graphic of the cow we've added to the scene a few minutes ago. Select it and remove its components. Then add the Spawner script. 29. Testing It's time to test the game. Press Command + P to play the game in Unity. If everything works as expected, you are ready for the final steps. 30. Player Settings When you're happy with your game, it's time to select Build Settings from the File menu and click the Player Settings button. This brings up the Player Settings in the Inspector panel where you can adjust the parameters for your application. 31. Application Icon Using the graphics you created earlier, you can now create a nice icon for your game. Unity shows you the required sizes, which depend on the platform you're building for. 32. Splash Image The splash or launch image is displayed when the application is launched. 33. Build Once your project is properly configured, it's time to revisit the Build Settings and click the Build Button. That's all it takes to build your game for testing and/or distribution. 34. Xcode If you're building for iOS, you need Xcode to build the final application binary. Open the Xcode project and choose Build from the Product menu. Conclusion In this tutorial, we've learned about the new 2D capabilities of Unity, collision detection, and other aspects of game development with Unity. Experiment with the result and customize it to make the game your own. I hope you liked this tutorial and found it helpful. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/working-with-unitys-2d-tools--cms-20305
CC-MAIN-2018-39
refinedweb
2,394
64.1
This one is probably the most useful of the lot ;-) >From: Michel Pelletier <[EMAIL PROTECTED]> >Greetings, > >Well, Jim, Evan, Brian and I pow-wowed yesterday and came up with an >interesting change. The world 'Method' is too overlaoded, as it means >too much to too many people. Also, Python Methods don't work like >methods in python, which was my argument, but they are very useful and >there are sound reasons for them working like they do (which J, E and B >convinced me of yesterdat). We have decided to change the name of >Python Methods to something else, the current candidate being 'Python >Script'. > >'Script' objects make a lot of sense, they don't overload the concept of >methods, they describe an action that people commonly want to do (script >the web) and they clear up a lot of potential confusion for newbie and >old-hat alike. > >The bonus for all of this is that the only thing that needs to change is >the name. Which name is still an issue though, and we want your input. >what do you think of the idea of Perl Script objects? > >The other issue, for the sake of documentation, is variable binding >(which was the root of our disagreement yest. Python Methods do not bind >variables and argument like methods in python do). From what I can see, >Perl Methods seem to get 'self' pass in as a first argument. Is this >all there is too it or are there more details? Python Methods have five >special variables (defined on the bindings tab) that get created in the >namespace of the method. Should perl methods work the same way and not >have special variables passed in as arguments? This would probably be >more consistent with the Python model, and since 'self' will probably >not be the name of the variable bound to either the container or the >context it should be more explicit for perl methods also. > >What do you think? > >-Michel _______________________________________________ Zope-Dev maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - ) - [Zope-dev] Method binding Chris Withers - [Zope-dev] Michel's Reply Chris Withers - [Zope-dev] My $0.02
https://www.mail-archive.com/zope-dev@zope.org/msg02695.html
CC-MAIN-2016-44
refinedweb
362
76.96
The use of graphical processing units (GPUs) rapidly improves the processing time for machine learning models. ArcGIS Notebook Server can take advantage of NVIDIA GPUs on its host machine once some additional steps are performed. Note: Starting at 10.8, the built-in ArcGIS Notebook Server runtimes include the Conda CUDA Toolkit to enable GPU support. Previously, this workflow required building a custom runtime to include CUDA. The following workflow has two primary goals. The first is to install NVIDIA drivers and runtime, which will allow your site's Docker component to build GPU-ready containers. The second is to create a copy of the Advanced notebook runtime that's configured to use the NVIDIA runtime. All ArcGIS Notebooks opened using this runtime will launch in GPU-ready containers. Aside from that, the new runtime will keep all the Python libraries of the Advanced notebook runtime. Once ArcGIS Notebook Server has been installed and configured, follow these steps. If your ArcGIS Notebook Server site has multiple machines, follow steps 1 through 3 on all machines. - Install the appropriate NVIDIA drivers on each machine in your site. See the NVIDIA website for complete information. - Install the nvidia-docker 2.0 runtime on the machine so that notebook containers can take advantage of GPUs. Refer to the NVIDIA-Docker repository on GitHub for the downloads and documentation pertaining to your specific OS. - Run the following command on each machine to ensure that your NVIDIA elements are properly installed: docker run --runtime=nvidia --rm nvidia/cuda:9.0-base nvidia-smi - Sign in to your ArcGIS Enterprise portal as an administrator and open ArcGIS Notebook Server Manager. - Open the Settings page, and click Runtimes. - Click the Edit icon for the runtime labeled ArcGIS Notebook Python 3 Advanced. Copy the value given for its Image ID. Click Cancel to exit the editor. - From the Runtimes page, click Register Runtime. - On the Register Runtime page, provide an appropriate name (such as GPU Runtime) and give the version as 10.9. For the Image ID value, add the value you copied in step 5. - Set the Docker Runtime value to be nvidia. Click Register Runtime to confirm. - Verify you have successfully configured ArcGIS Notebook Server to use NVIDIA GPUs. As a portal member with the Advanced Notebooks privilege, create a new blank notebook. When you specify the runtime of the notebook, select your new GPU-ready runtime. Copy the following into a notebook cell and run the cell. The output returns as True, because the torch.cuda package requires GPUs to run. import torch torch.cuda.is_available() - Run the following command in a new cell to view your machine's GPU configuration: !nvidia-smi If you want to remove the capacity for your site to use GPUs, open the Runtimes page in ArcGIS Notebook Server Manager and delete the runtime you created in this workflow.
https://enterprise.arcgis.com/en/notebook/latest/administer/linux/configure-arcgis-notebook-server-to-use-gpus.htm
CC-MAIN-2021-43
refinedweb
479
58.89
[...] I think that this [bound methods] really does belong more into languages that have method calls as field access plus call like Python and JavaScript. Incidentally Javascript doesn't really have this. It was most confusing to me as a Python programmer. Bob Ippolito described the situation well. Yup, this is similar to ruby-contract -- but still, I think that wrappers are not always the best solution to problems. If a good implementation of selector namespaces can be found I think it is besser for solving this specific problem. (Even though it has not been a serious problem so far. -- I guess it is part of the Ruby mindset that being tolerant is usually a good idea, even if it might mean that you can step onto others toes.) In practice most Python programmers get by just fine when they do stuff that risks name collision. Some people say it's just because the applications are small and reuse not that common; and it's people with an eye to big systems (like Zope 3 people) that are pushing for more isolation. I'm still not sure if it's easier just to deal with problems when they occur, instead of trying to avoid all possible conflicts. Especially in an open-source ecosystem -- when all code is open to change, and there is no "my code" and "not my code" -- I think problem-avoidance isn't as important as intelligent and cooperative problem-solving. And of course we both have the option to monkey patch (fix the code in-process, instead of on-disk).
http://www.ianbicking.org/rubypythonpower-comment-30.html
CC-MAIN-2018-05
refinedweb
264
68.7
I am a struggling young software developer, and I often find myself surfing the web in search of various solutions for various problems, and CodeProject seems to be there for me most of the times. This time I encountered another problem: I wanted to create a setup and deployment project which passes arguments during installation time from the user to the configuration file of my application. It took me a while but I managed to find a way to make it work. In this article, I will demonstrate how to create a Windows setup project which receives a string from the user and places that string in the configuration file of the application during the installation. In brief, the whole process is as follows: Installer Install Commit Rollback Uninstall Let's get to work... First of all, I created a simple Windows application that simply gets a path from the configuration file and sets the background image of the form to that path. The app.config file looks like this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="FilePath" value="..\..\Images\penguin.png"/> </appSettings> </configuration> And the constructor of the form gets that string and sets the BackgroundImage property to the given string which, in fact, represents the image file. BackgroundImage The constructor looks like this: public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // Get the path for the background Image from app.Config string filePath = ConfigurationSettings.AppSettings["FilePath"]; // Set the BackgroundImage property Image backImage = Image.FromFile(filePath); this.BackgroundImage = backImage.GetThumbnailImage( this.Width, this.Height, null, IntPtr.Zero); this.Refresh(); } Don't forget to add a reference to the System.Configuration namespace in order to gain access to ConfigurationSettings.AppSettings. System.Configuration ConfigurationSettings.AppSettings Now, what I want to do is create a setup and deployment project for my desktop application. In order to do that, what we need is to add a new project to our solution and select the setup and deployment project option as shown in the image below, and choose the "Setup Project" option in the Templates option. Image 1: adding a setup and deployment project. After adding the project, we can see the 'File System' window: Image 2: file system window. This window has three default folders: Image 3: Adding primary output to the Application Folder By right clicking the root ('File System On Target Machine'), one can add more folders to the tree in the 'File System' window, were each folder installs the items placed with in it to a similar location on the target computer. Up until now, all I did was simply install my application on the target computer and create its shortcut in the desktop. When we run the installation wizard, we see only three screens: Welcome screen, Installation Folder screen (in which we specify were to install our application, and it is in that location that the installation wizard will install all the items we put in the 'Application Folder' node in the 'File System' eindow), and the Confirm screen which is the last screen before the installation finishes. Now, let's play with the installation wizard and add some more screens. First of all, we need to right click the setup project in the Solution Explorer, and in the 'View' option, we choose 'User Interface' (as shown in the image below). In this screen, we see a tree that specifies the order of the screens of the installation wizard. Under the Install node, you can see the three default screens. I added a screen with a textbox for the user to enter a string, by right clicking the Install node and choose the 'Add Dialog' option (Image 5). You will see a number of dialogs you can add. I chose the TextBoxes (A) dialog. Image 4: view the 'User Interface' window to add more dialogs to the installation wizard. Image 5: add a dialog to the 'User Interface' window. In the TextBoxes dialog that I add to my wizard, there are, by default, four textboxes, but I need only one, so I simply change the other three textboxes' 'Visible' property to false in the Properties window. In the Properties window, you can also play with the text in the banner and the body of the dialog. Visible false After we add the dialog, we need to somehow perform during the installation an action that will take the string from the textbox in the newly added dialog, and update the configuration file. Now, we write a method that will be called during the installation process. To do that, we need to create a class that will derive from the class Installer, and add the attribute [RunInstaller(true)]. The new class can override the four main methods: Install, Uninstall, Commit, and Rollback. [RunInstaller(true)] [RunInstaller(true)] public class InstallHelper : Installer { * * * In this class, I override the Install method in which I will get the text from the new textbox, and update the configuration file. However, in order that the installation wizard will turn to our method, we first need to add a Custom Action. By right clicking on the setup project in the Solution Explorer window and clicking View->Custom Actions, we see the 'Custom Actions' window which presents to us a tree with four nodes: Install, Commit, Rollback, and Uninstall. What I need now is to "connect" the installation wizard to my 'Install' method, so I added a new custom action by right clicking the Install node and clicking on 'Add Custom Action': Image 6: Custom Actions window. After doing so, a window pops up in which I select my application primary output (in my application, I have the 'InstallerHelper' class): InstallerHelper Image 7: adding a Custom Action Note that for each method we can override (in the class that derives from 'Installer'), we have a node in the Custom Actions window. Now when the install wizard will run, it will perform my overridden 'Install' method. Now what we need to do is: Text TextBox For exposing the Text property, we go to the Properties window of the newly added custom action. Here, we can see a property named 'CustomActionData', and here, I declare my Text property in the following format: /<key>=[<property name>]. My specific declaration was '/PathValue=[EDITA1]' because PathValue was the name I gave, and with this name, I will get the property value in the code later on, and the TextBox name was 'EDITA1': CustomActionData /<key>=[<property name>] /PathValue=[EDITA1] PathValue EDITA1 Image 8: update the CustomActionData property Note that you can add as much declarations as you want. Now, we can finally write some code. To read the value in the TextBox from the code, all we need to do is in the 'Install' method we override, read the value from Context.Parameters[key] were the 'key' is actually the key we write when we declare the property (when we expose the textbox). In my case, the key is, of course, 'PathValue'. Context.Parameters[key] key Note that the property Context.Parameters's default value does not contain the Text property of our new textbox. We had to expose it in the Custom Action Properties window. Context.Parameters Another important fact is that after installing the application, the configuration file exists in the target computer under the name of the executable file plus the ending ".config". For instance, if after the installation, the executable file is "MyApp.exe", then in the same directory, you will find the configuration file "MyApp.exe.config" (assuming of course that the application has a configuration file). Another important value in the 'Context.Parameters' property is the path to the executable file that will be installed to the target computer. Since we know that the configuration file has exactly the same path plus the ending ".config", we have the path to the configuration file. // Get the path to the executable file that is being installed on // the target computer string assemblypath = Context.Parameters["assemblypath"]; string appConfigPath = assemblypath + ".config"; All that is left to be done is to use the 'XmlDocument' class to update the configuration file which we have the path to. You can view my code in the files attached. XmlDocument Hope this will help you like you always help me. Very important: note that the user can't enter a string with spaces in the textbox. For some reason unknown to me, whenever I enter a string with spaces, the installation fails to work. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here this is my blog post about how to make .net setup project. Dim myInputFromTextboxA As String = Me.Context.Parameters.Item("HostName") Dim myPropertyA As String Dim myPropertyB As String Dim myInputArrayTextBoxA() As String = myInputFromTextboxA.Split(";"c) Dim myInputFromCheckboxA As String = Me.Context.Parameters.Item("Properties") Dim myInputArrayCheckboxA() As Objecet = myInputFromCheckbox.Split(";"c) Dim myInput As String = Me.Context.Parameters.Item("HostName") subStrings = myInput.Split(New String() {"/Properties="}, StringSplitOptions.None) myInputFromTextbox = subStrings(0) myInputFromCheckbox = subStrings(1) Dim myInputArray() As String = myInputFromTextbox.Split(";"c) 'Extract the text box data Dim Host1 As String = Me.Context.Parameters.Item("HostName1") Dim Host2 AS String = Me.Context.Parameters.Item("HostName2") 'Extract the checkbox values Dim CheckBox1 As String = Me.Context.Parameters.Item("Properties1") General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/12780/A-Setup-and-Deployment-project-that-passes-paramet?msg=3857129
CC-MAIN-2014-52
refinedweb
1,604
53.21
#include <Size.h> Collaboration diagram for Size: Definition at line 22 of file Size.h. The following function returns the depth. Definition at line 72 of file Size.h. References Size::m_depth. Referenced by Rect::getDepth(), Rect::isInDepth(), and Rect::makeInBounds(). The following function returns the height. Definition at line 64 of file Size.h. References Size::m_height. Referenced by Rect::getHeight(), and Rect::makeInBounds(). The following function returns the width. Definition at line 56 of file Size.h. References Size::m_width. Referenced by Rect::getWidth(), and Rect::makeInBounds(). Sets the depth dimenision of the size. Definition at line 45 of file Size.cxx. References Size::m_depth. Referenced by Rect::setDepth(). Definition at line 38 of file Size.cxx. References Size::m_depth, Size::m_height, and Size::m_width. Definition at line 32 of file Size.cxx. References Size::m_height, and Size::m_width. Referenced by Rect::setRect(). Definition at line 27 of file Size.h. Referenced by Size::getDepth(), Size::setDepth(), and Size::setSize(). Definition at line 26 of file Size.h. Referenced by Size::getHeight(), and Size::setSize(). Definition at line 25 of file Size.h. Referenced by Size::getWidth(), and Size::setSize().
http://www.slac.stanford.edu/grp/ek/hippodraw/lib/classhippodraw_1_1Size.html
CC-MAIN-2015-11
refinedweb
192
56.42
Dart program to check if an integer is odd or even Introduction : Dart integer class contains two properties to check if a number is even or odd. We can check these properties to find out quickly if a number is odd or even. In this tutorial, I will show you how to do that : isEven and isOdd : isEven and isOdd are two boolean values that you can access in an integer variable in dart. Just check for these values to find out if a number is odd or even. In the below example, we will take one number as input from the user and find out if it is odd or even. Example program : import 'dart:io'; void main() { int number; print("Enter a number : "); number = int.parse(stdin.readLineSync()); if (number.isEven) { print("$number is an even number"); } else if (number.isOdd) { print("$number is an odd number"); } } Sample Output : Enter a number : 12 12 is an even number Enter a number : 13 13 is an odd number Note that it will also work for negative numbers. For example, if your number is -12, it will print as an even number.
https://www.codevscolor.com/dart-check-integer-odd-even/
CC-MAIN-2020-16
refinedweb
192
69.82
Toggle switch button in Actionscript 3 In this tutorial I will create a Toggle switch button in Actionscript 3. The button will change between the on and off states when clicked. There are two ways you can make this toggle effect. The first method uses timeline frames and motion tweens to switch between the two states, and the second method uses coded tweens to create a smooth sliding transition. I will provide code for a simple toggle by moving the x positions, and also code for a coded tween using the TweenNano class. Step 1 Open a new AS3 file and save it with the name: Toggle switch button. You will need to download the TweenNano class from greensocks.com Step 2 On the menu bar select Insert > New Symbol. Enter the name ‘Toggle button’ choose the type Movie clip and click ok. Step 3 On the timeline change ‘Layer 1’ to the name ‘base’. This layer will be the base colour for the toggle button. Select the Rectangle Primitive Tool (R) and draw a rectangle shape with the width: 110 pixels and height: 40 pixels and the corner radius: 9. Make sure the x and y position of the rectangle is set to 0. Step 4 On the timeline insert a new layer called ‘text’. This layer will display the message for the button. Select the Text tool (t) and type the words ‘ON’ and ‘OFF’ in each half of the rectangle shape. I have used the Verdana Regular font with 15pt size and 0xFFFFFF colour. Step 5 Insert another new layer on the timeline called ‘Switch’. The switch layer is the movie clip that will move between the on/off positions. Select the Rectangle Primitive Tool (R) and draw a rectangle shape with the width: 55 pixels and height: 36 pixels and the corner radius: 9. Move the x and y position to 2. Convert the rectangle into a movie clip (F8) with the top left registration point selected and give it the instance name: switchBtn. Step 6 Return to the main timeline. Then from the Library panel drag the Toggle button movie clip onto the stage and give it the instance name: toggleBtn. Insert a new layer on the timeline called actions and enter the following code into the Actions panel. //Determines the on and off state. var onState:Boolean = true; //The x positions of the on/off. const ON_POSITION:int = 2; const OFF_POSITION:int = 53; //Adds a hand cursor on the button and adds a click event to the button. toggleBtn.buttonMode = true; toggleBtn.addEventListener(MouseEvent.CLICK, btnClicked); function btnClicked(e:MouseEvent):void { //This sets the onState variable to true/false when toggleBtn is clicked. //I have used the shorten logic for the true/false. onState = !onState; //If the onState is true then the switchBtn button is moved to the on position, //and if the onState is false then switchBtn button is moved to the off position. //You can also write the code using the ternary operator (shorten if-else statement) //like this: toggleBtn.switchBtn.x = (onState) ? ON_POSITION : OFF_POSITION; if(onState){ toggleBtn.switchBtn.x = ON_POSITION; }else{ toggleBtn.switchBtn.x = OFF_POSITION; } } The coded tween version is very similar. I have used the TweenNano class to tween the x position of the switchBtn movie clip. import com.greensock.TweenNano; var onState:Boolean = true; toggleBtn.buttonMode = true; toggleBtn.addEventListener(MouseEvent.CLICK, btnClicked2); function btnClicked(e:MouseEvent):void { onState = !onState; if(onState){ TweenNano.to(toggleBtn.switchBtn, 0.5, {x:ON_POSITION}); }else{ TweenNano.to(toggleBtn.switchBtn, 0.5, {x:OFF_POSITION}); } } Optional To make the button look less flat I have added a drop shadow to give a slight raise from the background. Since, the button is already on the stage you can add the drop shadow from the Filters panel. Here are the values I have used: BlurX & BlurY – 4, Strength – 70%, Angle – 90, and distance – 1. Alternatively, you can add the drop shadow using the following code. import flash.filters.DropShadowFilter; toggleBtn.filters = [new DropShadowFilter(1,90,0,1,4,4,0.7)]; Step 7 Export your movie Ctrl + Enter. The button on the left is the normal version which shifts the x position of the switchBtn, and the one on the right uses coded tweens to move the switchBtn. To make the button reusable for other projects you add the code into an Actionscript Class. Firstly, I assume you have created the tweened version. In the library, right click on the toggleBtn movie clip and select properties. Select the 'Export for Actionscript' checkbox and set the Class name to: 'ToggleBtn' and click ok. Now, open up an AS3 class file and enter the following code. package { import flash.events.Event; import flash.events.MouseEvent; import flash.display.MovieClip; import com.greensock.TweenNano; public class ToggleBtn extends MovieClip { public static const BTN_CLICKED:String = "btnclicked"; private const ON_POSITION:int = 2; private const OFF_POSITION:int = 53; private var onState:Boolean = true; public function ToggleBtn() { buttonMode = true; addEventListener(MouseEvent.CLICK, btnClicked); } private function btnClicked(e:MouseEvent):void { onState = ! onState; TweenNano.to(switchBtn, 0.5, {x: (onState) ? ON_POSITION : OFF_POSITION }); dispatchEvent(new Event(BTN_CLICKED)); } public function get buttonState():Boolean { return onState; } } } 1 comments: Very Interesting tutorial.I like your websites for these good and interesting tutorials.
http://www.ilike2flash.com/2012/07/toggle-switch-button-in-actionscript-3.html
CC-MAIN-2017-04
refinedweb
871
67.15
Like most programmers, I have frequently needed to identify parts and structures that exist inside textual documents: log files, configuration files, delimited data, and more free-form (but still semi-structured) report formats. All of these documents have their own "little languages" for what can occur within them. The way I have programmed these informal parsing tasks has always been somewhat of a hodgepodge of custom state-machines, regular expressions, and context-driven string tests. The pattern in these programs was always, roughly, "read a bit of text, figure out if we can make something of it, maybe read a bit more text afterwards, keep trying." Parsers of the formal variety distill descriptions of the parts and structures in documents into concise, clear, and declarative rules for how to identify what makes up a document. The declarative aspect is particularly interesting here. All my old ad hoc parsers were imperative in flavor: read some characters, make some decisions, accumulate some variables, rinse, repeat. As this column's installments on functional programming have observed, the recipe style of program flow is comparatively error-prone and difficult to maintain. Formal parsers almost always use variants on Extended Backus-Naur Form (EBNF) to describe the "grammars" of the languages they describe. Those tools we look at here do so, as does the popular compiler development tool YACC (and its variants). Basically, an EBNF grammar gives names to the parts you might find in a document; additionally, larger parts are frequently composed of smaller parts. The frequency and order in which small parts may occur in larger parts is specified by operators -- mostly the same symbols you see in regular expressions. In parser-talk, each named part in a grammar is called a "production." Possibly without even knowing it, readers have already seen EBNF descriptions at work. For example, the familiar Python Language Reference defines what a floating point number looks like in Python: EBNF-style description of floating point number floatnumber: pointfloat | exponentfloat pointfloat: [intpart] fraction | intpart "." exponentfloat: (nonzerodigit digit* | pointfloat) exponent intpart: nonzerodigit digit* | "0" fraction: "." digit+ exponent: ("e"|"E") ["+"|"-"] digit+ Or you might have seen an XML DTD element defined in an EBNF style. For example, the <body> of a developerWorks tutorial looks like: EBNF-style description in a developerWorks DTD <!ELEMENT body ((example-column | image-column)?, text-column) > Spellings vary slightly, but the general notions of quantification, alternation, and sequencing exist in all EBNF-style language grammars. Building tag lists with SimpleParse SimpleParse is an interesting tool. To use this module, you need the underlying module mxTextTools, which implements a "tagging engine" in C. mxTextTools (see Resources later in this article) is powerful, but rather difficult to use. Once SimpleParse is layered on top of mxTextTools, the work becomes a lot easier. Using SimpleParse is really quite simple, because it removes the need to think about most of the complexity of mxTextTools. The first thing to do is create an EBNF-style grammar that describes the language you want to handle. The second step is to call mxTextTools to create a tag list that describes all the successful productions when the grammar is applied to the document. Finally, you actually do something with the tag list returned by mxTextTools. For this article, the "language" we will parse is the set of markup codes used by "smart ASCII" to indicate things like boldface, module names, and book titles. This is the very same language mxTextTools was earlier used to identify, and regular expressions and state-machines before that, in earlier installments. The language is far simpler than a full programming language would be, but complicated enough to be representative. We probably need to back up for one moment here. What the heck is a "tag list" that mxTextTools gives us? Basically, this is a nested structure that simply gives the character offsets where every production was matched in the source text. mxTextTools traverses a source text quickly, but it does not do anything to the source text itself (at least not when using the SimpleParse grammars). Let's look at an abridged tag list: Tag list produced from SimpleParse grammar (1, [('plain', 0, 15, [('word', 0, 4, [('alphanums', 0, 4, [])]), ('whitespace', 4, 5, []), ('word', 5, 10, [('alphanums', 5, 10, [])]), ('whitespace', 10, 11, []), ('word', 11, 14, [('alphanums', 11, 14, [])]), ('whitespace', 14, 15, [])]), ('markup', 15, 27, ... 289) The elipses in the middle represent a bunch more matches. But the part we see says the following. The root production ("para") succeeds and ends at offset 289 (the length of the source text). The child production "plain" matches offsets 0 through 15. This "plain" child is itself composed of smaller productions. After the "plain" production, the "markup" production matches offsets 15 through 27. The details are left out, but this first "markup" is made of components, and additional productions succeed later in the source. An EBNF-style grammar for "smart ASCII" We have glanced at the tag list that SimpleParse + mxTextTools can give us. But we really need to look at the grammar that was used to generate this tag list. The grammar is where the real work happens. EBNF grammars are almost self-explanatory to read (although designing one does require a bit of thought and testing): typographify.def para := (plain / markup)+ plain := (word / whitespace / punctuation)+ whitespace := [ \t\r\n]+ alphanums := [a-zA-Z0-9]+ word := alphanums, (wordpunct, alphanums)*, contraction? wordpunct := [-_] contraction := "'", ('am'/'clock'/'d'/'ll'/'m'/'re'/'s'/'t'/'ve') markup := emph / strong / module / code / title emph := '-', plain, '-' strong := '*', plain, '*' module := '[', plain, ']' code := "'", plain, "'" title := '_', plain, '_' punctuation := (safepunct / mdash) mdash := '--' safepunct := [!@#$%^&()+=|\{}:;<>,.?/"] This grammar is almost exactly the way you would describe the "smart ASCII" language verbally, which is a nice sort of clarity. A paragraph consist of some plain text and some marked-up text. Plain text consists of some collection of words, whitespace, and punctuation. Marked-up text might be emphasized, or strongly emphasized, or module names, etc. Strongly emphasized text is surrounded by asterisks. And so on. A couple of features like just what a "word" really is, or just what a contraction can end with, take a bit of thought, but the syntax of EBNF doesn't get in the way. In contrast, the same sort of rules can be described even more tersely using regular expressions. This is what the first version of the "smart ASCII" markup program did. But this terseness is much harder to write, and harder still to tweak later. The following code expresses largely (but not precisely) the same set of rules: Python regexs for smart ASCII markup # [module] names re_mods = r"""([\(\s'/">]|^)\[(.*?)\]([<\s\.\),:;'"?!/-])""" # *strongly emphasize* words re_strong = r"""([\(\s'/"]|^)\*(.*?)\*([\s\.\),:;'"?!/-])""" # -emphasize- words re_emph = r"""([\(\s'/"]|^)-(.*?)-([\s\.\),:;'"?!/])""" # _Book Title_ citations re_title = r"""([\(\s'/"]|^)_(.*?)_([\s\.\),:;'"?!/-])""" # 'Function()' names re_funcs = r"""([\(\s/"]|^)'(.*?)'([\s\.\),:;"?!/-])""" If you discover or invent some slightly new variant of the language, it is a lot easier to play with the EBNF grammar than with those regular expressions. Moreover, using mxTextTools will generally be even faster in performing the manipulations of the patterns. Generating and using a tag list For our sample program, we put the actual grammar in a separate file. For most purposes, this is a good organization to use. Changing the grammar is usually a different sort of task than changing the application logic; and the files reflect this. But the whole of what we do with the grammar is pass it as a string to a SimpleParse function, so in principle we could include it in the main application (or even dynamically generate it in some way). Let's look at our entire (compact) tagging application: typographify.py import os from sys import stdin, stdout, stderr from simpleparse import generator from mx.TextTools import TextTools input = stdin.read() decl = open( 'typographify.def').read() from typo_html import codes parser = generator.buildParser(decl).parserbyname('para') taglist = TextTools.tag(input, parser) for tag, beg, end, parts in taglist[1]: if tag == 'plain': stdout.write(input[beg:end]) elif tag == 'markup': markup = parts[0] mtag, mbeg, mend = markup[:3] start, stop = codes.get(mtag, ('<!-- unknown -->','<!-- / -->')) stdout.write(start + input[mbeg+1:mend-1] + stop) stderr.write('parsed %s chars of %s\n' % (taglist[-1], len(input))) Here is what it does. First read in the grammar, and create an mxTextTools parser from the grammar. Next we apply the tag-table/parser to the input source to create a tag list. Finally, we loop through the tag list, and emit some new marked-up text. The loop could, of course, do anything else desired with each production encountered. For the particular grammar used for smart ASCII, everything in the source text is expected to fall into either a "plain" production or a "markup" production. Therefore, it suffices to loop across a single level in the tag list (except when we look exactly one level lower for the specific markup production, such as "title"). But a more free-form grammar -- such as occurs for most programming languages -- could easily recursively descend into the tag list, and look for production names at every level. For example, if the grammar were to allow nested markup codes, this recursive style would probably be used. You might enjoy the exercise of figuring out how to adjust the grammar (hint: remember that productions are allowed to be mutually recursive). The particular markup codes that go to the output live in yet another file, for organizational not essential reasons. A little trick of using a dictionary as a switch statement is used here (although the otherwise case remains too narrow in the example). The idea is just that we might in the future want to create multiple "output format" files for, say, HTML, DocBook, LaTeX, or others. The particular markup file used for the example looks like: typo_html.py codes = \ { 'emph' : ('<em>', '</em>'), 'strong' : ('<strong>', '</strong>'), 'module' : ('<em><code>', '</code></em>'), 'code' : ('<code>', '</code>'), 'title' : ('<cite>', '</cite>'), } Extending this to other output formats is straightforward. Conclusion SimpleParse provides a concise and very readable EBNF-style wrapper to the underlying power and speed of the cryptic mxTextTools C module. Moreover, EBNF grammars are already familiar to many programmers, even if only in passing. I cannot prove anything about what is easier to understand -- intuitions differ -- but I can comment quantitatively on source length. The mxTypographify module that was manually developed earlier is the following size: wc mxTypographify.py 199 776 7041 mxTypographify.py Of these 199 lines, a fair number are comments. And 18 of those lines are an included regular expression version of the markup function that is included for timing comparisons. But what the program does is essentially identical to what typographify.py -- listed above -- does. In contrast, our SimpleParse program, including its support files comes to: wc typo*.def typo*.py 19 79 645 typographify.def 20 79 721 typographify.py 6 25 205 typo_html.py 45 183 1571 total In other words, about one fourth as many lines. This version has fewer comments, but that is mostly because the EBNF grammar is fairly self-documenting. I would not want to emphasize LOC too strongly -- obviously, you can play games with minimizing or maximizing code length. But in a general way, one of the few real empirical results of work studies on programmers is that kLOC/programmer-month is fairly close to constant across languages and libraries. Of course, the regular expression version is, in turn, one third as long as the SimpleParse version -- but I think the density of its expression makes it fragile to maintain and harder to write. I think, on balance, SimpleParse wins of the approaches considered. Resources - Read the previous installments of Charming Python. - Read David's previous Charming Python column on developerWorks summarizing Python's text processing facilities: Charming Python: Text processing in Python. mxTextToolsis now part of the larger eGenix package of extensions. For more information, read mxTextTools - Fast Text Manipulation Tools for Python. - The reference module mxTypographifywas built using mxTextToolsdirectly. The SimpleParseversion becomes much more readable: SimpleParse, along with a brief introduction to its usage. - Visit John Aycock's Sparkmodule home page. Sparkis in many ways a more sophisticated parsing framework than is SimpleParse. A number of Python developers have recommended Spark, which has the additional virtue of being pure-Python (with a corresponding natural disadvantage in terms of speed). - Get more information on the ISO 14977 standard for EBNF syntax. - Browse more Linux resources on developerWorks. - Browse more Open source resources on developerWorks..
http://www.ibm.com/developerworks/library/l-simple/index.html
CC-MAIN-2014-52
refinedweb
2,076
55.44
27 May 2010 16:59 [Source: ICIS news] LONDON (ICIS news)--Three engineering, procurement and construction (EPC) contracts for the Borouge III expansion, including those for the major polyolefins plants, worth a total of $2.6bn (€2.1bn), have been awarded, the Borealis/ADNOC (Abu Dhabi National Oil Company) joint venture said on Thursday. A Tecnimont/Samsung Engineering consortium has won the $1.255bn contracts for two polyethylene (PE) and two polypropylene (PP) units and the $400m contract for a 350,000 tonne/year low density polyethylene (LDPE) unit, it said. The contracts were awarded on a lump sum turnkey basis. The two linear low density (LLD)/high density (HD) PE units will have capacities of 540,000 tonnes/year each. The two PP plants will have capacities of 480,000 tonnes/year each. All will use the Borealis Borstar technology. The LDPE unit will use LyondellBasell’s Lupotech T process “associated with” Borealis’s LDPE W&C (Wire and Cable) process, Tecnimont said, Borouge said also that it had awarded a $935m contract for utilities and off-site facilities for the project expansion at Ruwais in ?xml:namespace> The contract to build the 1.5m tonne/year Borouge III ethane cracker was previously awarded to Linde. Borouge said it was currently tripling its polyolefins capacity at Ruwais to 2m tonnes/year with an on-stream date for the Borouge II facilities of mid-2010. The additional 2.5m tonnes/year of polyolefins capacity is planned to be on-stream in 2013. Tecnimont was the main contractor for the polyolefins unit for Borouge I, completed in 2001 and in 2007 was awarded the contracts for the polyolefins unit for Borouge II as well as for a de-bottlenecking project. It completed the front end engineering and design (FEED) contract for Borouge III at the start of this year. ($1 = €0.82) For more on polyethylene and polypropylene visit ICIS chemical intelligence For more on Borealis/Borou
http://www.icis.com/Articles/2010/05/27/9363063/tecnimontsamsung-engineering-to-build-borouge-iii-polymer.html
CC-MAIN-2014-42
refinedweb
326
53.81
Table of contents - Introducing stage video - The StageVideo API - Video encoding guidelines - Video delivery guidelines - Supporting legacy content on Google TV - General optimizations for the Flash Platform - Authoring content for multiple device types and screen sizes - Video player and rendering optimizations - User interface guidelines - Content protection guidelines - Customize based on target device for Flash Player - Where to go from here Created 17 January 2011 The Adobe Flash Platform is the leading platform for video and rich interactive content on the web. Now Adobe is teaming up with companies like Google and Samsung to bring Adobe Flash Player 10.1 and Adobe AIR 2.5 to television sets so that consumers can enjoy this same video content in their living rooms. This article contains recommendations for adapting your content to perform optimally on televisions. To help ensure that your video content performs optimally, you should do the following: - Use the new StageVideo API - Verify that your video stream is encoded in a format that is appropriate for televisions - Optimize the performance of your video player and of your application, both for new and legacy content - Ensure that the user interface of your application is appropriate for televisions - Understand the content protection options for your video - Add conditional logic to your website so that you can customize your video stream and video player depending on the target device Up until now, video in Flash Player has been rendered using the Video object in ActionScript 3. The Video object is treated the same as any other object on the stage, which gives developers an unprecedented amount of creative control. For example, video can be displayed on each face of a spinning cube, or multiple videos can be blended together with one another. To support that level of creative control, the Flash runtime must do a significant amount of processing for each video frame. Depending on the power of the underlying device, this increased processing may decrease the frame rate of the video, or it may increase the load that Flash places on the CPU. To solve for this problem, Adobe has introduced a new way to render video. This new approach, called "stage video," takes full advantage of the underlying video hardware. The resulting much lower load on the CPU translates into higher frame rates on less-powerful devices and also less memory usage. The performance benefits of stage video are especially pronounced for televisions and set-top boxes. Those devices do not have CPUs that are as powerful as desktop computers, but they do have very powerful video decoders capable of rendering high-quality video content with very little CPU usage. With this new stage video approach, the video is rendered onto a StageVideo object instead of a Video object. The StageVideo object is always displayed in a window-aligned rectangular region of the screen. Although other graphics may be layered on top of the StageVideo object, you cannot layer objects behind the video. Furthermore, the following features are not available when the StageVideo object is used: - The StageVideo object cannot be rotated. - The StageVideo object may not have a colorTransform or 3D transformations transform applied to it. It may not have a matrix transform that skews the video. - The StageVideo object cannot have an alpha channel, blendMode, filter, mask, or scale9Grid applied to it. - The video data cannot be copied into a BitmapData object. - The video data must not be embedded in the SWF file. Stage video can only be used with videos originating from a NetStream object. - Depending on the underlying hardware, some color spaces may not be supported. In those cases, the Flash runtime will choose a substitute color space. The new StageVideo ActionScript API provides a means to query the color space that is being used. - To ensure compatibility between Flash Player on desktop and on TV devices, use wmode=direct. - Avoid layering wmode=transparentSWF files on top of each other. Platforms such as Google TV do not support wmode=transparent. This means that all Flash instances are supported in wmode=windowregardless of the embed tag parameters. In practice, none of the above restrictions will affect the most common use case, which is a video player application. In cases where these restrictions are acceptable, developers are strongly encouraged to use the StageVideo object. Stage video is supported on Flash Player 10.1 beta on Google TV, on all AIR for TV platforms, and it will soon be included on all platforms that support Flash Player. The API examples in this document are specific to those platforms, and the API is evolving and may change in future version of Flash Platform products. Flash Player includes a new class called StageVideo which represents a single video display instance in the hardware video plane. StageVideo objects are created by the Flash runtime and cannot be instantiated on their own. StageVideo objects can be accessed from the Stage object as such: var v:Vector.<StageVideo> = stage.stageVideos; var stageVideo:StageVideo; if ( v.length >= 1 ) { stageVideo = v[0]; } The length of the Stage.stageVideosvector will vary depending on platform and hardware availability when the stageVideos property is accessed. The length of the vector will sometimes be zero. Developers are required to check for this condition, as content is sure to break otherwise. If a StageVideo object is not available, then the Video object should be used instead. Once you have obtained a StageVideo object, you can move and resize it. Coordinates are always in Stage coordinate space as the StageVideo object essentially exists as a child of the Stage and is not part of the standard display list. Sample code: stageVideo.viewPort = new Rectangle(10,10,320,240); Before displaying a video stream, the developer should add a listener for the StageVideoEvent.RENDER_STATEevent. Here is the skeleton for an event handler: function onStageVideoEvent(event:StageVideoEvent) { if ( event.status == StageVideoEvent.RENDER_STATUS_UNAVAILABLE ) { // The video hardware stopped showing video. On the desktop you // would want to fall back to use a normal Video object // to continue rendering video at a cost of performance. } if ( event.status == StageVideoEvent.RENDER_STATUS_SOFTWARE) { // The video is decoded using a software video decoder. } if ( event.status == StageVideoEvent.RENDER_STATUS_ACCELERATED ) { // The video is decoded using a hardware based video decoder. } } stageVideo.addEventListener(StageVideoEvent.RENDER_STATE, onStageVideoEvent); To display a video stream in a StageVideo, use the attachNetStreammethod; it is analogous to the Video.attachNetStreammethod: stageVideo.attachNetStream(myNetStream); The StageVideo API offers a few methods to track capabilities before any of the above APIs are used. For example, we can query what video color spaces the StageVideo object is able to display. The API returns a vector of strings usually containing "BT.601" and "BT.709." var colorSpaces:Vector.<String> = stageVideo.colorSpaces; Here is an application fragment that uses the new StageVideo API: public class SamplePlayer extends Sprite { public var netStream:NetStream; public var netConnection:NetConnection; public var video:Video; public function SamplePlayer() { netConnection = new NetConnection(); netConnection.connect(null); netStream = new NetStream(netConnection); video = new Video(320,240); video.attachNetStream(netStream); // might be overridden later // Set up normal display list properties video.x = 100; video.y = 100; video.width = 320; video.height = 240; addChild(video); // Try to render as stage video var v:Vector.<StageVideo> = stage.stageVideos; if ( v.length >= 1 ) { var stageVideo:StageVideo = v[0]; stageVideo.viewPort = new Rectangle(100,100,320,240); stageVideo.addEventListener( StageVideoEvent.RENDER_STATE,renderStateEventHandler); stageVideo.attachNetStream(netStream); } netStream.play("MyVideo.f4v"); } public function renderStateEventHandler(event:StageVideoEvent):void { // If video is not rendered properly let the // video object in the display list try to render it. if ( event.status == StageVideoEvent.RENDER_STATUS_UNAVAILABLE ) { video.attachNetStream(netStream); } } } When streaming video to a TV device, Adobe recommends the following encoding guidelines: - Flash Player also supports video that is encoded using the Sorenson Spark or On2 VP6 codecs. However, those codecs are not fully supported by the video hardware, so they will play at a much lower frame rate. As a result, H.264 should be used if at all possible. These video encoding guidelines are not appropriate for some of the other devices that support Flash Player, such as smartphones. Therefore, your website should include some conditional logic that delivers different video streams to different target devices. Additional detail is provided later in this document. To read more about optimizing video with Flash Player, do not hesitate to check the document entitled Delivering video for Flash Player 10.1 on mobile devices. From mobile video encoding guidelines to video player optimizations, the document covers general optimizations interesting for any Flash developer working with video. Given the largely unreliable quality of the Internet connections that run into your users' homes, your video delivery system needs to have some sort of an adaptive bitrate policy, regardless of device type. For different reasons, this applies for video to deliver to living room as it does on mobile. In the former case, as other users start to use the same Internet connection, network congestion increases; in the latter case, as users move around, the quality of the signal changes. In both cases, the available bandwidth changes throughout the time a video is playing back. Technologies such as Adobe Flash Media Server 4 with adaptive bitrate capabilities, as well as recovery during network outages, allows for a high-quality user experience while the network capabilities vary during playback. Features in Flash Player on Google TV and AIR on Samsung devices enable this adaptive bitrate playback. In order to take advantage of the various technologies, as well as take advantage of extensive testing already accomplished, Adobe strongly recommends using the Open Source Media Framework (OSMF) for the basis of any video player going towards an embedded device. Adobe provides OSMF free of charge, enabling video players to be quickly enabled to take advantage of all the various Flash Platform capabilities, including adaptive bitrate and our content protection solutions. For the delivery of the content, there are a variety of protocols that are available in the Flash Platform to enable you to move video over the network: - HTTP Dynamic Streaming (F4F format) - RTMP/e Streaming - HTTP Progressive Download - RTMFP Peer-to-Peer - RTMFP Multicast The choices above give you the flexibility to use your existing delivery infrastructure to target TV devices. Going forward, Flash Player will support both the Video object and the StageVideo object. If a piece of conent displays video in a window-aligned rectangular region on the screen, then you should use the StageVideo object; if a piece of content performs complex transformations on the video, then the slower Video object should be used instead. Because the StageVideo object is new, all existing content on the web uses the Video object. When that content is displayed on a high-resolution device using a less-powerful CPU, the result is sometimes less than ideal. To solve for this problem, Adobe has decided to make a short-term trade-off. On the Google TV and AIR for TV platforms, the Video object will be rendered using the same code path that is used by the StageVideo object. As a result, the Video object will enjoy the same performance as the StageVideo object but it will be subject to the same restrictions. If any of the unsupported features (listed in the "Introducing stage video" section of this article) are applied to the Video object, then they are simply ignored. For example, if the Video object's alphaproperty is set to 0.5, the video is rendered as if the alphaproperty were set to 1. If you attempt to simultaneously play multiple videos in multiple Video objects, then only one or two will play at a time. Each call to NetStream.play()will cause a new video to begin playing, and other videos will just stop. In future releases, Adobe intends to restore the original, intended behavior of the Video object. When the original behavior of the Video object is restored, it will render more slowly. StageVideo, on the other hand, will always maximize performance, maximize quality, and minimize power consumption on all platforms. Therefore, the StageVideo object should be used for any video content that does not depend on complex transformations or rendering effects. This document covers specific optimizations for developers targeting Flash Player on Google TV or Adobe AIR on TV. Note that another document entitled Optimizing performance for the Adobe Flash Platform (PDF, 3.8 MB) contains a lot of general optimizations that are true in any embedded systems context. Do not hesitate to read it; several advanced techniques are covered, ranging from object pooling to manual bitmap caching. Those techniques will improve the performance of your content when viewed in Flash Player. Flash Player and AIR on devices, such as Google TV or Samsung Internet-connected TVs, support hardware acceleration for H.264 video. As an ActionScript developer targeting GPU-accelerated devices, you should be aware of things to avoid in order to get the best performance possible. The document Flash Player 10.1 hardware acceleration for video and graphics sheds some light on the technical details of hardware acceleration in the Flash runtime. Many resources are available to you to see how improve the performance of ActionScript. Adobe suggests to use ActionScript 3 on embedded platforms, as Flash can take advantage of the improved performance characteristics that ActionScript 3 enables: As Flash Player and AIR proliferate to various screens and on to various kinds of devices, Flash content needs to be aware of the fact that it will run on any kind of screen, whatever its size. An AIR application can be designed to run on a mobile phone, a desktop computer, a TV, or a tablet. Someobody who visits your website may be visiting from an Android phone, a Google TV, or a desktop computer. Being aware of the differences in all these devices, yet leveraging the Flash Platform, enables you to build a multiscreen application. These applications respect the soul of the device, but let you, the content developer, share much of your code in order to reduce the costs of optimizing to that device—or, at best case, do nothing at all. Consider a TV screen. TVs offer a small number of screen resolutions for content to support, namely 960 × 540, 1280 × 720 (720p) or 1920 × 1080 (1080p). Even with three basic TV screen resolutions, there are many input methods (mouse, remote control, free motion wand, hybrid keyboards, and more) and CPU/GPU performance characteristics that mean that your content may need to address differences in order to be accessible to your users. To make sure your video content for Flash handles different screen sizes and resizing common behaviors properly, make sure you read the document Authoring mobile Flash content for multiple screen sizes, which covers the essentials. In addition to encoding your video stream properly, it is also important to optimize your video player and the content around it. If your video player uses too many CPU cycles, then it may affect the frame rate of the video playback, or it may cause the user interface to feel sluggish. Inefficient video players are typically plagued by both excessive script execution and excessive rendering. The following sections describe a number of video player optimizations that may help to significantly improve performance on a television. Reduce the number of objects on the Stage as much as possible. For instance, simplify the shape of essential buttons by using non-complex fill styles like simple, rectangular, solid-color shapes rather than gradients or multiple small lines. Be especially judicious using expensive rendering features such as filters. If shapes such as the playhead are changing shape or position, they should be updated as infrequently as possible—no more than once or twice per second. This item applies when you are are targeting Google TV or any other platform that has Flash Player embedded in a TV class device. In that case, the video player SWF file is embedded in an HTML page using a combination of <object>and <embed>tags. If those tags contain a wmodeparameter, then ensure that the value of that parameter is set to "direct". Other values of wmodemay be supported on some platforms but they cannot be supported consistently. In particular, setting wmode="transparent"will not work on these platforms. Overlapping SWF files will not layer correctly with each other, nor with other overlapping HTML elements. The goal here is to minimize ActionScript processing intervals: enterFrame handlers, callback functions registered with NetStream, mouse event handlers, and other such functionality. When registering a timer function, it will be called as often as possible up to the rate requested; Flash Player may end up potentially spending all of its time executing script as opposed to drawing video frames. This is especially true for timer functions that update UI components, and hence trigger redraws, which are expensive operations. If an object is hidden off Stage or behind another object, the Flash renderer will still waste time attempting to render the hidden object (computing its bounding box, for instance). If you want to make an object invisible, do not hide it behind another object, move it off Stage, set its alphaproperty to zero, or set its visible property to false. Instead, call removeChild()to remove the object from the display list entirely. Also, be sure to stop the timeline of any hidden object. If the video associated with a NetStream object has finished playing, call the NetStream.close()method. This allows the Flash runtime to manage video resources better. Avoid bitmap caching (via the cacheAsBitmapproperty) on frequently updated objects. When bitmap caching is enabled, the bitmap needs to be recached—an expensive operation—each time the object is updated. For example, frequently updated text fields should not be bitmap cached,; examples include avoiding large loops, reducing the depth of function calls, and simplifying the design of object-oriented classes. Adobe makes available best practices to improve ActionScript performance. Due to the behavior of many video players, they may be executing a large amount of script while video is playing back. It is possible that the amount of time consumed by the executing ActionScript can cause issues with video playback if the CPU is completely taxed with ActionScript execution. Avoid using ActionScript timers with very short intervals (for example, shorter than a frame update) or spending significant time in any one handler. For Flash Player, calling from ActionScript to JavaScript can be expensive and should not be done at regular intervals during video playback. Further, avoid flushing LocalObjects more often than needed. This is only critical when communicating between SWF files on a page. If your goal is to communicate between SWF files on a page, LocalConnection is a higher performing option. Consider the typical household. The television is in the center of the room, with various devices connecting to it. There may be one or many people in the living room, some watching the TV, others engaging in other activites, but also in the living room. Your application lives in a very unique context, unlike any other type of platform on which Flash runs. The television is the only consumer electronics device that is shared between various individuals and members of a family. Unlike a mobile phone or a desktop or laptop computer, the TV does not necessarily have an "owner"; the same person who turns it on may not be the same person who turns it off. Thus, the user interface for your application and for your video player should be optimized for television sets and for the living room environment. Consider what happens if you're building a game and somebody picks up where somebody else has left off, or if you're building a video player and the play/pause state may be transient between users. Your user is likely sitting 10–15 feet from the screen, and the device in the hand is probably not a mouse and QWERTY keyboard—it's likely a remote control. It may even be a hybrid remote control, or it may be a mobile phone. The room may be dark, so imagery needs to be crisp and fonts and colors need to be legible. Font sizes need to be readable from over 10 feet away, and often at a glance as somebody is pushing buttons on the remote quickly to get to the application. A common practice for most UIs is to be responsive to button clicks in less than 200ms; as such, it's necessary to precache items that may be in the user's workflow to provide the most optimal experience for the user. It's easy to think of a television as another PC-class device, but it's also important to consider the history of television and the decades of behaviors adults and children have been trained in how a TV should behave and act. People expect TV to be an entertainment device, either as a lean-back device (in the case of video) or a sitting-upright device (in the case of gaming). For example, notifications that require dismissal get in the way of entertainment-oriented expectations, as consumers expect their TV to just work. Consider using as few modal dialog boxes as possible and simplifying the user experience to keep it entertainment-focused. All these factors should influence the design of your application and any user interface. AIR for TV and Google TV devices support Flash Platform content protection for premium video content. Many of the leading premium video providers use the Flash Platform to provide a seamless viewing experience. Streaming video securely from Flash Media Server (FMS) is possible by using technologies such as RTMPE (Real Time Media Protocol Encrypted) and SWF Verification. The content protection features in FMS are supported by the vast majority of content delivery networks (CDNs), enabling an easy content workflow and broad geographical reach. Protecting online video distribution with Adobe Flash media technology, a white paper on the Adobe Developer Connection, provides an overview of typical content protection workflows using RTMPE, SWF Verification, and related features. Adobe also offers Flash Access, an end-to-end content protection and monetization solution that can provide an even higher level of protection, increased flexibility, and new opportunities for monetizing content. Flash Access works for both downloading and streaming use cases, with either FMS or the new HTTP Dynamic Streaming protocol from Adobe. This technology supports a broad range of business models including electronic sell-through (EST), video on demand (VOD), rental, subscription, and pay-per-view (PPV). Flash Access support is included on desktops starting with Flash Player 10.1 and Adobe AIR 2. Starting with AIR for TV 2.5, Flash Access is also supported on Digital Home devices. By providing a common protection solution across different devices and screens, and integrating content protection into the Flash runtimes, Flash Access enables content providers to have a single workflow with the highest level of protection, bringing to consumers a rich, interactive experience around premium video content. Developers can leverage the Flash Access server SDK or work with one of our hosted content protection partners to create solutions that integrate with your existing back end (such as a subscriber database or a payment processor). The white paper, Adobe Flash Access overview on protected streaming (PDF, 319 KB), describes using Flash Access in various workflows, while the Flash Access 2.0 Help Resource Center provides more detailed information and documentation about the server components. On the client, Flash Access introduces a few ActionScript APIs that can be used to control the acquisition of content licenses, user authentication (where required), and other functionality. Silicon vendors and OEMs can use the Flash Access porting kit to leverage the native security hardware for the best user experience and highest level of protection. For additional information, refer to the following resources: - flash.net.drm package classes (API documentation) - Rich media content: Using digital rights management (ActionScript 3 Developer's Guide) To provide users an optimal experience while browsing on television sets, you may need to re-encode your video stream or customize the user interface of your video player. At the same time, you will want to continue providing an optimal experience on desktop computers and smartphones, which may each require a different video encoding or a different user interface. Therefore, you need to add some conditional logic to your website so that the web page is tailored to the device on which is it displayed. This conditional logic could be included on your web server, in the JavaScript that runs in your HTML page, or in the ActionScript that runs in your SWF file. When a web browser issues an HTTP request, it inserts some information in the header of the request. One of the inserted fields is called "user-agent." The user-agent field describes the device on which the browser is running. By adding logic to your web server, you can serve a television-specific HTML page when you detect a television browser's user-agent string. A good way to handle redirecting a browser to a television-specific page on the server is by using an HTTP Redirect. There is more information on the "Redirect" directive in the Apache manual and on redirection in the Microsoft IIS documentation. Also, there are some sample scripts that perform device detection at John Boxall's mobile device detection site. Note that the content of the user agent will vary from one device to the next and may change if the software on a device is updated. New devices and software updates appear very frequently, so you should plan to update your server-side logic accordingly. A second option is to include the same user-agent logic in the JavaScript code within your HTML page. Depending on the user agent it detects, it can use the document.writemethod to embed a SWF file tailored to the device. In this case, your site contains a single version of the HTML page, but a different version of the SWF file is delivered to each different target device. As mentioned above, code that relies on user-agent strings will not work with future agent strings. In addition, the code may be slow because of all the string comparisons. The benefit to using the JavaScript approach is the ability to detect specific devices and operating systems to help you take advantage of platform-specific capabilities. For more information about user-agent strings and how to use them, check out the information on browser detection and cross-browser support from Mozilla.org. To get around the static nature of saving user agents in your JavaScript code, you can use WURFL, a service that maps user agents to device capabilities. This might be useful if you're trying to use JavaScript to detect specific attributes of the device that is browsing your web site. A third option is to include the detection logic in the ActionScript code within your SWF file. When this option is used, a single version of the HTML page and a single version of the SWF file is delivered to all devices. Within the SWF file, the ActionScript code determines the type of the target device, requests a video stream that is appropriate for that device, and customizes the video player user interface for that device. Flash Player provides many useful ActionScript properties to gather information about the target device: Capabilities.cpuArchitecture Capabilities.os Capabilities.screenDPI Capabilities.screenResolutionX, Capabilities.screenResolutionY Capabilities.touchscreenType Mouse.supportsCursor On Google TV, the Capabilities.os property is set to GTV, and as such you could infer that an Intel-based Android device with a high-resolution screen and Capabilities.os=="GTV"is a Google TV device. On other TV platforms, including AIR for TV, the Capabilities class will vary in what data it returns based on the underlying hardware. You may be able to use information in the Capabilities class to make various playback and rendering decisions. This strategy involves guesswork, and it does not always enable content to identify the exact model of the target device, but it is a bit more future-proof than a solution that hard-codes user-agent strings. Flash Player is now available on Google TV, and AIR for TV will soon be available on Samsung TV and Blu-ray devices, so you can deliver the video experience that your users have come to love on yet another screen. While you will be able to leverage many of your assets from existing projects targeting Flash Player, you may want to customize your video stream and video player for television sets. We'll be updating this document and the tips, techniques, and methods to optimize the Flash Platform on TV. Visit this document regularly to check out updates that Adobe posts. Please consult the following resources for more information:
https://www.adobe.com/devnet/devices/articles/video_content_tv.html
CC-MAIN-2018-47
refinedweb
4,800
51.48
typical object oriented language (i.e. Java): public class Square { private int x, y, len; ... public boolean equals(Object o) { if(o instanceof Square) { Square s = (Square) o; return x == s.x && y == s.y && len == s.len; } return false; } } What is frustrating here, is that we need to cast variable o to an entirely new variable s. The condition o instanceof Square asserts that variable o has type Square — and, the compiler should really be able to exploit this to avoid the unnecessary cast. o s o instanceof Square Square In Whiley, the compiler is able (amongst other things) to exploit type tests in this manner. For example, consider the following Whiley program: define Square as { int x, int y, int len } define Circle as { int x, int y, int radius } define Shape as Square | Circle boolean equals(Square s1, Shape s2): if s2 is Square: return s1.x == s2.x && s1.y == s2.y && s1.len == s2.len else: return false In this example, no casting is necessary for variable s2 as the Whiley compiler knows it has type Square when the condition s2 is Square holds. An interesting question is: what type does s2 have on the false branch? Well, clearly, it is not a Square. And, that’s exactly how it’s implemented in the compiler — using a negation type. A negation type ¬T represents a type containing everything except T. In our example above, the type of s2 on the false branch is Shape & ¬Square. Here, T1 & T2 represents the intersection of two types T1 and T2. Thus, Shape & ¬Square represents everything in Shape but not in Square. s2 s2 is Square ¬T T Shape & ¬Square T1 & T2 T1 T2 Shape In building a compiler, it’s obviously important to develop algorithms for manipulating the types being used. In this article, I want to focus on the algorithm for subtyping. This simply reports whether or not a type T1 subtypes a type T2, denoted T1 <= T2. Based on the description given so far, one has an intuitive understanding of types as sets. That is, a type T represents the set of values which can be held in a variable declared with type T. In this way, we can think of T1 being a subtype of T2 if the set of values represented by T1 is a subset of those represented by T2. T1 <= T2 We now begin to formalise more precisely what types in Whiley mean (i.e. their semantics). We use the following language of types, which is a cut-down version of those found in Whiley: Here, any is the type containing all values, int is the type of integers, (T1,...,Tn) is a tuple type, ¬T is a negation type, T1 /\ T2 an intersection type (written T1 & T2 in Whiley source syntax), and T1 \/ T2 a union type (written T1 | T2 in Whiley source syntax). any int T1,...,Tn) T1 /\ T2 T1 \/ T2 T1 | T2 To accompany our language of types, we need to define what constitutes a value in the system: Here, v represents a value which is one of two possibilities: either it is an integer, or it is a tuple value the form (v1,...,vn). Using this we can give a semantic interpretation of types in our language: v (v1,...,vn) Here, we have defined a way to construct the set of values represented by a given type T. Whilst this may all seem rather mundane, it provides the necessary foundation for the subtyping algorithm. The subtyping algorithm is intended to determine when a type T1 is a subtype of a type T2. Or, equivalently, when the set of values represented by T1 is a subset of those represented by T2. The algorithm is surprisingly difficult to get right, and it has taken me sometime to develop. The following represents a good attempt to capture the algorithm and is presented as a series of recursive “type rules” covering the different possible forms of T1 and T2: Under these rules, we can for example show that (int,int) is a subtype of (any,any) and, likewise, that (int,int)is a subtype of (int,any)|(any,int). (int,int) (any,any) (int,any)|(any,int) The real challenge with the above subtyping rules is: how do I know they are right? Obviously, I want to be sure that the type checking algorithm in my compiler will work as expected. But, it’s rather difficult to decide this just by staring at the rules. We need to break the problem down and we do this using the following notions of soundness and completeness: In fact, the above rules can be shown as sound. However, they are not complete. For example, we cannot show that any is a subtype of int | ¬int — a fact which is indeed true under our semantic interpretation. int | ¬int Now, the question is: Is there a sound and complete algorithm for subtyping testing in this language and, if so, what is it? The first part of the question (i.e. existence) was already shown by Frisch, Castagna, and Benzaken in their excellent (albeit complicated) paper. The second part of the question (i.e. finding an actual algorithm) is also very important for me since I’m implementing an actual compiler. To figure this out, I went back to the drawing board several times and, finally, found a reasonable algorithm which is discussed here: I won’t go into all the details here since its quite involved and the paper does a good job explaining things. However, the key idea is to represent types in a “special form” such that we can easily perform the subtype tests. The challenge is then to convert any given type T into its corresponding “special form”… That’s all for now! This is cool and the logic is very pretty. Negation types are obviously integral to the formal type system. Do they have a more practical use in the language? I noticed you did not provide a Whiley language representation of “¬T” ! So, I wonder if there are any benefits to implementing one. Constructions similar to your first example could simply test for memberhip of a negation type by transposing the two branches of the if-statement: if s2 is (not T): foo(…) else: bar(…) Becomes: if s2 is T: bar(…) else: foo(…) In terms of syntactic requirements, I’m unsure if there is code that *requires* a variable to be of type (not T) — for instance if the else branch of your example had simply had s2 of type any, nothing would be apparently broken in the program: the code in that branch does not demand a (not T) variable. Is there possible code that could? Hi Edmund, Yeah, so there is a Whiley source syntax for negation types: !T !T But, the more general question you raise is whether or not these are useful to the programmer (i.e. other than as a hidden feature of the subtype algorithm). That’s a good question. I suppose one could imagine a situation where we have a function f() which wants to accept a parameter which can be anything *except* an int. In such case, its type would be f(!int). But, it is still unclear to me whether this is really useful or not … f() f(!int) Hi Dave, I just stumbled on this old post. For what concern the second part of the question (finding an actual algorithm, the answer was in in Alain Frisch’s PhD thesis (written in French). But I tried to explain all the algorithm and data structures used in CDuce in an unpublished paper ” Covariance and Contravariance: a fresh look at an old issue (a primer in advanced type systems for learning functional programmers)” (See section 4:). Feedback would be welcome 🙂 Cheers Giuseppe Castagna Hey Giuseppe, Ah, thanks for the pointer about Alain’s PhD! Sadly, yes, I haven’t read it unfortunately. But, I’ve printed out that you new paper, and I’ll have a read — it looks really interesting!! Cheers, 62 queries. 0.334 seconds.
http://whiley.org/2012/10/31/formalising-flow-typing-with-union-intersection-and-negation-types/
CC-MAIN-2020-05
refinedweb
1,353
69.52
An API wrapper for MercadoPago Project description PyMercadoPago is user-friendly library to interact with the MercadoPago API. Python 3 only. To install it from PyPI, simply run: pip install pymercadopago If you haven’t done so already, obtain your CLIENT_ID and CLIENT_SECRET here. Quickstart Create a new mercadopago.Client instance and pass it your credentials: import mercadopago CLIENT_ID = 'XXX' CLIENT_SECRET = 'XXX' mp = mercadopago.Client(CLIENT_ID, CLIENT_SECRET) You can navigate the full API from the client methods. Try running the above code in a Python shell and explore them. # Get the invoice with ID 1234 mp.invoices.get('1234') # Get the current user account balance mp.users.account_balance() # Create a new customer instance mp.customers.create( first_name='Federico' last_name='Bond', # ... ) In general, assuming mp is a mercadopago.Client instance and there is an endpoint documented at (for example) /customers or /v1/customers, you can do: - mp.customers.list() - List all customers. Pass pagination parameters via keyword arguments. - mp.customers.create(**data) - Create a new Customer. - mp.customers.delete(id) - Delete a Customer. - mp.customers.update(**data) - Update a Customer, include ìd in your keyword arguments. - mp.customers.search(**params) Not all methods are available for all resources, and some additional convenience methods have been added to some. To learn more, check out the official docs and/or the code from the mercadopago.api module. Nested resources like are usually accessed by following the corresponding resource paths. For example: # GET /v1/customers/:id/cards # ---- mp.customers.cards(id).list() All methods return a Response object if successful (HTTP status code in the 2XX range) or raise an instance of mercadopago.Error otherwise. Response Every API call you make will return a Response instance with the following attributes: If MercadoPago returns a response with pagination information, a PaginatedResponse will be returned instead. Paginated responses have the following additional methods: - response.total - Total amount of records in this collection. - response.limit - Maximum number of records for this page. - response.offset - Number of records skipped to reach this page. - response.results - List of records in this request. This is different from .data which contains the full body of the response, with the pagination info. - response.has_prev() - Whether there are any preceding pages. - response.has_next() - Whether there are any following pages. - response.prev() - Requests the previous page and returns a PaginatedResponse. - response.next() - Requests the next page and returns a PaginatedResponse. - response.auto_paging_iter() - Returns a generator of records that will automatically request new pages when necessary. Error If there is a connection error or the HTTP response contains a non-2XX status code, the method will raise an instance of mercadopago.Error. The error object contains the following attributes: The specific subclass raised depends on the HTTP status code. Running the tests Make sure tests pass before contributing a bugfix or a new feature. To run the test suite, execute this in your terminal: python setup.py test This will execute the tests with your default Python interpreter. Use tox to run the tests in all supported Python versions. To Do - Implement idempotency headers in POST/PUT requests. - Implement retry request from error. For more information about the API, refer to the official docs. License Apache-2.0 Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pymercadopago/
CC-MAIN-2021-39
refinedweb
556
52.26
c++ - Code generation bug in mixing C and C++ in returning structs - Burton Radons <burton.radons gmail.com> Oct 10 2009 - Walter Bright <newshound1 digitalmars.com> Oct 10 2009 Say I have this header file, "a.h": typedef struct S S; struct S { int a; int b; #ifdef CPP_CONSTRUCTOR #ifdef __cplusplus S () : a (0), b (0) { } #endif #endif }; #ifdef __cplusplus extern "C" #endif S f (); I also have this C file, "b.c": #include "a.h" #ifdef __cplusplus extern "C" #endif S f () { S result; result.a = result.b = 100; return result; } Finally I have this C++ file, "c.cpp": #include "a.h" #include <stdio.h> int main () { S t = f (); printf ("%d %d\n", t.a, t.b); return 0; } Then I compile it with "sc b.c c.cpp -DCPP_CONSTRUCTOR a.exe". When executing the file I would expect it to print "100 100". Instead it prints garbage. If I instead compile it with "sc b.c c.cpp a.exe" (causing the constructor in S to be not present), it prints "100 100" as it should. The reason is that in the latter case without the constructor it expects the return value to be in EAX EDX, as it actually is returned from f. In the former case it passes a return pointer in EAX, which of course isn't written with anything so it reports whatever was on the stack beforehand. Note that b.c is being compiled correctly, so it's not dependent on build process but only the presence of the constructor. Other methods in the structure don't have an effect, just the constructor. Does anyone know of a workaround? Oct 10 2009 I added it to bugzilla: Oct 10 2009
http://www.digitalmars.com/d/archives/c++/Code_generation_bug_in_mixing_C_and_C_in_returning_structs_5918.html
CC-MAIN-2015-48
refinedweb
288
76.72
Aspirin Also found in: Dictionary, Thesaurus, Medical, Acronyms, Encyclopedia, Wikipedia. Related to Aspirin: Paracetamol, Baby aspirin Aspirin Australian Stock Price Riskless Indexed Notes. Zero-coupon four-year bonds repayable at face value plus the percentage increase by which the Australian stock index of all ordinaries (common stocks) rises above a predefined level during the given period. Aspirin Australian Stock Price Riskless Index Note. A debt security with no coupon with a return based on the return of a benchmark stock index. Unlike most zero-coupon bonds, an Aspirin is issued at face value; however, like others, it is redeemed at face value at maturity, which is four years after issue. The return (or the equivalent of a coupon) on an Aspirin is the fact that the bondholder receives a percentage of the return on the Australian all-ordinaries stock index provided it is over a certain amount. For example, if the limit is 5% and the return is 9% over the four years of the Aspirin, the bondholder receives a return of 4%. However, if the return on the all-ordinaries index falls below the limit, the bondholder receives no return. Aspirins allow investors to participate in the stock market without assuming all of the risk involved.
https://financial-dictionary.thefreedictionary.com/Aspirin
CC-MAIN-2018-13
refinedweb
207
50.97
wq.io 0.4.1 Consistent iterable API for reading and writing to external datasets wq.io is a collection of Python libraries for consuming (input) and generating (output) external data resources in various formats. It thereby facilitates interoperability between the wq framework and other systems and formats. Getting Started pip install wq.io # Or, if using together with wq.app and/or wq.db pip install wq # To use wq.io's GIS capabilities also install Shapely and Fiona pip install shapely fiona See the documentation for more information. Features The basic idea behind wq.io is to avoid having to remember the unique usage of e.g. csv, xlrd, or lxml every time one needs to work with an external dataset. Instead, wq.io abstracts these libraries into a consistent interface that works as an iterable of namedtuples. The field names for a dataset are automatically determined from the source file, e.g. the column headers in an Excel spreadsheet. from wq.io import load_file data = load_file('example.xls') for row in data: print row.name, row.date When fiona and shapely are available, wq.io can also open and create shapefiles and other OGR-compatible geographic data formats. from wq.io import ShapeIO data = ShapeIO(filename='sites.shp') for id, site in data.items(): print id, site.geometry.wkt It is straightforward to extend wq.io by subclassing existing functionality with custom implementations. - Downloads (All Versions): - 0 downloads in the last day - 12 downloads in the last week - 565 downloads in the last month - Author: S. Andrew Sheppard - Bug Tracker: - License: MIT - Categories - Package Index Owner: sheppard - DOAP record: wq.io-0.4.1.xml
https://pypi.python.org/pypi/wq.io/0.4.1
CC-MAIN-2016-18
refinedweb
278
53.07
Software Glitches Stall Toyota Prius 560 t35t0r writes "CNN/Money/Tech reports that 2004 and early 2005 Toyota Prius models have software bugs that cause them to stall while traveling at highway speeds. While no accidents were reported to have been caused by the software glitch, could we be heading into an era where our automobiles will require software updates and fixes to keep them from literally 'crashing'?" Shouldn't have stolen that code... (Score:5, Funny) Re:Shouldn't have stolen that code... (Score:4, Informative) Actually in this case Ford is paying Toyota royalties to use their Synergy Drive System (the gas/electric hybrid technology at the core of the Escape Hybrid) Re:Shouldn't have stolen that code... (Score:5, Informative) Mostly these technologies have to do with the transmission and, I believe, some of the control mechanisms and algorithms. But, despite what you have read in most media outlets, Ford is not buying parts or designs from Toyota (at this time). Re:Shouldn't have stolen that code... (Score:4, Informative) While there are only a limited number of economical solutions, it's noteworthy that Honda shipped a completely different CVT design for the Civic hybrid. Re:Shouldn't have stolen that code... (Score:5, Informative) That's not "Ford's" problem so much as any number of cars that have experienced accelerator sticks. BTW - if you're still on speaking terms with your ex, you should let her know that if that happens in the future she should have Re:Shouldn't have stolen that code... (Score:5, Funny) I've actually had this happen once with an older Ford - Punched it around a corner and the throttle stuck wide open with a new SUV parked crossways 40 feet away. Didn't touch Nuetral. Went from drive to 1st, 1st to park and stopped about 3 feet from the truck. The kid standing beside it nearly died of fright. I expect doing this with any car made in the last 20 years would leave your transmission in little itty bits... Re:Shouldn't have stolen that code... (Score:5, Funny) I've done it some 20 times at least, and never got even so much scared, except for one time when the stupid throttle got stuck just as I was racing an 18-wheeler after flipping a birdie at him. Which was, of course, somewhat dangerous even without the throttle problems. Re:Shouldn't have stolen that code... (Score:5, Funny) Re:Shouldn't have stolen that code... (Score:5, Insightful) I don't know why so many moderators thought this was funny, but you likely have it exactly right. It happened to me once on an icy road when my car started drifting. I thought I had my foot off the accelerator and on the brakes, but didn't realize why the anti-lock system wasn't working and the engine was making so much noise until I was sliding into a ditch. There was no damage and I was able to drive out, but at that moment I knew exactly how people can believe they had their foot on the brake. Unfortunately, my mother wasn't so lucky. She got the pedals mixed up while manuvering in the driveway behind the house and ended up parking in the neighbor's bedroom (fortunately, no one was home). When my father ran outside and shut down the ignition, she was dazed from the impact, but her foot was still jammed on the accelerator. Re:Shouldn't have stolen that code... (Score:4, Insightful) Re:Shouldn't have stolen that code not informative (Score:3, Informative) Power for PB(Power Brakes)is USUALY provited by vacum assist. This is created by the "sucking" power of an engine as it pu Re:Shouldn't have stolen that code not informative (Score:5, Insightful) Whenever I get a 'new' car, I run down to the nearby college at night and find an empty lot and slide around a bit, and see what happens when I turn the engine off and if I can turn the key back and have it start magically, aka, a push start, which is incredibly useful if your car stalls while you're driving down the highway. (The other option being a normal start in neutral, but that takes much longer. And wouldn't work if your battery was dead, but that's a rather worse-case scenerio.) Then I come back and do it again when it's raining, solely for seeing how it skids. And if I have a car I've never tried it on, and I'm on a completely empty and straight stretch of highway, I kill the engine there, too, to see if it does something different at high speeds. (That's probably a traffic violation, but if a cop appeared out of the blue, I'd just say I stalled for some reason.) I will admit I've never tried to solve a hypothetical 'stuck pedal', but, OTOH, the parking lots aren't really big enough for that. It's a good idea, though. I know I can shift into neutral at any speed, but I agree that cutting the engine is better...for one thing, it should let the engine slow down the car. I'll have to figure out some way to test that. Do people really drive around in a ton of metal and not know in advance how it operates when bad things happen to it? When, exactly, are they planning on learning? The time to learn what happens when you slam on the brakes on a puddle of water is not in the middle of traffic. I once had an early antilock system that pulsed the brakes really oddly...there was a lag between losing traction and the unlocking of the brake, or something, I never really figured it out. I mean, there are somethings you can't learn until they happen, for example, if you really need to stop the car, you can switch into park when you're going 20 mph, but you'd obviously never want to do that unless you had to. But what happens when your engine cuts off, or if you hit a patch of water while turning? Everyone should test that. Re:Shouldn't have stolen that code not informative (Score:3, Informative) you must either be living outside the USA, or are very young and has very little experience with your fellow driver on the roads Yes, 99.997% of all drivers do not know ANYTHING about their car. Hell a large subset of that group can barely drive. Examples? Ok. offramp, semi and a line of cars taking it. Semi merges onto highway as does 40% of the cars, the other 60% try to speed past t Re:Shouldn't have stolen that code... (Score:3, Informative) You know, I don't even know why I'm bothering to keep adding to this thread. It's not like anyone gives a crap. Re:Shouldn't have stolen that code... (Score:3, Funny) I know your wife SAID it was an "accident" when she rammed her Ford Explorer into you, but I've watched enough Court TV to know better. <:) Failover (Score:5, Insightful) Re:Failover (Score:3, Insightful) IIRC, some of the stealth bombers will fall apart in less than a second if the computers go. If the fuel injection is gone because of the computer crash, what do you fail over to? Re:Failover (Score:2) Reminds me of the old clip in Fallout of the car advertisement: All analog! No electronics! (Or some such thing, been years since I played it. Re:Failover (Score:2) Re:Failover (Score:4, Informative) Re:Failover (Score:3, Insightful) How is this a big problem? Have you never had a car stall and these things fail on you before? It's no big deal. You push the pedal a little harder and you put a little more effort into steering. Re:Failover (Score:3, Informative) I would have occasional power steering failures, generally caused by the fluid leaking out of the pump. When this happened, there was no problem controlling the car at speed, but it was an absolute beast to get out of parking spaces. So in short, a power steering failure is actually no big deal It Finally came true..... (Score:5, Funny) Re:It Finally came true..... (Score:3, Funny) Re:Failover (Score:5, Insightful) It did. At least based on the anecdotes posted at edmunds.com by the drivers. The engine shut off, the dashboard lit up like a Christmas tree and the battery continued to power the car. Not surprising that you might conclude total failure from the Guess what folks; you are expected to be capable of coping with vehicle problems while traveling at the phenomenal rate of "highway speed". Tires blow, people fuck up, things fly off randomly; deal with it. Re:Failover (Score:5, Funny) #include <obYouMustBeNewHere.h> Re:Failover (Score:5, Funny) LOL. Note the user id, Mr. 151611. See, it's that 'should' (Score:2) Going down the road, using only a change of the accelerator position: the lawn-mower-esque throttle comes apart. It accelerates to about 90 mph (fortunately, this is a straight country road starting to climb a hill). I'm a little agitated. Mother reminds me that, ultimately, turning the key to off within the ignition will stop any car. Sort of a three-finger salute[1], if you will. [1]ctrl-alt-del Re:Failover (Score:3, Interesting) Actually, that's not the problem. The problem is that we're now starting to see more and more cars using "drive-by-wire" technologies. The gas pedal is no longer a lever controlling an engine aperture directly; it's a rheostat feeding a variable voltage to a computer, which then decides how to adjust the aperture. If that computer gets into an irrecoverable state Re:Failover (Score:3, Interesting) But officer..... (Score:5, Funny) There will be no crashing (Score:4, Funny) I can see it now... (Score:2, Funny) Yes officer, I was trying to figure out how fast I was going but the speedometer was not refreshing and when I looked up "WHAM!" If Microsoft designed cars... (Score:5, Funny) Blue screen of death... (Score:2) Re:Blue screen of death... (Score:3, Funny) Re:Blue screen of death... (Score:2) After all, the color PURPLE is a trademark of 3M. (I kid you not.) BMW?? (Score:5, Informative) More to the point. How does everyone feel giving up full control of thier car? What about the Mercedes digital brakes? There is no physical link between the pedal and the wheels. We were promised self driving cars, and we're on the way to it. Re:BMW?? (Score:5, Interesting) My car (2004 Mazda 3) has a fully electronic throttle body. It's all servo-driven, no linkage between the throttle and the gas pedal at all. If I had thought to check stuff like that I wouldn't have bought it. It hasn't given me any trouble yet (it's a 2004, it had better not), but just wait until the sensor shorts out and tells the engine that I want to floor it, or vice versa. Re:BMW?? (Score:5, Interesting) Simple and functional, and after a while you'll even look forward to spending a weekend maintaining it. I drive a 40 year old vehicle, and wouldn't give it up for anything. As vehicles become more and more drive-by-wire, I only see it as validating my decision. Re:BMW?? (Score:3, Insightful) Re:BMW?? (Score:2, Funny) Yeah, there's nothing worse than your engine shorting out and telling the sensor that you want to floor it. Re:BMW?? (Score:3, Interesting) Re:BMW?? (Score:5, Funny) It's all servo-driven, no linkage between the throttle and the gas pedal at all. If I had thought to check stuff like that I wouldn't have bought it. And a cable is any better? I've been a car where the accelerator cable broke and left the throttle wide open. I suspect a servo might well be more robust than a cable. Luckily it was a 70's era VM Vanagon camper. I think we went from 62 to 63 in the 5 minutes or so we spent playing with the accelerator pedal to see what the problem was. Re:BMW?? (Score:5, Insightful) Re:BMW?? (Score:3, Insightful) But most of us assume that part of the extremely large cost of those planes is in both more reliable technology and increased redundancy. I think the systems of a Boeing 777 are probably held to a higher standard than a Mazda or even a BMW...mostly due to the more catastrophic nature of a failure. Doesn't mean we're right...maybe the systems on a BMW are every bit as reliable as on a plane. But it would still explain this reaction. Re:BMW?? (Score:5, Interesting) Imagine if in 10 years, when there's a minor fender-bender, once the accident is off to the shoulder, traffic picks back up at a regular pace. Now, everyone gawks and traffic stays backed up for miles thanks to that. Or even better, when someone misses an exit, they don't slam on the brakes in the middle of the expressway and back up to the exit. There was an 8 car pileup with numerous fatalities last year on the Baltimore beltway thanks to someone in the middle lane cutting across 2 lanes of traffic at top speed to turn into those "Emergency turnaround" digouts between expressway lanes. If he literally was prevented from doing something that stupid thanks to his car, those people would still be alive. Sure, he'd be 5 minutes later to where he was going... Bring on cars that don't let people be idiots. The rest of us who do a good job of obeying traffic laws will be that much safer thanks to it. As far as software controlling much of our cars, we're already mostly there. Power locks lock you out of your car if they fail. Power steering makes your car nearly unturnable if that fails. Power breaks provide so much extra breaking power that if they fail, your car is basically going to be nearly brake-less anyway. Re:BMW?? (Score:3, Insightful) It can also be the other way around. Take an example where someone is driving the speed limit in the left lane of a major urban expressway. On most of these roads, when traffic permits, the left lane moves at least 10 mph faster than the speed limit. Someone driving the speed limit, obeying the law, will cause drivers behind them to back up and try and go Re:BMW?? (Score:2) Bleh... Ford invented that years ago: it's called a "brake fluid leak". software updates and fixes? (Score:2) Yes. I can just imagine it... (Score:5, Funny) Re:I can just imagine it... (Score:2) Re:I can just imagine it... (Score:2, Informative) It's called a Continuously Variable Transmission (CVT) [com.sapo.pt] and is the same technology as used in your friendly, every-day snowmobile. In a nutshell, it's a chain-driven set of pulleys that resemble a pair of cones that move together and apart to give you a near infinite number of ratio combinations Re:I can just imagine it... (Score:5, Informative) The Prius does not use any belt or cone system. That is the older CVT used in other cars many years ago. The Prius uses a planetary gear set to transfer power around between its various inputs/outputs. See this article for more details: [howstuffworks.com] "Crashing" (Score:2) More on-topic, Slashdot recently ran an article about some guys trying to infect a Prius via Bluetooth, and were able to accomplish a system crash repeatedly. Turned out to be low on battery power. Software fixes are already part of auto recalls (Score:5, Informative) Re:Software fixes are already part of auto recalls (Score:2, Interesting) Among us for some time indeed. A friend of mine had a similar problem two or three years ago with a Peugeot. I do not rememember the model, but it was one of the first batches out of the factory. She had problems with the engine shutting down sporadically while driving (at any speed). This happened one or twice. She went with her car to the garage, and the mechanic told her, blank face, "Known problem. Needs a software upgrade. Come back in two weeks time, we have place in our schedule by then". Of course s Isn't the engine designed to turn off? (Score:5, Funny) what i'm waiting for (Score:4, Interesting) you would watch it move like a wave through traffic: on one end, normal moving traffic, on the other, fender benders and honking horns and frozen cars it would move under overpasses and propagate upward and spread in either direction, like dominoes awesome and frightening and completely plausible in the next 10-20 years Re:what i'm waiting for (Score:4, Informative) hour long software upgrade (Score:5, Funny) They meant: It's a five minute software upgrade, but if we told you that, you'd be upset when the service dept made you wait for an hour. There is a reason VW Beetle (Score:2, Insightful) is still the world most reliable car it has nothing to do with electronics Re:There is a reason VW Beetle (Score:2) Car Firmware Upgrades and Rebooting on the Road (Score:3, Insightful) Back in the 80s, I had an old beater 1971 Chevy Van with the usual Weird Chevy Electrical Problems. Every once in a while the engine would stop running while I was driving down the road (which is a problem for power steering...), so I'd put it in neutral and reboot, which would usually work. My current van is a 1987 Chevy, with a new engine installed about 5 years ago. The engine's not quite identical to the original, and every once in a while the monitoring system decides something's wrong and turns on the "Service Engine Soon" light, typically when I accelerate to pass somebody while going uphill on a freeway. There's no harm done, as long as that's the cause (as opposed to something actually being wrong with it), but to turn the light off you also have to reboot the car. Re:Car Firmware Upgrades and Rebooting on the Road (Score:2, Informative) Uh, that's a classic sign of an air leak and one of the sensors is picking up either too much or too little pressure. Could also be the knock sensor, O2 sensor, etc. Read the code from the computer and see why it turned on the light, duh... Updating software (Score:5, Insightful) Without putting too fine a point on it, yes! But there is no reason to go all chicken little. Standards of reliability for automotive software are generally much higher than for desktop PC software. No EULAs and auto manufacturers generally can not disclaim warranties. If a car breaks down due to crappy software, Consumer Reports will put out a report and people won't buy it. Additionally there are Lemon Laws and lots of eager lawyers to protect consumers. Unlike PCs where we have been trained to expect crashing software, people don't put up with that in cars, especially since there is the potential for physical harm when hurtling down the road at 80mph. That "era" started long ago (Score:2) It's been well known for a long time that parking a computer-equipped car (that is, one with at least electronic ignition and/or electronic fuel injection) under a high-voltage powerline can very well "crash" the computer or scramble the computer's memory to the point that it's impossible to start. I first heard of that problem when I was a kid, and I'm not all that young Aren't We Already There??? (Score:2) Do a search for "software" on this page [internetautoguide.com] If its software driven. (Score:2) "...could we be heading into an era where our automobiles will require software updates and fixes to keep them from literally 'crashing'?" Yes. Figures (Score:2, Funny) "Please insert your Prius into the original location from which the software was installed." Slashdot reporting (Score:2, Informative) From the actual article: The report said no injuries or fatalities have been linked to the problem, but it did not say whether there had been accidents due to the problem. Close enough for government work, eh? Nothing new (Score:2) My friend has a Merc S500, and he mentions havi Perspective (Score:5, Insightful) What OS are they running? (Score:2) I know that Steve "Woz" has several of them. Maybe he can talk to Steve J about putting OS X in it. BSOD (Score:2) Hah (Score:2) Of course when a old-style mechanical car has a problem at least you can just connect it to a modem and get a redesigned fuel system dropped in without and cost or hassle! Yet one more reason (Score:2) Wouldn't have it any other way. If Microsoft made cars... (Score:2, Funny) (From Here [vbrad.com] Micr Re:If Microsoft made cars... (Score:3, Funny) Yes, there are still a few wandering nomads in equitorial New Guinea who haven't seen the "if cars were as unreliable as computers" joke yet. Good job! Missing the point (Score:2) Cars... (Score:2) The Volkswagon Bug (Score:2) Engineering philosophy (Score:3, Insightful) Regular devourers of world news will recall that a few years ago, Bridgestone/Firestone got sued for producing tires with a propensity for exploding. A few years before then, there were horror stories of malfunctioning cruise control that would activate itself due to a short-circuit, with no way to switch it off. Actually, a similar fault to that last one even appeared on the Space Shuttle - the last launch window was scrubbed when it was realized that the attitude rockets could fire themselves, even when the power was switched off. Engineering to build fault-tolerent systems (ie: systems that will still behave sensibly, even when something goes wrong) is expensive, difficult, time-consuming and requires enormous resources to cover every possible aspect. Even when faced with the prospect of multi-million dollar lawsuits for death/injury, it is often cheaper to simply let people die a torturous, firey death in agony than to prevent such incidents from arising. Because we live in a competitive world, where success is measured in dollars, there is simply no incentive to get things right. Getting things affordably wrong is a far more profitable approach. It would be possible to build a car that can do 100 miles to the gallon, be able to keep the occupants intact after a 150 mph head-on collision (F1 monocoques can handles 240 mph collisions) and have software driving every aspect of the system that is not only 100% free of bugs but is able to adapt to handle the natural degredation of the hardware. Such a car would cost about as much as a NASA Space Shuttle and don't expect the insurance to be any less, simply because of the theft value. A company producing such a car might sell as many as one. The McLaren F1 road car would be much more affordable but is wtill somewhere in the low double-digit sales, and was reportedly still in single-figure sales at the end of the first year. Having said that, I think that it should be mandatory that car companies produce the very best they can. Failure is not only an option, it's often so cheap that it's the best option. That should not be the case, ever. Bugs in software and failures of hardware are going to happen in the Real World, but they should not be encouraged. Good practices, good designs and thorough design reviews should be the norm. When too much tech is a bad thing (Score:3, Interesting) Growing up we did most of our own car repairs, changed the oil, etc. But with our newer car we cannot do a lot if something goes wrong, especially with electronics which is what fails 90% of the time. The day my push mower won't start because of a faulty sensor is probably the day I really get mad. Why? Because with all this technology, I think many, especially engineers, might have forgotten that true genisus is making something complex simple. Too often I think we are making simple things way too complex. Larger picture (Score:5, Insightful) Electronic systems are, in general, more reliable, with lower failure rates, than the mechanical systems they replace. They are also easier to service. (Though the repair bill may very well be higher, and specialized equipment may be necessary.) This "software", as others have said, are not the same as the software we run on our PCs. The software quality standards are higher, and the testing is far more intense. People lament the loss of simpler mechanical systems that can be fixed with know-how and a socket set. We publicize every example of a system failure we hear of. But the numbers don't lie: a 2005 model with a half-dozen embedded computers has a far lower incidence of problems than a corresponding 1970 model when it was new. You are far less likely to ever have to call a tow truck in your lifetime than your father/grandfather was. Sensationalism is so much more fun than fact, though. Re:Larger picture (Score:4, Insightful) I've spent a lot of time looking Consumer Reports' car reviews, and frankly, their reviews have no basis in reality. Cars that were rated as extremely noisy, may be quieter than cars rated as quiet. I know this from experience. Go read their reviews of a few cars you have owned, and see if they match reality. Now, you can certainly attribute that to different reviewers having different standards, or to individuals' biases, but it seems to be very widespread, and seems obvious to me that it's always in favor of one brand or another. I can't prove it, but it looks very much like certain companies (eg. Toyota) are getting far more favorable reviews than the best cars of other makes, even on their poorest offerings. I've come to this conclusion long before I came to this thread, so the fact that the car in this case happens to be a Toyota is coincidence. That's really not true. I've never had a mechnical cooling fan fail on me, while I've had a few electric fans fail. Which would you will find in trucks? Not electric. Now that's just blatantly wrong. The only problems that are easy to fix on computers are the problems introduced by the computer. For instance when the warning light comes on, sensors go crazy, etc. You may also have heard of cases where certain models of cars will drive fine for 80,000 miles, then like clockwork, start running too rich/lean/etc. It's debatable whether car manufacturers are intentionally inducing these faults, but it is not debatable that these faults are there, and tricking the computer can commonly fix problems the computer has caused. The numbers don't lie, but you sure do. Those numbers are certainly due to improvments in engineering vehicles, (manufacturing/design) improvements to mechanical parts, improvements in fluids, materials, etc. It's only common-sense that those numbers would improve. Also, the Those numbers are also deceptive, because people don't complain much about computer problems with new cars. Give me numbers when those cars are 5 years old, the we'll see. I'm tired, so I'll say the one thing that will end this arguement instantly: New BMWs I hope this gets duped... (Score:5, Funny) Oh wait, this is slashdot, even the dupe is going to have tired jokes. New Microsoft Slogan (Score:3, Funny) My Prius has done this thrice... (Score:4, Funny) It seems to me that the problem occurs when the computer tries to restart the engine, and it doesn't catch immediately. It does seem that the car will continue to run as an electric car, and it does seem to come its senses within a few seconds. My blindingly white Prius is nicknamed "Snowcrash" for exactly this reason -- if the computer goes down, it's just a car shaped hunk of metal. Thad Beier Eerie coincidence (or maybe not!) (Score:3, Funny) The driver was wandering around the hood looking like he wanted to open it, but had no idea what to do when he did Re:old school (Score:2) Re:old school (Score:2) (Disclaimer: I work for a major automotive electronics supplier. That said, all of the above is true.) Re:Crashing? I can see it now. (Score:2, Funny) Re:Crashing? I can see it now. (Score:2) I'd be more happy to see more work being done on the prius, and alternative fuel vehicles like it. Re:Crashing? I can see it now. (Score:3, Funny) Well no, Minardi cars can start without an activation key. Re:Cars already need this.. (Score:3, Insightful) I call BS on this one. Re:Cars already need this.. (Score:3, Informative) >> The steering is even drive by wire. I think this is only partially correct. That car, like all other cars to date, has a direct mechanical connection between the steering wheel and the angle of the front wheels. That connection is the primary means of changing the car's direction. You should be able to observe this by turning the ignition to the unlocked (but off) position and observing that the front wheels still budge when you turn the wheel. Volvo does Re:Cars already need this.. (Score:3, Informative) No car in production today has drive by wire steering. Mercedes has drive by wire brakes, but even those have a mechanical backup in case something goes wrong. And no auto manufacturer in their right mind would design a car to operate using a client/server architecture. What would be the point? You could sit in your car and control a Volvo on the other side of the parking lot? I think you're just throwing out buzzwords and hoping for a mod up. Irresponsible post (RTFA)! (Score:3) Re:Irresponsible article! (Score:3, Interesting)
http://it.slashdot.org/story/05/05/16/1859251/software-glitches-stall-toyota-prius
CC-MAIN-2014-52
refinedweb
5,162
71.14
Conservapedia:The Zeuglodon Blues In March 2010, a discussion board of the sysops at Conservapedia was leaked.[1] Most probably authentic and spanning the time from early 2008 to early 2009, the discussion brings back fond memories of cherished Conservapedian moments. As every reader finds his own nuggets of lulz, feel free to add. Contents - 1 Common themes - 2 Andy displays his monumental gullibility - 3 Quotes by individual users - 4 Fellow sysops' thoughts about TK - 5 Lenski affair - 6 Read your own name - 7 Plan approved, execution delayed - 8 Misc. observations - 9 See also - 10 External links - 11 Footnotes Common themes[edit] Looking beyond individual discussions, several things came up again and again throughout the year. The most striking issue was that Andy's personal opinion was explicitly regarded as The Truth. This is why Conservapedia labels itself as a fact-based and trustworthy encyclopedia while at the same time simply being Andy's blog. Not toeing the party line (or even openly discussing with Andy about such things) was viewed as insubordination. TerryH, in particular, seems to have placed Andy in his personal pantheon. This also resulted in the growing trend that public discussions in general were highly undesirable. Not only was discussing regarded as a waste of time, but some sysops figured that Conservapedia would be able to attract high-ranking conservatives like William Bennett or Ann Coulter if only people stopped questioning obvious truths like Obama using his mind control powers to win the election. In fact, most CP sysops had a general problem with people who disagreed with their views and described the opposition in ways that would make WW2 propaganda posters jealous: Anybody who disagreed with any of God King Andy's views was a liberal, and when liberals are not busy shoving drugs and aborted babies into family's faces or burning churches,[2] they are trying to force conservatives to think like them. The only group worse than regular liberals are RationalWiki members whose sole goal is to destroy Conservapedia. The war against RW will only be won when one of them is in prison. Another trend was how the "Sysops are not allowed to undo another sysop's blocks" rule was handled. Sysops were supposed to discuss these things in private or in the discussion group because they wanted to present a united front to the public. Questioning a sysop's decision in public was undermining his authority. Similarly, those who questioned even the strangest blocks were accused of aiding liberals and saboteurs who aimed to destroy the site; new users were regarded as undercover saboteurs until proven otherwise. There were two ways of proving yourself; either by gaining Andy's favor (e.g., noted parodists Bugler and Rod Weathers) or by providing evidence as to one's real identity. Andy displays his monumental gullibility[edit] Andy explains his reasons for reappointing TK as a sysop during the 01 January 2009 promotions:[3] TK has ruffled feathers on our side, but mostly on the other side. He's never vandalized the site and his self-initiated "double agent" work (which Philip documents in another thread) was merely that. It was not a sincere effort to harm the site. TK was defrocked by Conservapedia and yet returned to volunteer more, something very few people would do. Our general policy has been to restore privileges to those who make a good faith return and request for them. I've done that in the past as a matter of routine. Given the strong support (Note at least 3 sysops expressed reservations about TK's re-appointment) by several in this group for TK becoming a Sysop again, it seems appropriate. It is needed to protect images. (Our emphasis) Quotes by individual users[edit] Andy[edit] TK: I blocked TimS (CPAdmin1) for being an arguing troublemaker, but I did it with love. Andy: "Thanks for your kind and considerate comments, Terry". [4] I wouldn't rely on FoxNews, which is not as conservative as it pretends... From: Tom Moore & Phil Scheur blocking decisions[6] [Sesame Street] is a show that has long pushed unusual multiculturalism on kids. Nuggets of Wisdom from Uncle Ed[edit] From "How long are we going to tolerate TK?" (part 1):[7] Ed: From long experience, I can tell you that they way to shape someone's behavior is not with an axe but with a whip. From "How long are we going to tolerate TK?" (part 2):[8] . . . From "Guidelines Change/Quality of Sources:[9] On whether books or internet sources are better: I'm biased in favor of electrons (designed and created by God) and against paper (a man-made invention). But I'll follow the consensus on this one. ;-) From "Socialist Healthcare Files"[10] On use of the International Phonetic Alphabet spellings at Wikipedia: Wikipedia has taken internationalization to such an extreme that it borders on anti-Americanism. From "Old sysop RobS" [11] My concern is that he [Rob Smith] NOT, please dear God, under any circumstances, be brought suddenly into into our private Zeuglodon Blues mailing list. You all remember the trouble we had last time. We cannot afford to have quarrels in this discussion group. That kind of stuff just paralyzes us. And that's why, even when I lobbied for TK's restoration to the project, I always said leave him out of the discussion loop. Rob and TK may be zealous foes of liberal trolls, but they just don't "play well with others" when it comes to discussions amoung [sic] sysops. From "Inappropriate block by bugler, followed by 'edit warring' over it" [12] [Defending Bugler] Let's not jump on the bandwagon of "justice" and "politics of personal destruction" which liberals use to get their way and consolidate their power. Let's see some Christian love and brotherhood around here. From "Unencyclopedic?[13] I have a fairly good idea of what is encyclopedic. I have extensive experience in this matter, on two major online encyclopedia projects. One is Wikipedia, which I helped turn into the world's top ten website.. From "Problem with Math entries"[14] I think that a 760 SAT in math (in high school) qualifies me as a math expert. I have corrected numerous mistakes in our math articles. Some may have been made out of ignorance; others may be deliberate sabotage. I am suspicious that hardly any one but me has been able to produce an error-free article on any aspect of math below the university level. From "Curses and insults [15] You'd have to be an idiot to think that phrases like "don't be a dick" or "don't be an idiot" are generally considered to be insulting. Nuggets of wisdom shit from TK[edit] You should never feel obligated to keep re-explaining. From "The After-effects of RodWeathers and Bugler [17] (or why TK doesn't think wiki-admin is necessary) The "Housekeeping" chores have never been enumerated, or the supposed need for them to be done explained, Jessica. Some of those lists, they appear to be needless "make-work" chores, not important to proper wiki function. and Most merge candidates I have seen are senseless and a product of our enemies desire to cripple CP. Yes, that is a known method of theirs; confusion and disruption. Bill, this place isn't about anyone's differences. They don't matter one bit. This place, and CP, is about Andy Schlafly, and what he wants From "Fwd: Conservapedia e-mail [19] Let's not go deactivating new accounts too quickly, is all I ask. Geo.plrd[edit] From:"Inappropriate block by bugler, followed by 'edit warring' over it" [20] (With that kind of thinking, no wonder conservatives lead us into things like Enron and the Credit Crunch.)(With that kind of thinking, no wonder conservatives lead us into things like Enron and the Credit Crunch.) Geo.plrd: Andy is still the leader of Conservapedia. We serve at his pleasure. He does not have to listen to senior sysops. In business, my way or the highway is the way it works. When your supervisor makes a bad decision, you don't complain about it, because you will be fired. From:"Massive attack on site" I guess that the public schools aren't learning people properly. [21] Fellow sysops' thoughts about TK[edit] Geo.plrd:Is anyone here a psychotherapist? I would be interested in TKs psychological makeup. Karajou:I remember a Far Side cartoon a few years back, in which the psychiatrist has penciled (sic) in his notepad three simple words about the patient on his couch: "just plain nuts!" I can't help but think of that right now![22] Conservative:TK told me when we had a dispute about search engines that he recently talked to a founder of Google and that I was wrong. Well, I know I was not wrong and I don't believe that TK did talk to a founder of Google. I don't trust TK farther than I can throw him. [23] TerryH: "This is TK all over again. In fact...has anyone done an elementary thing like run CheckUser on the TK and Bugler accounts to make sure that those two jokers are not one and the same man?" [24] Lenski affair[edit] From folder 610, file eafacd8f8 Summary: PJR (notably one of the more intelligent members of Conservapedia by an order of magnitude) has reservations about Andy's letter to Lenski. DanH and TerryH can't imagine what could possibly go wrong, with TerryH proclaiming ironically that evolutionists are so over-confident that they never expect to be discredited. LearnTogether senses that it might be wiser to follow the lead of AiG or other experienced groups. Then Lenski's reply arrives at Conservapedia, creating a shockwave of pwnage which was still measurable on its fourth passage around the earth. Ed Poor reads Lenski's reply and declares victory. PJR: I noticed that Andy now has ten people willing to "sign" the proposed e-mail to Lenski (see) along with him. A few are familiar names who were discussing the issue before this proposal was made, but others have appeared from almost nowhere, including editors with few or no other posts. (Four have no other edits or their post to this page was their first edit. Another three have few other edits.) Then I found the likely source. On RationalWiki, there is an encouragement to "Sign up now to ensure Andy starts really bothering Prof. Lenski!". They presumably believe, as do I, that the proposed letter will only serve to make Andy and/or Conservapedia look silly. So they want Andy to send the letter. Shouldn't RationalWiki wanting something sound alarm bells about whether or not we should be doing it? DanH: Do they elaborate on their rationale for wanting us to send the letter/point out what they specifically think would discredit Conservapedia? TerryH: I wouldn't expect them to. They are so convinced that "evolution" (read: /methodological naturalism/) is "the scientific truth" that they can't imagine that anything could possibly redound to the discredit of anyone except their enemies. LearnTogether: Personally, if possible, I would recommend that we "piggy-back" with an organization that already has an active presence in the scientific community. Perhaps an ICR, Answers in Genesis, or any other group that deals in these areas on a regular basis. It would certainly give our position more clout, and may help us in the learning curve of understanding what is normally deemed to be acceptable behavior and what is not. Ed Poor: Lenski's answer was condescending. Much of it amounts to saying, "I already answered those questions before." A sincerely helpful, genuine scholar would actually answer the questions instead of dodging them. This is typical liberal behavior. It makes Lenski look bad - not us. PJR: First, what's wrong with saying "I answered those questions before" if in fact he did? Second, not only did he say something like that, he /also/ gave answers. That's not dodging them. Third, and perhaps more to the point, your response totally failed to address the point of the message you were replying to. And, for those that haven't noticed, my concerns with some of the signatories have turned out to be well founded, with a number of RationalWiki people registering various user names simply to add their vote to sending the e-mail. Which leaves the alarm bells ringing even louder: Why are we going ahead with doing something that they /want/ us to do, if not because they believe that it will make us look silly. We should follow the lead of the professional creationists in pointing out that Lenski's research does not support evolution nor disprove creation, rather than pursuing a pointless goal that seemed good at the time. Would you like to see my credentials on why I believe I'm a better judge of this than anyone else here? Read your own name[edit] The first thing for a man of some vanity is to search for his own name to appear in the discussions... DiEb[edit] ... only appeared two times, in 490 and 500, when Philip J. Rayment says to Ed Poor: You've been known to misconstrue comments before (e.g. DiEb), and And no, it's fallacious to argue that a legitimate newbie would surely find a way to get in touch with us and convince us of their sincerity. DiEb is an example: He sent numerous e-mails to various people, and got only /one/ response! And even then it took an effort, because we are not inclined to believe people who say that they are innocent! Sid[edit] Mostly a bad memory of CP's ancient past, but every now and then becomes a looming threat at the horizon despite not having raised a finger on CP since his banhammering. As TK speculated in the 230 folder: Remember, the guys there, have several names, like GhengasKahnt/BrianCo, who is also MadMin there, CatWatcher, etc., etc. I am pretty sure Bugler is Sid or Wikinterpreter. Major claim to fame would be the (quickly obsoleted) anti-hack script from the time someone rewrote CP's links. But alas, it looks suspicious with the rw mentions in there as Dean noted in the 530 folder... Qwest[edit] From folder 120: Karajou: "QWest may have shot himself in the foot when he posted that bit of garbage (the Conservapedia hitlist), and if it suggests something worse than political assassination we can go after him. I suggest notifying his ISP as to what transpired. Then I suggest notifying each of the senators on the list, as well as the state governors mentioned in the article." Followed by TK: "YES. I have no idea how to, but put it into his block to scare him." Ace McWicked[edit] In 450;1c70320451ecdedb, Ace McWicked is identified as various "Bill" characters, BillC, BillD, BillE etc. This leads to the quip by Brian MacDonald that Ace "displayed too much of a persistance in getting into Conservapedia under whatever name he can create". Obviously, he may not have noticed the unusable names game. In 460;0d375229566cf1c0: kara…@gmail.com: I blocked AceMcWicked again, this time under user MrMike. Here is a list of his socks, courtesy of running check user: MrMike (Talk / contribs / block) (Check) (21:01, 18 September 2008 -- 23:21, 18 September 2008) [6] (Blocked) 203.xx.xx.xx AlexM (Talk / contribs / block) (Check) (22:48, 16 September 2008 -- 22:59, 16 September 2008) [5] (Blocked) 203.xx.xx.xx JonoP (Talk / contribs / block) (Check) (21:28, 15 September 2008 -- 22:15, 15 September 2008) [6] (Blocked) 203.xx.xx.xx ScrewyouKarakjou (Talk / contribs / block) (Check) (21:13, 11 September 2008) [1] (Blocked) 203.xx.xx.xx ClarkeD (Talk / contribs / block) (Check) (21:00, 25 August 2008 -- 20:11, 10 September 2008) [107] (Blocked) 203.xx.xx.xx PeterSK (Talk / contribs / block) (Check) (21:50, 13 August 2008 -- 23:34, 13 August 2008) [8] (Blocked) 203.xx.xx.xx JohnsonB (Talk / contribs / block) (Check) (20:58, 12 August 2008 -- 21:01, 12 August 2008) [2] (Blocked) 203.xx.xx.xx FrankMilton (Talk / contribs / block) (Check) (22:13, 10 August 2008 -- 22:15, 10 August 2008) [2] (Blocked) 203.xx.xx.xx AlJones (Talk / contribs / block) (Check) (21:55, 7 August 2008 -- 21:56, 7 August 2008) [2] (Blocked) 203.xx.xx.xx HaroldB (Talk / contribs / block) (Check) (21:27, 6 August 2008 -- 21:28, 6 August 2008) [2] (Blocked) 203.xx.xx.xx AMcW (Talk / contribs / block) (Check) (20:51, 5 August 2008 -- 20:55, 5 August 2008) [4] (Blocked) 203.xx.xx.xx AceM (Talk / contribs / block) (Check) (22:29, 4 August 2008 -- 22:41, 4 August 2008) [4] (Blocked) 203.xx.xx.xx JohnK (Talk / contribs / block) (Check) (18:39, 31 July 2008 -- 18:40, 31 July 2008) [2] (Blocked) 203.xx.xx.xx PeterQ (Talk / contribs / block) (Check) (20:04, 29 July 2008) [1] (Blocked) 203.xx.xx.xx JJacob (Talk / contribs / block) (Check) (19:28, 7 July 2008 -- 20:56, 22 July 2008) [110] (Blocked) 203.xx.xx.xx As JJacob he did a lot of subtle damage to the site. As Ace in RW he boasts about the damage he has caused or will cause. Again, I implore everyone that has it run check user on every individual who comes into the site. [Ed. Emphasis added, pipes removed and IP addresses obscured] Plan approved, execution delayed[edit] - On March 17, 2009, Conservative suggested to install social networking buttons on his pet articles (or the entire site, whichever would have been easier).[25] CPWebmaster and Andy approved, yet one year later, we still can't dig it up. - Ed suggested at least twice[26] to allow users to edit their own talk page after a block or ban in order to communicate more easily with the blocking sysop and to quickly clarify if there had been an error. But even though it's just a simple option and nobody was against it, the proposal was never implemented. - Namespaces for essays and debates have been suggested since at least April 2007img (making it older than the Night of the Blunt Knives). In June 2008, the topic was brought up again, and Andy promised to make it a priority.[27] The proposal will soon have its third anniversary withoutimg being set into motion. Although this useful proposal languishes, 8 namespaces were created for the quite useless "Contest"; setting these special namespaces up was actually more difficult than setting up the proposed namespaces, because the contest namespaces had associated user groups and visibility settings. - Even though mentioning "RationalWiki" in any way on CP is absolutely forbidden, Karajou had planned to dedicate a CP article on it in 2008.[28] - Another of Karajou's stillborn suggestions was that CP be divided up into various "curriculums", with a sysop heading up each one. Examples included Religion, Christianity (which had to be kept separate from Religion... interesting), Science and History. However, apart from TerryH leaping in a declaring himself "professor and chairman" of the Department of Bible Study, and at least as "adjunct professor" in the Departments of Astronomy/Cosmology and Creation Science nothing happened. [29] Misc. observations[edit] - The Information Warrior's Handbook was cited frequently and has completely warped the perception of how a trustworthy editor should act. Apparently, because several passages of the Handbook basically instruct socks to act like normal good-faith editors, people who act normally have to be socks and those who don't act normally while still toeing the party line are fine, right? Hilarity ensued, and the fallout included: - blocking zero-edit users after a certain delay (between 48 hours and some months)[30] - suspecting HelpJazz to be a deep-cover parodist because he had been helpful and had stuck around for a long time,[31] - justifying Bugler's blocks even after he had been identified as a parodist, reasoning that - according to the Handbook - socks are supposed to act like good Christian conservatives and not to block innocents.[32] - Ken made a thread to announce that two atheists have created YouTube videos about his Atheism article and (maybe rightfully) thinks that a video of Andy promoting his pet article would have a brown note effect on atheists. The reaction of his fellow sysops is eccentric even by their own high standards: The discussion instantly turns to THE RAPTURE.[33] - Filed under "Policy Proposals from Hell", Ed Poor made the suggestion to put all new users on probation and to ban them unless enough sysops approve of them. In the same vein was his suggestion to block them for a month if they don't contribute good content regularly. Nobody reacted to this proposal, likely because CP had already been operating under a much stricter code of conduct: Ban them if at least one sysop disapproves.[34] - PJR provides a bit of information on how much RW influences CP pageviews - one day, he created two articles. One was mentioned on RW, and two days later had 273 views. The other, un-mentioned article had 11. [35] - Karajou - "This user is in violation of 90/10, but he agrees with us. Let's change/ignore the rule."[36] - Karajou: "Sorry to bust your bubble, Phillip, but when I say so-and-so troll is AmesG, he's AmesG." Sadly, everybody appears to be AmesG.[37] See also[edit] - Conservapedia:Special Discussion Group - Conservapedia:Quagga Prime - Conservapedia:Conservapedia Group - Conservapedia:Fab Five - Forum:Latest dump discussion External links[edit] Footnotes[edit] - ↑ At a blog tracking the goings-on at CP, a link to the contents of Conservapedia’s Zeugloden[sic] Blues chat room was made public. One can also go to the direct link provided to access the lulz. - ↑ We are not making this up: 440/a5b1b68361b37119.html - "Saul Alinsky" - ↑ 250/f10bbe861e1bb6aedf1e674aba293b1e.html - 5 new Sysops for the New Year's (sic) - ↑ 70/bca8... - ↑ 90/9069fa1f68fc6e6f.html - ↑ 770/c7a79248e780a6c3.html - ↑ 860/d0f1c0a9e00ee7da.html - ↑ 860/d0f1c0a9e00ee7daa8ff39c21ca65336.html - ↑ 840/0ec18358753debd0.html - ↑ 10/b43956f20878731f.html - ↑ 660/5e02a294fd4d64bb.html - ↑ 360/28b7a0502878a355.html - ↑ 710/cd5515ffc50cd21f.html - ↑ 210/f58247ee1fe8a02d.html - ↑ 890/4dac6491fcdfeaa1.html - ↑ 10/0075b3ce10883354.html - ↑ 50/befb37de0aa557a9.html - ↑ 170/0e91789c500c29c3.html - ↑ 50/5690008a425caf5a.html - ↑ 360/28b7a0502878a3552fa54952af7da46b.html - ↑ 720/3e8da355a572e010.html - ↑ 890/4dac6491fcdfeaa1.html - Curses and insults - ↑ 320/10d39ca7d42157a1.html - ↑ 360/28b7a0502878a355.html - ↑ 10/bbab6bd77513bddf.html - "social bookmarking tags for our most popular articles to get them to rank higher at the search engines - Can the wiki software do it?" - ↑ In 700/939ab810f3e00c69.html ("blocked user", May 2008) and 160/da1b8036a78f06e5.html ("Jp's block of JustSayin", January 2009) - ↑ 590/22b7fe34b449527b.html - "Namespaces" - ↑ 720/af3866c70aac99d9.html - "Ratwiki article" - ↑ 50/c05cba5ca927643f.html - ↑ 190/f59341e4e6ffa35e.html - "IW handbook & passive socks" - ↑ 290/e86357a5992d81a4.html - "HelpJazz - home for Christmas?" - ↑ 250/f10bbe861e1bb6aedf1e674aba293b1e.html - "5 new Sysops for New Year's" - ↑ 690/9965f2990dd4c665.html - "2 Youtube atheist videos on atheism article. Time for Andy to be unleashed!" - ↑ 510/8cc5729b724ebc20.html - "Probation for all new users" - ↑ 480/4b7f... - ↑ 260/f2d1... - ↑ 790/5ca0c03d276607c6.html
https://rationalwiki.org/wiki/Conservapedia:The_Zeuglodon_Blues
CC-MAIN-2020-40
refinedweb
3,855
61.67
Server posts. You may still be wondering how useful server-side JavaScript can be in an App Engine app. Here's a few example use-cases: - Allow users to provide custom code to be executed when conditions are met in your app. - A tool for writing straightforward RESTful APIs for text mainpulation etc. - A programming game, allowing people to submit programs that compete against each other for rankings. - A CodeWiki, where users can enter code and demonstrate the result of executing it. - A Google Wave bot that executes code entered in a Wave and adds a response with the result. - A tool for performing operations over the entire datastore without having to explicitly cater for breaking tasks up into smaller chunks. That, of course, is just a few ideas - I'm sure you can think of others yourself. Let us know in the comments if you think of anything interesting! Implementation Using Rhino is surprisingly simple. Create a new Web Application Project, select App Engine, and unselect GWT. I've called mine 'rhinopark'. Open index.html in the war directory, and replace it with the following: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http- <script type="text/javascript" src=""></script> <script type="text/javascript"> function sendCode() { var code = $("#code").val(); $("#output").load("/rhinopark", {"code": code}); } </script> <title>Server-side JavaScript demo</title> </head> <body> <h1>Server-side JavaScript demo</h1> <pre style="border: 1px solid black; width: 590px; padding: 5px; margin-bottom: 16px;" id="output"></pre> <textarea id="code" style="display: block; width: 600px; height: 300px;"></textarea> <input type="button" value="Submit" onclick="sendCode();" /> </body> </html> This is all very straightforward. We provide a textarea for users to enter code in, and a submit button. Instead of a regular form submission, however, we use JQuery to send the code to the /rhinopark URL on the server, and insert the response in the 'output' element. Next, you need to download Rhino. Extract the file 'js.jar' from the downloaded zip, and copy it to the war/WEB-INF/lib subdirectory of your project. Right-click on your project's entry, and select "Build Path -> Configure Build Path". Then, click on Add JARs..., and select js.jar from the directory you just placed it in. Then, open the RhinoParkServlet that was created automatically, and replace the body of the class with the following: public class RhinoparkServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); String code = req.getParameter("code"); Context ctx = Context.enter(); try { Scriptable scope = ctx.initStandardObjects(); Object result = ctx.evaluateString(scope, code, "<code>", 1, null); resp.getWriter().print(Context.toString(result)); } catch(RhinoException ex) { resp.getWriter().println(ex.getMessage()); } finally { Context.exit(); } } } This snippet illustrates the basic steps of using Rhino. First, we call Context.enter(). This returns a Context object, which we will need in order to use Rhino, as well as setting the thread's context to the returned object. The rest of the code is wrapped in a try/finally block, to ensure that Context.exit() gets called once we're done. Next, we call initStandardObjects() on our Context. This creates a Scriptable we can use as a global scope, containing the basic objects that JavaScript scripts expect to find in its environment. Then, we call evaluateString on the context, passing in the scope we created, the code to execute, a name and line number for the module, and an optional security manager we don't need one, so we leave it as null. This actually executes the code, returning the result. We stringify the result, and write it to the response. If the Javascript has an error, Rhino will throw a RhinoException when we call evaluateString. In that case, we catch the exception and return it in the response instead. Try it out - start the development server, and go to. Enter a snippet of JavaScript and click 'Submit' to see it evaluated and returned. Sandboxing All isn't quite well yet, though. Try entering the following snippet in the console: new java.lang.String("foo") Rhino supports a JavaScript feature called LiveConnect, which assists interoperation between Java and JavaScript by making it possible for JavaScript to seamlessly instantiate and use Java classes. Unfortunately, on its own, this constitutes a huge security hole. Rhino makes it easy to patch, however. Create a new class in the project called DenyAllClassShutter, and enter the following: public class DenyAllClassShutter implements ClassShutter { public boolean visibleToScripts(String arg0) { return false; } } This class implements the ClassShutter interface from Rhino, which has a single method, visibleToScripts. This method is passed the name of a class or package, and is expected to return a boolean indicating if the class or package in question should be accessible from JavaScript. Since we don't want to permit any LiveConnect functionality in our case, we simply return false always. To make use of this, we need to make a single modification to RhinoparkServlet: Context ctx = Context.enter(); try { ctx.setClassShutter(new DenyAllClassShutter()); Scriptable scope = ctx.initStandardObjects(); Try the snippet from above again - it will now return an error. In a future post, I'll pick up the embedded interpreter theme again, and we'll see what other neat tricks we can play with it on App Engine.Previous Post Next Post
http://blog.notdot.net/2009/10/Server-side-JavaScript-with-Rhino
CC-MAIN-2015-06
refinedweb
886
58.08
i'm doing java exercise, their is 6 question and i had done 5. another 1 i tried all the alternative but still error. this code: class __(1)__ { static ___(2)___ int MIDTEST = 30; public static void main(String [ ] args) { int a=15, b=10, quiz, ___(3)___; Course ____(4)___ = new Course( ); quiz=courseWork.calculateMark(a); assignment=courseWork.calculateMark(a,b); System.out.println("Quiz Mark : " +quiz); System.out.print("Assignment mark: " +assignment); } public int calculateMark( __(5)__ ) { return (a + MIDTEST); } public ___(6)___ calculateMark(int a, int b) { return (a+b); } } i had answered : 1. Course 2. final 3. assignment 4. courseWork 6. void but for no.5 i had try to fill int a, a, quiz, assignment, int quiz, int assignment, int MIDTEST but still can. anybody can help me ?? thanks.
https://www.daniweb.com/programming/software-development/threads/275806/how-to-solve-this
CC-MAIN-2018-39
refinedweb
141
66.13
The quest for C# OpenGL GUI I need a GUI framework for C# that is renderable in an OpenGL context. It needs to be skinnable and have at least the standard GUI controls implemented. It seems easy, but after extensive searching for a week or two, I found nothing. I’m using SFML graphics library. Some candidates: - sfgui: looks promising, but no C# bindings out of the box. Unfinished. - cpGUI: too limited, C++ only. - CEGUI: C++, seems overly complicated. C# port seems dead. - GWEN: stumbled upon it by accident while browsing SFML forums. C++, small but have lots of features, skinnable. Written by Garry Newman. 😉 There might’ve been others, but you can see the trend – no usable C# ports. C++ is tricky when it comes to interop with C#, normal P/Invoke is not able to bind to C++ classes from DLL. I didn’t try to achieve such integration before, but GWEN looks too good not to try (and C++ examples work at least). So I googled about C++/C# interop and basically found two options: - Creating C++/CLI managed proxy that will act as a bridge between C# and C++ (MSDN explanation). I’ve never touched C++/CLI and would prefer to not need to. - Using SWIG. SWIG is supposed to be able to parse C++ code semantically and create wrappers for various languages. It sounds almost too good to be true… and it is. Documentation for it is massive. It has problems with custom operators and same-named identifiers in different namespaces. After spending most of today trying to get it work, I gave up. So, what we have left? Nothing? No! We can always rewrite the whole thing in C#! Crazy, you say? Not so much I think. GWEN is really not a big project and it’s written in very clean C++ from what I can tell. Rendering portion is neatly abstracted, it even has a separate SFML renderer. I’d rather not “waste time” on GUI library, but if I manage to do that it will be great for the community. We’ll see… Edit: get it here: GWEN.NetC#, code, GUI
http://omeg.pl/blog/2011/07/the-quest-for-c-opengl-gui/
CC-MAIN-2020-50
refinedweb
359
76.72
Question: I am building an ASP.NET web service that will be used internally in my company. Exception and trace/audit logging will be performed by the web service class as well as the business objects that the web service will call. The logging is handled by an instance of an internally developed log helper class. The log helper must be an instance as it tracks state and a reference guid that is used to relate the log messages into groups. In the past we handled this situation by passing references to the log helper instance from class to class using the method parameters. I am trying to find a reliable way to find a way to store and access the instance throughout the call without having to explicitly pass it around. I am attempting to store the instance in the HTTPContext during the early stages of the web service call. When my business objects need it later during the call, they will access it as a property of a base class that all my objects inherit from. Initially I tried storing the instance in the web service's Context.Cache. This seemed to work and my research led me to believe that the Cache would be thread safe. It wasn't until I started calling the web service from more than 3 concurrent sessions that the instance of the logger would be shared from call to call rather than be recreated new for each call. I tried Context.Application and found very similar results to the Cache storage. I was able to find what looks like a usable solution with Context.Session. This requires me to use EnableSession = true in the attributes of each method but it does seem to keep the instance unique per call. I do not have a need to track data between calls so I am not storing session cookies in the client space. Is session the optimal storage point for my needs? It seems a little heavy given that I don't need to track session between calls. I'm open to suggestions or criticism. I'm sure someone will suggest using the built in Trace logging or systems like Elmah. Those might be an option for the future but right now I don't have the time required to go down that path. Update: I should clarify that this service will need to run on .Net Framework 2.0. We are in the process of moving to 3.5/4.0 but our current production server is Win2000 with a max of 2.0. Solution:1 I take it that, in the past, you have used these business objects in a Windows Forms application? You should not have your business objects dependent on some ambient object. Instead, you should use either constructor injection or property injection to pass the logger object to the business objects. The logger should be represented by an interface, not by a concrete class. The business objects should be passed a reference to some class that implements this interface. They should never know where this object is stored. This will enable you to test the business objects outside of the web service. You can then store the logging object wherever you like. I'd suggest storing it in HttpContext.Current.Items, which is only valid for the current request. public interface ILogger { void Log(string message); } public class Logger : ILogger { public void Log(string message) {} } public class BusinessObjectBase { public BusinessObjectbase(ILogger logger) { Logger = logger; } protected ILogger Logger {get;set;} } public class BusinessObject : BusinessObjectBase { public void DoSomething() { Logger.Log("Doing something"); } } Solution:2 You could try using OperationContext.Current. This will enable you to store variables for the lifetime of the web service call. Edited to ad a possible No WCF Solution: Since you don't have WCF, you can create something like thread local storage by creating a static map of thread IDs to your object. Just make sure that you are correctly cleaning up this static map when requests are finished or else the next call that uses that thread will pick up your object. Also, make sure to lock the map when you are accessing it. Solution:3 My understanding is that an ASMX class is instantiated for each call. Therefore, it seems like you could instantiate your log-helper class in the ASMX's constructor, and store it in an instance variable. All processing within the ASMX class would reference that instance variable. In that way, the same log-helper instance would be used throughout the lifecycle of a single webservice call, and would NOT be shared across multiple calls. This would most likely be implemented within a common superclass, from which all your ASMX classes would inherit. Though I guess there's nothing preventing you from implementing it over and over again in every ASMX class, if for some reason you eschew a common superclass. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
https://www.toontricks.com/2019/06/tutorial-how-should-i-store-object-in.html
CC-MAIN-2022-21
refinedweb
840
63.29
Check out these tips and techniques that you can use when attempting to optimize Angular applications. Learn how to use lazy loading, server-side rendering and more. When an application grows from a couple lines of code to several files or folders of code, then every byte or second saved matters. When an application grows to that size, the word “optimization” gets whispered a lot. This is because is application of that size would typically run like a coal-powered train, but users expect a high-speed train. Today we’ll look at some useful techniques to adopt when attempting to optimize Angular applications. These techniques are useful for improving load-time and runtime performance. A very useful technique and one of the most recommended for a majority of web applications, lazy loading is basically load-on-demand. In this technique, some parts of your application are bundled separately from the main bundle, which means those parts load when an action is triggered. For example, you have a component called AboutComponent. This component renders the About page, and the About page isn’t the first thing a user sees when the page is loaded. So the AboutComponent can be bundled separately and loaded only when the user attempts to navigate to the About page. To achieve lazy loading in Angular, lazy modules are used, meaning you can define modules separately from your app’s main module file. Angular naturally builds a separate bundle for each lazy module, so we can instruct Angular to only load the module when the route is requested. This technique improves load-time performance but affects runtime performance in the sense that it might take some time to load the lazy modules depending on the size of the module — that’s why Angular has a useful strategy called PreloadingStrategy. PreloadingStrategy is used for telling the RouterModule how to load a lazy module, and one of the strategies is PreloadAllModules. This loads all the lazy modules in the background after page load to allow quick navigation to the lazied module. Let’s look at an example. You have a feature module called FoodModule to be lazy loaded. The module has a component called FoodTreeComponent and a routing module FoodRoutingModule. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FoodRoutingModule } from './food-routing.module'; import { FoodTreeComponent } from './food-tree/food-tree.component'; @NgModule({ imports: [ CommonModule, FoodRoutingModule ], declarations: [FoodTreeComponent] }) export class FoodModule { } To lazy load the FoodModule component with the PreloadAllModules strategy, register the feature module as a route and include the loading strategy: import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { PreloadAllModules, RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, RouterModule.forRoot([ { path: 'food', loadChildren: './food/food.module#FoodModule' } ], {preloadStrategy: PreloadAllModules} ) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } In your application, Angular runs checks to find out if it should update the state of a component. These checks, called change detection, are run when an event is triggered ( onClick, onSubmit), when an AJAX request is made, and after several other asynchronous operations. Every component created in an Angular application has a change detector associated to it when the application runs. The work of the change detector is re-rendering the component when a value changes in the component. This is all okay when working with a small application — the amount of re-renders will matter little — but in a much bigger application, multiple re-renders will affect performance. Because of Angular’s unidirectional data flow, when an event is triggered, each component from top to bottom will be checked for updates, and when a change is found in a component, its associated change detector will run to re-render the component. Now, this change detection strategy might work well, but it will not scale, simply because this strategy will need to be controlled to work efficiently. Angular, in all its greatness, provides a way to handle change detection in smarter way. To achieve this, you have to adopt immutable objects and use the onPush change detection strategy. Let’s see an example: You have a component named BankUser. This component takes an Input object user, which contains the name and @Component({ selector: 'bank-user', template: ` <h2>{{user.name}}</h2> <p>{{user.email}}</p> ` }) class BankUser { @Input() user; } Now, this component is being rendered by a parent component Bank that updates the name of the user on the click of a button: @Component({ selector: 'the-bank', template: ` <bank-user [user]="bankUser"></bank-user> <button (click)="updateName()">Update Name</button> ` }) class Bank { bankUser = { name: 'Mike Richards', email: 'mike@richards.com', } updateName(){ this.bankUser.name = 'John Peters' } } On the click of that button, Angular will run the change detection cycle to update the name property of the component. This isn’t very performant, so we need to tell Angular to update the BankUser component only if one of the following conditions is met: detectChanges Inputhas been updated This explicitly makes the BankUser component a pure one. Let’s update the BankUser component to enforce these conditions by adding a changeDetection property when defining the component: @Component({ selector: 'bank-user', template: ` <h2>{{ user.name }}</h2> <p>{{ user.email }}</p> `, changeDetection: ChangeDetectionStrategy.OnPush }) export class BankUser { @Input() user; } After making this update, clicking the Update Name button will have no effect on the component unless we also change the format by which we update the name of the bank user. Update the updateName method to look like the snippet below: updateName() { this.bankUser = { ...this.bankUser, name: 'John Peters' }; } Now, clicking the button works because one of the conditions set is met — the Input reference has been updated and is different from the previous one. Rendering lists can affect the performance of an application — huge lists with attached listeners can cause scroll jank, which means your application stutters when users are scrolling through a huge list. Another issue with lists is updating them — adding or removing an item from a long list can cause serious performance issues in Angular applications if we haven’t provided a way for Angular to keep track of each item in the list. Let’s look at it this way: There’s a list of fruits containing 1,000 fruit names being displayed in your application. If you want to add another item to that list, Angular has to recreate the whole DOM node for those items and re-render them. That is 1,001 DOM nodes created and rendered when just one item is added to the list. It gets worse if the list grows to 10,000 or more items. To help Angular handle the list properly, we’ll provide a unique reference for each item contained in the list using the trackBy function. Let’s look at an example: A list of items rendered in a component called FruitsComponent. Let’s see what happens in the DOM when we attempt to add an extra item with and without the trackBy function. @Component({ selector: 'the-fruits', template: ` <ul> <li *{{ fruit.name }}</li> </ul> <button (click)="addFruit()">Add fruit</button> `, }) export class FruitsComponent { fruits = [ { id: 1, name: 'Banana' }, { id: 2, name: 'Apple' }, { id: 3, name: 'Pineapple' }, { id: 4, name: 'Mango' } ]; addFruit() { this.fruits = [ ...this.fruits, { id: 5, name: 'Peach' } ]; } } Without providing a unique reference using trackBy, the elements rendering the fruit list are deleted, recreated and rendered on the click of the Add fruit button. We can make this more performant by including the trackBy function. Update the rendered list to use a trackBy function and also the component to include a method that returns the id of each fruit. @Component({ ... template: ` <ul> <li * {{ fruit.name }} </li> </ul> <button (click)="addFruit()">Add fruit</button> `, }) export class FruitsComponent { fruits = [ ... ]; ... trackUsingId(index, fruit){ return fruit.id; } } After this update, Angular knows to append the new fruit to the end of the list without recreating the rest of the list. Now we know lazy loading your application will save a ton of time on page load due to reduced bundle size and on-demand loading. On top of that, server-side rendering can improve the load time of the initial page of your application significantly. Normally, Angular executes your application directly in the browser and updates the DOM when events are triggered. But using Angular Universal, your application will be generated as a static application in your server and served on request from the browser, reducing load times significantly. Pages of your application can also be pre-generated as HTML files. Another benefit of server-side rendering is SEO performance — since your application will be rendered as HTML files, web crawlers can easily consume the information on the webpage. Server-side rendering supports navigation to other routes using routerLink but is yet to support events. So this technique is useful when looking to serve certain parts on the application at record times before navigating to the full application. Visit this in-depth tutorial by the Angular team on how to get started with server-side rendering using Angular Universal. You may find instances when a component within your component tree re-renders several times within a short span of time due to side effects. This doesn’t help the highly performant cause we’re working towards. In situations like this, you have to jump in and get your hands dirty: you have to prevent your component from re-rendering. Let’s say you have a component that has a property is connected to an observer and this observer’s value changes very often — maybe it’s a list of items that different users of the application are adding to. Rather than letting the component re-render each time a new item is added, we’ll wait and handle updating of the application every six seconds. Look at the example below: In this component, we have a list of fruits, and a new fruit is added every three seconds: @Component({ selector: 'app-root', template: ` <ul> <li * {{ fruit.name }} </li> </ul> <button (click)="addFruit()">Add fruit</button> `, styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor() { setInterval(() => { this.addFruit(); }, 2000); } fruits = [ { id: 1, name: 'Banana' }, { id: 2, name: 'Apple' }, { id: 3, name: 'Pineapple' }, { id: 4, name: 'Mango' } ]; addFruit() { this.fruits = [ ...this.fruits, { id: 5, name: 'Peach' } ]; } trackUsingId(index, fruit) { return fruit.id; } } Now imagine if this component was rendering other components that rendered other components. I’m sure you get the image I’m painting now — this component will mostly update 20 times a minute, and that’s a lot of re-renders in a minute. What we can do here is to detach the component from the change detector associated with it and handle change detection ourselves. Since this component updates 20 times every minute, we’re looking to halve that. We’ll tell the component to check for updates once every six seconds using the ChangeDetectorRef. Let’s update this component now to use this update: @Component({ selector: 'app-root', template: ... }) export class AppComponent implements OnInit, AfterViewInit { constructor(private detector: ChangeDetectorRef) { // ... } fruits = [ // ... ]; // ... ngAfterViewInit() { this.detector.detach(); } ngOnInit() { setInterval(() => { this.detector.detectChanges(); }, 6000); } } What we’ve done now is to detach the ChangeDetector after the initial view is rendered. We detach in the AfterViewInit lifecycle rather than the OnInit lifecycle because we want the ChangeDetector to render the initial state of the fruits array before we detach it. Now in the OnInit lifecycle, we handle change detection ourselves by calling the detectChanges method every six seconds. We can now batch update the component, and this will improve run-time performance of your application radically. We’ve looked at a few ways to optimize an Angular application. A few other notable techniques are: enableProdModeto optimize your build for production. Employing useful optimization techniques no matter how small and irrelevant the results may seem might go a long way to making your application run even more smoothly than it currently is. The CLI by Angular for bootstrapping your application has employed several optimization techniques, so be sure to get started using the CLI. Further optimization to your server will produce better results, so ensure you look out for those techniques. You can include useful techniques that work for your application too. Happy coding. Check out our All Things Angular page that has a wide range of info and pointers to Angular.
https://www.telerik.com/blogs/tips-for-optimizing-your-angular-application
CC-MAIN-2021-49
refinedweb
2,063
52.19
25 August 2011 17:41 [Source: ICIS news] WASHINGTON (ICIS)--A major manufacturers group on Thursday lowered its forecast for ?xml:namespace> In its quarterly economic forecast, the Manufacturers Alliance said it expects For 2012, the alliance forecasts GDP growth of 2.1%, a downgrade from its May outlook predicting a 2.7% expansion. Daniel Meckstroth, chief economist for the alliance, cited the sharply lower economic performance in the In late July the Department of Commerce (DOC) drastically cut its estimate of US GDP for the first quarter, saying that the economy barely expanded at all in the first three months at 0.4%. The department’s initial estimate had been 1.9% GDP growth in the first quarter. In addition, the department said that second quarter GDP growth was only 1.3%, well below the 1.8% pace that many economists had been expecting. The Normal annual GDP growth for the With its outlook for “Overall job growth will be disappointing,” Meckstroth said. Other concerns also impact US economic prospects going forward, he said. “We have already seen a stock market correction, and there could be further reverberations of the “In addition, the political gridlock in solving the long term federal budget deficit lowers confidence in the US, and state and local governments are in an austerity mode,” he added. “Unfortunately, there are relatively few economic drivers that are likely to accelerate over the rest of the year,” Meckstroth said. Manufacturing is among the few bright spots in the However, here too the alliance has lowered its expectations from just three months earlier, when it forecast manufacturing growth of 6.2% this year and 4.2% in
http://www.icis.com/Articles/2011/08/25/9488072/manufacturers-cut-us-growth-rate-forecasts-for-2011-2012.html
CC-MAIN-2015-14
refinedweb
278
53.51
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hi, I want my custom render token to output a path fragment as for example root/name. root/name So, when I have the render path $MyRenderToken/myFile.png, I want it to be resolved to root/name/myFile.png. All my attempts resulted in the path delimters being replaced with the underscore character, resulting in a directory root_name instead of a pair of nested directories root/name. $MyRenderToken/myFile.png root/name/myFile.png root_name Thanks! [edited by @ferdinand]: This is an interesting question which might be relevant for more users, so I took the liberty to make this posting more accesible. Original posting by @Dunhou: , Thanks! , Hello @dunhou, Thank you for reaching out to us. Unfortunately, the answer is no, you cannot escape this. In the backend, the render path handling has a list of special characters (".", " ", "/", "?", "<", ">", "\\", ":", "*", "|", "(" ")") which will be replaced by the underscore character (_). As you can see, this list includes the path delimiters for both Windows and macOS. Among other things, this replacement logic is applied to the output of render token callback functions. There is nothing you can do to prevent this. ".", " ", "/", "?", "<", ">", "\\", ":", "*", "|", "(" ")" _ The only thing I could think of is to implement multiple tokens. So, let's say you want to depict a directory depth of up to 5. You would then have to implment the render tokens $a, $b, $c, $d, and $e and enter a render path as shown below: $a, $b, $c, $d, $e $a/$b/$c/$d/$e/myFile.jpg These tokens would have to analyze the path they are contained in and then output a desired folder structure, e.g., this: a/b/c/d/e/myFile.jpg You should also be able to produce shorter paths by for example let $c and $d return the empty string when some condition x is met. This would formally result in this output: $c $d a/b///e/myFile.jpg which is equivalent to a/b/e/myFile.jpg Cheers, Ferdinand @ferdinand Thanks for your repley. My personal solution is also use multiple custom tokens, but it is a bit painful QAQ. I have to reg multiple tokens and define a string include token symol by a command buttom script. A little annoying problem-.- but better than input by hand Thanks for your help @ferdinand I try to return a empty string when project name don't have a delimiter like _vstring , but in output path doesn't work anymore. This token just as a string in output: C4D File name : token.c4d / token_v2.c4d MyToken : $root/$rprj(real prj name with out _v[version])/$vn(version name)/$rprj expect path A :token_v2.c4d > $root/token/v2/token.png expect path Btoken.c4d > $root/token/token.png but when there is no version in prj name[B], It's output like this: token.c4d > $root/token/$vn[just the token symbol as str]/token.png And this is the $vnpart code : _v token.c4d / token_v2.c4d $root/$rprj(real prj name with out _v[version])/$vn(version name)/$rprj token_v2.c4d > $root/token/v2/token.png token.c4d > $root/token/token.png token.c4d > $root/token/$vn[just the token symbol as str]/token.png $vn import os import c4d import re delimiter = "_v" # Get version number def GetVersion(filePath): versionList = re.findall(delimiter+"\d+",filePath) if len(versionList) == 0: # If no versions found return None, None rawVersion = re.compile(delimiter).split(versionList[len(versionList)-1])[1] # [string] version = int(rawVersion) # [integer] return version, rawVersion # Thoken : Project Version Name with _v ($vn) def GetProjectVersionName(data): # _v2 prjName = data[0].GetDocumentName() ver = GetVersion(prjName)[1] # rawVersion [string] if ver == None: # if prj name have no delimiter component verStr = "" return verStr # null string else: verStr = delimiter + ver return verStr # _v2 if __name__=="__main__": for registeredToken in c4d.modules.tokensystem.GetAllTokenEntries(): if registeredToken.get("_token") in ["root", "rprj", "vn"]: exit() c4d.plugins.RegisterToken("vn", "DH Project Version Name", "v001", GetProjectVersionName) Is there something wrong,please help me out. Thank you Hey @dunhou, Your code is fine, my suggestion simply does not work. I suggested it because I could have sworn this worked before and we show something similar with returning an empty string in the C++ Docs for the TOKENHOOK documentation. Not sure what happened there, if this was always intended to work like this, or if this is a regression. The render token functionality is however not that old, so it likely is intended. The culprit is this: // #entry is here a render token String search = String("$" + entry.GetKey()); String value = CheckSpacialStrings(entry.GetValue()->GetString(const_cast<void*>(data))); if (value.IsPopulated()) { // The replacement of the token is prepared here ... } So, when your token returns the empty string, it simply does not carry out the replacement. I am sorry that I have send you into the wrong direction. There is not really much left you can do, apart from ignoring the render token system altogether and implement this from scratch on your own. @ferdinand It's so sad , I'll try a script to define some output path token presets. Hope it can work as expect. Thanks for your answer
https://plugincafe.maxon.net/topic/14078/can-a-render-token-contain-special-characters
CC-MAIN-2022-27
refinedweb
900
57.98
haraka-resultsharaka-results Add, log, retrieve, and share the results of plugin tests. SynopsisSynopsis Results is a structured way of storing results from plugins across a session, allowing those results to be retrieved later or by other plugins. UsageUsage Use results in your plugins like so: exports.my_first_hook = function (next, connection) { let plugin = this; // run a test ...... // store the results connection.results.add(plugin, {pass: 'my great test' }); // run another test ..... // store the results connection.results.add(plugin, {fail: 'gotcha!', msg: 'show this'}); } Store the results in the transaction (vs connection): connection.transaction.results.add(plugin, {...}); Config optionsConfig options Each plugin can have custom settings in results.ini to control results logging. There are three options available: hide, order, and debug. hide - a comma separated list of results to hide from the output order - a comman separated list, specifing the order of items in the output debug - log debug messages every time results are called ;put this in config/results.ini [plugin_name] hide=skip order=msg,pass,fail debug=0 Results FunctionsResults Functions addadd Store information. Most calls to results will append data to the lists in the connection. The following lists are available: pass - names of tests that passed fail - names of tests that failed skip - names of tests that were skipped (with a why, if you wish) err - error messages encountered during processing msg - arbitratry messages human - a custom summary to return (bypass collate) emit - log an INFO summary When err results are received, a logerror is automatically emitted, saving the need to specify {emit: true} with the request. Examples: var c = connection; c.results.add(plugin, {pass: 'null_sender'}); c.results.add(plugin, {fail: 'single_recipient'}); c.results.add(plugin, {skip: 'valid_bounce'}; c.results.add(plugin, {err: 'timed out looking in couch cushions'}); c.results.add(plugin, {msg: 'I found a nickel!', emit: true}); In addition to appending values to the predefined lists, arbitrary results can be stored in the cache: results.add(plugin, {my_result: 'anything I want'}); When arbirary values are stored, they are listed first in the log output. Their display can be suppressed with the hide option in results.ini. incrincr Increment counters. The argument to incr is an object with counter names and increment values. Examples: var c = connection; c.results.incr(plugin, {unrecognized_commands: 1}); c.results.incr(plugin, {karma: -1}); c.results.incr(plugin, {karma: 2}); pushpush Append items onto arrays. The argument to push is an object with array names and the new value to be appended to the array. Examples: var c = connection; c.results.push(plugin, {dns_recs: 'name1'}); c.results.push(plugin, {dns_recs: 'name2'}); collatecollate var summary = connection.results.collate(plugin); Formats the contents of the result cache and returns them. This function is called internally by add() after each update. getget Retrieve the stored results as an object. The only argument is the name of the plugin whose results are desired. var geoip = connection.results.get('geoip'); if (geoip && geoip.distance && geoip.distance > 2000) { .... } Keep in mind that plugins also store results in the transaction. Example: var sa = connection.transaction.results.get('spamassassin'); if (sa && sa.score > 5) { .... } hashas Check result contents for string or pattern matches. Syntax: results.has('plugin_name', 'result_name', 'search_term'); result_name: the name of an array or string in the result object search_term: a string or RegExp object Store Results: var r = connection.results; r.add(plugin, {pass: 'some_test'}); r.add(plugin, {pass: 'some_test(with reason)'}); Retrieve exact match with get: if (r.get('plugin_name').pass.indexOf('some_test') !== -1) { // some_test passed (1x) }; Same thing with has (retrieve a string match): if (r.has('plugin_name', 'pass', 'some_test')) { // some_test passed (1x) } The syntax for using has is a little more pleasant. Both options require one to check for each reason which is unpleasant when and all we really want to know is if some_test passed or not. To retrieve a matching pattern: if (r.has('plugin_name', 'pass', /^some_test/)) { // some_test passed (2x) } Private ResultsPrivate Results To store structured data in results that are hidden from the human and human_html output, prefix the name of the key with an underscore. Example: connectionresults; Redis Pub/SubRedis Pub/Sub If a redis client is found on server.notes.redis, then new results are JSON encoded and published to Redis on the channel named result-${UUID}. This feature can be disabled by setting [main]redis_publish=false in results.ini. Plugins can recieve the events by psubscribing (pattern subscribe) to the channel named result-${UUID}* where ${UUID} is the connection UUID. This snippet is from the karma plugin, subscribing on the connect_init hook. exports {this;}exports {var plugin = this;plugin;} It's also wise to unsubscribe. It's easy to do on the disconnect hook: exports {this;}
https://www.npmjs.com/package/haraka-results
CC-MAIN-2021-39
refinedweb
782
51.44
peewee 0.9.8 a little orm peewee - a small orm - written in python - provides a lightweight querying interface over sql - uses sql concepts when querying, like joins and where clauses - supports sqlite, mysql and postgresql For flask integration, including an admin interface and RESTful API, check out flask-peewee. Examples: # a simple query selecting a user User.get(username='charles') # get the staff and super users editors = User.select().where(Q(is_staff=True) | Q(is_superuser=True)) # get tweets by editors Tweet.select().where(user__in=editors) # how many active users are there? User.select().where(active=True).count() # paginate the user table and show me page 3 (users 41-60) User.select().order_by(('username', 'asc')).paginate(3, 20) # order users by number of tweets User.select().annotate(Tweet).order_by(('count', 'desc')) # another way of expressing the same User.select({ User: ['*'], Tweet: [Count('id', 'count')] }).group_by('id').join(Tweet).order_by(('count', 'desc')) You can use django-style syntax to create select queries: # how many active users are there? User.filter(active=True).count() # get tweets by a specific user Tweet.filter(user__username='charlie') # get tweets by editors Tweet.filter(Q(user__is_staff=True) | Q(user__is_superuser=True)) You can use python operators to create select queries: # how many active users are there? User.select().where(User.active == True).count() # get me all users in their thirties User.select().where((User.age >= 30) & (User.age < 40)) # get me tweets from today by active users Tweet.select().join(User).where( (Tweet.pub_date >= today) & (User.active == True) ) Learning more check the documentation for more examples. specific question? come hang out in the #peewee channel on freenode.irc.net, or post to the mailing list, lastly, peewee runs on python 2.5 or greater, though there is currently no support for python3 Why? peewee began when I was working on a small app in flask and found myself writing lots of queries and wanting a very simple abstraction on top of the sql. I had so much fun working on it that I kept adding features. My goal has always been, though, to keep the implementation incredibly simple. I’ve made a couple dives into django’s orm but have never come away with a deep understanding of its implementation. peewee is small enough that its my hope anyone with an interest in orms will be able to understand the code without too much trouble. model definitions and schema creation smells like django: import peewee class Blog(peewee.Model): title = peewee.CharField() def __unicode__(self): return self.title class Entry(peewee.Model): title = peewee.CharField(max_length=50) content = peewee.TextField() pub_date = peewee.DateTimeField() blog = peewee.ForeignKeyField(Blog) def __unicode__(self): return '%s: %s' % (self.blog.title, self.title) gotta connect: >>> from peewee import database >>> database.connect() create some tables: >>> Blog.create_table() >>> Entry.create_table() foreign keys work like django’s >>> b = Blog(title="Peewee's Big Adventure") >>> b.save() >>> e = Entry(title="Greatest movie ever?", content="YES!", blog=b) >>> e.save() >>> e.blog <Blog: Peewee's Big Adventure> >>> for e in b.entry_set: ... print e.title ... Greatest movie ever? querying queries come in 4 flavors (select/update/insert/delete). there’s the notion of a query context which is the model being selected or joined on: User.select().where(active=True).order_by(('username', 'asc')) since User is the model being selected, the where clause and the order_by will pertain to attributes on the User model. User is the current query context when the .where() and .order_by() are evaluated. an example using joins: Tweet.select().where(deleted=False).order_by(('pub_date', 'desc')).join( User ).where(active=True) this will select non-deleted tweets from active users. the first .where() and .order_by() occur when Tweet is the current query context. As soon as the join is evaluated, User becomes the query context and so the following where() pertains to the User model. now with q objects for users familiar with django’s orm, I’ve implemented OR queries and complex query nesting using similar notation: User.select().where( Q(is_superuser = True) | Q(is_staff = True) ) SomeModel.select().where( (Q(a='A') | Q(b='B')) & (Q(c='C') | Q(d='D')) ) # generates something like: # SELECT * FROM some_obj # WHERE ((a = "A" OR b = "B") AND (c = "C" OR d = "D")) using sqlite import peewee database = peewee.SqliteDatabase('my.db') class BaseModel(peewee.Model): class Meta: database = database class Blog(BaseModel): creator = peewee.CharField() name = peewee.CharField() class Entry(BaseModel): creator = peewee.CharField() name = peewee.CharField() using postgresql you can now use postgresql: import peewee database = peewee.PostgresqlDatabase('my_db', user='root') class BaseModel(peewee.Model): class Meta: database = database # ... same as above sqlite example ... using mysql you can now use MySQL: import peewee database = peewee.MySQLDatabase('my_db', user='root') class BaseModel(peewee.Model): class Meta: database = database # ... same as above sqlite example ... - Downloads (All Versions): - 964 downloads in the last day - 5540 downloads in the last week - 26796 downloads in the last month - Author: Charles Leifer - Categories - Package Index Owner: Charles.Leifer - DOAP record: peewee-0.9.8.xml
https://pypi.python.org/pypi/peewee/0.9.8
CC-MAIN-2015-22
refinedweb
834
53.17
Scenario: I have written a post that explains how to create a folder with date by using SSIS Package. You can check here. A reader asked me in comments that if it is possible to move the files to folders according to the date part in the file name. If the folder already exists with date part then the process will not create new folder. In case the folder does not exist and we have the file with new date, the folder will be created and file/s will be moved to that folder. Solution: We will be using For-each loop with Script Task to perform this task. Let's start step by step. Step 1: Create new SSIS Package. Inside SSIS Package created below variables as shown in fig. Fig 1: Create variables in SSIS Package FileName:This variable will save the file name with extension in For-Each Loop and we will use in Script Task. OutputMainFolder:This is the folder in which folders will be created by date part of file name if does not exist. SourceFolder:This is the folder in which our source files exists those need to be moved to different folders according to the date part in file name. Fig 2: Sample Source files with Date Fig 3: Main output folder The main folder already has one folder. Once we will execute the SSIS Package, two more folder should be created and files should be moved to already existing folder and newly created folder. Bring the For-Each Loop Container and configure as shown below. Fig 4: For-Each Loop Container to loop through source files. Fig 5: Map the FileName variable in For-Each Loop Container Step 3: Bring the Script Task and place inside the For-Each Loop Container. Double click on Script Task and add the script as shown below. Fig 6: Place Script Task inside For-Each Loop Container. Double click on Script Task and configure as shown below. Fig 7: Map the variables to Script Task Once you click on Edit Script as shown in #3. Place the below code in Script Task. #region Namespaces using System; using System.Data; using Microsoft.SqlServer.Dts.Runtime; using System.Windows.Forms; using System.IO; #endregion namespace ST_81929bb39573409283a321ba72401cba { [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute] public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { public void Main() { string filename; string datepart; bool FolderExistFlg; filename = Dts.Variables["User::FileName"].Value.ToString(); datepart = (filename.Substring(filename.Length - 12)).Substring(0,8); FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart); if (!FolderExistFlg) { Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart); } File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename, Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart+"\\"+filename); Dts.TaskResult = (int)ScriptResults.Success; } #region ScriptResults declaration enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; #endregion } } using System.IO; is the line that I added and the code added in public void Main(). The rest is auto generated. You can copy that and paste in your Editor. Save the code and then close the window. Let's run our SSIS Package and see if folders are created and files are moved to required folders. Fig 8: Output folders with moved files As we can see that new folders are created if not exist and files according to the date part are moved to the related folder.
http://www.techbrothersit.com/2014/12/ssis-how-to-move-files-to-difference.html
CC-MAIN-2017-04
refinedweb
568
60.21
Image processing optimization techniques This article explains how to optimize image processing using mathematical techniques and Intrinsics ARM NEON instructions. Nokia Original Imaging Effect Wiki Challenge (02 Jul 2014): The winner of segment two of the Nokia Original Imaging Effect Wiki Challenge is venu238 for his article Clip Image Filter Effect. Nice work, Venu. Note: This was an entry in the Nokia Imaging and Big UI Wiki Competition 2013Q4. Windows Phone 8 Introduction This article explains how to speed up computationally expensive operations when using the Nokia Imaging SDK. By using math optimization techniques and SIMD instructions in C++, you can boost your application's performance by a factor of up to 16x. For the purposes of illustration, on a Snapdragon™ S4 in my HDR I - Implementing High Dynamic Range filters using Nokia Imaging SDK project, to process and blend three shots, I saved more than 3 seconds compared to the C# not optimized version. The Nokia Imaging SDK is highly optimized in C++. Although using C++ remains the best way to increase performance, it isn't always feasible. For image processing, C# works fine in most cases. The techniques presented in this article can be used in both C++ and C#. This article explains how to: - use Magic Numbers to speed up division - use Fast Square Root to speed up sqrt - use SIMD intrinsics ARM NEON instructions for image processing Speeding up Division with Magic Numbers In image processing, division is one of the most used mathematical operations. Unfortunately it is also one of most expensive operations, and thus is often the cause of performance failure. This is why it's important to optimize division operations. To do this, we'll take use Magic Numbers to take advantage of two facts: - CPUs perform bit-shift operations much faster than other operations - Multiplication is faster than division You can perform division by multiplying by certain magic numbers and right-shifting by certain const bits. To some extent, you sacrifice accuracy with this approach. Division performed in this way will not have the same accuracy as divisions performed with floats, as is more commonly the case. This could be a problem in scientific calculations where an accuracy of 0.0000000001 can, in some cases, make a difference. For image processing, even if the result of our division is 34 instead of 35.02378 ( that would be rounded to 35 anyway), this loss of accuracy is not a problem at all compared to the benefits. Division by 3 Division by 3 is a common operation in image processing. For example, you use it to calculate the RGB average ((R+G+B)/3). To divide by 3 we will use the following values: - magic number - 0xAAAB - right shift - 17 Let's say we need to compute the average of the RGB values (137,78,246). Using normal division, the result will be ((137 + 78 + 246 ) / 3) = ( 461 / 3 ) = 153. Using magic numbers, the result will be (( 461 * 0xAAAB ) >> 17) = ((461*43691)>>17) = ( 20141551 >> 17 ) = 153. For ease of use, the magic number operation can be put inside a MACRO. Of course, for a few operations, you will not be able to see differences compared to standard division. However, once you see the effect multiplied by the millions of pixels there are in a image, you will start to see a definite improvement. 0xAAAB is not the only magic number that can be used to divide by three. It is the smallest one that results in very good accuracy. However, you should use a smaller number in some circumstances; for example, when using SIMD ARM NEON instructions, to be sure to stay inside the register's size. In this case you can use the following values: - magic number - 0x55 - right shift - 8 These numbers are easier to use, but result in lower accuracy. Using normal division, the result will be 30 / 3 = 10. Using magic numbers, the result will be ((30*0x55)>8) = ((30*85)>8) = 9. In some circumstances such a gap is unacceptable, but in my opinion, in a pixel context, there is no difference between 9 and 10. It's up to you to decide which magic number is more suitable; the bigger, but more accurate 0xAAAB, or the smaller, but not so accurate 0x55. Division by multiples of 2 To divide by 2 you don't need any magic numbers. You simply right-shift your value by 1. Using normal division: (255/2) = 127 Right-shifting values: ( 255 >> 1 ) = 127 Each time you shift by 1 you perform a division by 2. So if, for example, you want to divide by 4, perform a shift by 2: Using normal division: (255 / 4) = 63 Right-shifting values: (255 >>2 ) = 63 And so on. These are the operations I found most useful, but there are many others explained on the web. Speeding up sqrt with Fast Square Root Another operation always present in computer graphics is the square root ( sqrt in C++ ). As you probably know, sqrt is a very expensive operation. Let's see how to improve it. Assuming that the float is in the [IEEE 754 single precision floating point format, we will treat it as an int, leveraging the bit organization. To understand the math behind this solution, you can read Fast Inversion Square Root. right-shift iterations you want to increase the accuracy, but of course the accuracy will lead to lower performance. Another method is not based on reciprocal and magic numbers, but the approach is very similar. This approach is based on the implementation of the following formula: ((((val_int / 2^m) - b) / 2) + b) * 2^m = ((val_int - 2^m) / 2) + ((b + 1) / 2) * 2^m) where b is the exponent bias and m the number of mantissa bits. Here the code that implements performance. The first method is more accurate but less performant. The second method is less accurate and offers better performance. Which one you choose depends on how many operations you need to perform. The difference between both methods is not so great, and both bring dramatic performance improvements. In my opinion, if your algorithm needs to perform millions of square root operations, it is reasonable to sacrifice accuracy and use the second method. In my opinion these solutions are simply awesome! The dark math world sometimes produces miracles. The small loss in accuracy is worth all benefits in performance gains. In the end, it's up to you whether to use these mathematical techniques in your application. Using ARM Advanced SIMD (NEON) ARM NEON Instrinsics is a Single Instruction, Multiple Data (SIMD) instruction set. It speeds processing by performing a single set of instructions in parallel over multiple devices. It is commonly used for audio, video and graphics applications. The Advanced SIMD NEON extension is a combined 64- and 128-bit SIMD instruction set that provides standardized acceleration for media and signal processing applications like to execute MP3 audio decoding, GSM adaptive multi-rate (AMR) speech codec.. We will explain how to use the most common ARM NEON instructions for image processing, such as for interleaving, multiply-accumulator and bit-shifting. We will also give some examples that demonstrate how to combine these techniques to solve common problems. Using ARM NEON memcpy memcpy is one of my favourite, and, in my opinion, most useful functions can be optimized in ARM NEON. Think of image processing and moving data from one buffer to another more than once. The standard resolution starts from 5 milion pixels that in the ARRGB (or BGRA) means 20 million bytes of raw data to move each time! Now that you understand the amount of data we are talking about, think about how many pixels are present in high resolution images. This gives you an idea of the millions of byte we are moving. Using 128-bit ARM NEON registers, which can process 16 bytes at once, we can speed up this process up to 16x, depending on whether the size of the array we want to move is 16-aligned or, better yet, an exact multiple of 16. Let's start working with ARM NEON by importing the library with the following code: #if defined(_M_ARM) #include <arm_neon.h> #endif The following function works with ARM NEON to copy data in as many 16-byte vectors as possible, then copies the remainder with the standard function. As said before, the best performance results when the data length is an exact multiple of 16, as we can leverage ARM NEON for the entire length. void ARM::memcpy(void* Dest, void* Source, int length) { // Divide by 16 to find the limits of the array that can be managed by ARM NEON int arm_length = length / 16; uint8 * src = (uint8 *) Source; uint8 * dest = (uint8 *) Dest; // Declare a vector capable of 16 unsigned bytes uint8x16_t buffer; for( int i = 0 ; i < arm_length; i++ ) { // Load a single vector from memory buffer= vld1q_u8(src); // Store a single vector into memory vst1q_u8(dest, buffer); // We moved 16 bytes so do not increment just one byte as usual but 16 src +=16; dest +=16; // Prefetch the next data __prefetch(src); } // Copy the rest of data with standard function int gap = length - (arm_length*16); if(gap > 0 ) memcpy((byte*) Dest+arm_length, (byte*)Source+arm_length, gap); } - uint8x16_t vld1q_u8(__transfersize(16) uint8_t const * ptr); Load a single vector from memory - void vst1q_u8(__transfersize(16) uint8_t * ptr, uint8x16_t val); Store a single vector into memory Converting to grayscale This operation can be done easily using the Imaging SDK. We are using it as a starting point for explaining how to create the code for your own filter. We will use the approach of fast division we explained before, working with multiplication and shifting. For a better grayscale conversion we should avoid performing the average of three color components, (( R+ G + B ) / 3), and instead use an operation like this: - GrayLevel = (R*0.30 + g*0.59 + b*0.10); Even in C++ this simple operation could be straining, so we proceed with the fast division method. In our case the approximate values are given by: - 0.30 by 77/255 - 0.59 by 151/255 - 0.10 by 20/255 To perform this operation we introduce the Multiply–accumulate operation, a common step that computes the product of two numbers. It then adds that product to an accumulator; a register in which intermediate arithmetic and logic results are stored. Another very important feature introduced by the SIMD ARM NEON instruction set for image processing is interleaving. Assuming we are working with images using the ARGB color model, this means that looking at the byte in sequence, the first byte is the Alpha channel, the second Red, the third Green, the fourth Blue, the fifth again the Alpha channel, but of the second pixel, and so on. Interleaving operations vld4_u8 translate each channel on the same line in a single register, while de-interleaving vst4_u8 does the inverse restoring operation. This step is useful for perform operation like multiply each channel by a constant, 8 bytes at once. You use it as follows: - uint8x8_t vdup_n_u8(uint8_t value); Loads all lanes of vector to the same literal value - uint8x8x4_t vld4_u8(__transfersize(32) uint8_t const * ptr); Loads N-element structure from memory where in that case struct uint8x8x4_t { uint8x8x4_t val[4]; }; Imagine you have an RGB buffer like this: Interleaving data using vld4_u8 we get a vector structure like this: Performing the multiply-accumulate operation, and finally, right-shifting by 8 bits, we implement fast division. The last step is to copy the gray value to each of three former R,G,B channels and then perform de-interleaving. void Utilities::ConvertToGrayNeon( unsigned char* inputBuffer, unsigned char* outputBuffer, int length) { uint8 * src = (uint8 *) inputBuffer; uint8 * dest = (uint8 *) outputBuffer; int n = length; // Copy the const value of 77 for each of eight entries of vector dedicated to red channel uint8x8_t rfac = vdup_n_u8 (77); // Copy the const value of 151 for each of eight entries of vector dedicated to green channel uint8x8_t gfac = vdup_n_u8 (151); // Copy the const value of 28 for each of eight entries of vector dedicated to blue channel uint8x8_t bfac = vdup_n_u8 (28); // Calculate the new array length based on the fact we are processing eight bytes at once, so dividing by 8 n/=8; // Assign the default value to Alpha channel uint8x8x4_t interleaved; interleaved.val[0] = vdup_n_u8 (0xFF); //Alpha value for (int i=0; i < n; i++) { uint16x8_t temp; // Copy and interleave uint8x8x4_t rgb = vld4_u8 (src); // Multiply the red value by the const value 77 temp = vmull_u8 (rgb.val[1], rfac); // Multiply the green values by const value of 151 and add the result to previous temp = vmlal_u8 (temp,rgb.val[2], gfac); // Multiply the blue values by const value of 20 and add the result to previous temp = vmlal_u8 (temp,rgb.val[3], bfac); // Right-shift all values by 8, performing a division by 255 interleaved.val[1] = vshrn_n_u16 (temp, 8); // Since this is a gray scale value it can be copied to all remaining two (green and blue) interleaved.val[2] = interleaved.val[0]; interleaved.val[3] = interleaved.val[0]; // De-interleave the result vst4_u8 (dest, interleaved); // Move the pointer forward src += 8*4; dest += 8*4; } } - uint16x8_t vmull_u8(uint8x8_t a, uint8x8_t b); vector long multiply - uint16x8_t vmlal_u8(uint16x8_t a, uint8x8_t b, uint8x8_t c); vector multiply accumulate long: vmlal_<type>. Vr[i] := Va[i] + Vb[i] * Vc[i] - uint8x8_t vshrn_n_u16(uint16x8_t a, __constrange(1,8) int b); vector narrowing shift right by constant - void vst4_u8(__transfersize(32) uint8_t * ptr, uint8x8x4_t val); store N-element structure to memory Blending images The HDR::BlendArmNeon method for my project HDR I - Implementing High Dynamic Range filters using Nokia Imaging SDK is built on the two ARM functions we just discussed: using memcpy and converting to grayscale. It takes as input the raw camera buffer of unsigned char*. It assumes that it is working with anNV12 color model. The code that converts to grayscale takes as input a Buffer object. Ideally you would work with IBuffer but this doesn't change the nature of the function, you should just use a different conversion function from AsBuffer to FromIBuffer, both returning a unsigned char* that are referenced in the Nokia Imaging SDK in native code article. This portion of code that handles the Luminance information performs the blending as ((y1+y2+y3)/3). Division by 3 is performed using the magic number 0x55. All ARM instructions are already described but combined a bit differently. The code should be easy to understand. The main difference is that we are working with register that is 16-bit wide, rather than 8-bit as in one of previous examples, so that we can store numbers greater than 255.; } Parallel Processing The native C++ libraries were extended to provide rich support for parallel programming. There are different layers at which users can interact with the parallel runtime. The highest of these layers is the Parallel Patterns Library. It can be accessed using the header file ppl.h. ppl.h contains different constructs that you can use to parallelize your programs without extensive knowledge of scheduling decisions, underlying threads, the surrounding environment, etc. One of the constructs in ppl.h is the parallel_for construct, which is used to quickly parallelize a for-loop. parallel_for takes the body of a for-loop as captured in a function, divides the number of iterations amongst the available computing resources (processors), and executes that work in parallel. Here's a simple example of serial-to-parallel transformation: for (int i = 0; i < n; i++) { iter(); } becomes Concurrency::parallel_for(0, n, [] (int i) { iter(); }); Converting all for-loops in a program into parallel for-loops might have unintended consequences. You can only do this if all iterations of the loop run independently. Suppose, for example, you have the following code: for (int i = 0; i < n; i++) { // Array "a" contains both an original sequence and the end result a[i] += a[i-1]; } In order to compute the kth term in a resulting sequence, the k-1th term must be known. If you were to execute iterations in parallel, it's possible that the k-1th term may not be populated by the time the kth term is processed, yielding an incorrect result. Concurrency::parallel_for(0, n, [] (int i) { a[i] += a[i-1]; // incorrect! }); Consider, also, that creating a for-loop thread has a performance cost. Therefore it is makes sense to parallelize for-loops that process a large amount of data, but may not make sense to parallelize small for-loops. In our example, we parallelize each row of the image. On a dual core device, this means that we are likely processing two rows in parallel. However the final decision on parallelization is left to the scheduler. In my application, running on a Lumia 820 so working with 8MPx images, using parallelization resulted in a net improvement of 1.5 seconds, compared using a standard for-loop. Blending ARGB images; }; Summary This article presented three techniques for speeding up image processing in C++/CX and C#: - Using Magic Numbers to speed up division - Using Fast Square Root to speed up sqrt - Using SIMD intrinsics ARM NEON instructions for image processing Hamishwillee - Some very useful stuff here Hi Sebastiano Thanks very much. I think there is lots of useful information here. What it somewhat lacks is a "narrative" or story Creating and optimizing a custom effect for the Nokia Imaging SDK does this quite well by showing the different affects of all the optimisations for the same filter effect. I'm not sure that exactly the same approach is needed here but it would be good to have an overview graph/table showing some idea of what sort of benefits users can expect. The reason is that most times this stuff is scary, and people need to know when it is a reasonable trade off. I would certainly cross link to that article as it has some ideas you have not explored. Splitting out still seems like it was a very good idea. I think I can do a much better job of reviewing this article now. regardsHamish hamishwillee (talk) 03:45, 19 December 2013 (EET) BuildNokia - Edited for clarity Hi Sebastiano, This was a fun article to read. You've written up some great little tricks for optimizing image processing performance. Since this was a contest winner (congratulations!) and a lot of people will be reading it, I've taken the time to do an in-depth edit for clarity. Can you take a read through it and make sure I didn't break anything? Specifically, can you double-check the "Blending images" section? I had trouble understanding this and am not sure that I correctly interpreted what you were trying to say there. On a related note, your comments on most of the code in this article were very helpful, but it looked like you kind of lost steam there at the end. Understandable; there's a lot of work here! :-) When you get some time, it would be great if you could add comments to the rest of the code. I can read the code and I understand what the various operations are doing but have a hard time seeing how all the operations relate and the big picture of what the entire block of code is doing overall. That goes for all of the rest of the code, starting with the paragraph above, until the end of the article. Thanks for all the hard work you put into this.Jen BuildNokia (talk) 22:05, 2 January 2014 (EET) Galazzo - Hi Jen, I was asking who was this new account "BuildNokia" then reading the sign.. you are Jen :-) Welcome by me, suree is the begin of a great work. For sure I can check your edits, just let me some time. RegardsSebastiano galazzo (talk) 22:17, 2 January 2014 (EET)
http://developer.nokia.com/community/wiki/Image_processing_optimization_techniques
CC-MAIN-2014-23
refinedweb
3,329
59.03
In the previous lesson, we learned about the flow control structure. We learned about the if-else structures and nested if structures. In this lesson, we will learn about another flow control feature – switch-case. If-else Construct Consider a C program for calculator, the user is given a menu with options to choose from. - Add - Subtract - Multiply - Divide We can write a program using if-else construct for the above problem. #include <stdio.h> int main() { int choice; int a,b,c; a = 10; b = 20; printf (“Enter your choice:”); if (choice == 1) c = a+b; if (choice == 2) c = a – b; if (choice == 3) c = a * b; else if(choice == 4) c = a/b; else { printf(“Wrong input, Try again!”); } getch(); return 0; } The user enters a number and it is matched with if-else blocks and whenever there is a match that block is executed. The problem with these kinds of the construct is that when the menu is large, then the if-else construct will be difficult to manage. Also, there are many comparisons – each if a block is tested. Switch-Case The switch-case is suitable for menu driven C programs. Whenever the program is executed, a menu with a number of choices like the example below is presented to the user. /* Calculator Application in C */ Enter your choice: - Add - Subtract - Multiply - Divide The switch block look like the following in program source code. The switch block accepts a number as user choice. When the user enters a number next to an option and the Switch accepts the choice(number). int choice; Switch (choice) { } The switch () matches the user choice with a list of cases. Each of the cases has a number associated with them followed by a colon. Case 2: Statement1; break; Case 3: Statement2; Statement3; break; When the user choice and the case number matches, the statements from the case is executed and terminated by a break; statement. The entire switch-case block look like following int choice; scanf(“%d”,&choice); Switch(choice) { Case 1: Do something; break; Case 2: Do something; break; default: Do something; break; } Let’s create an example program using the Switch-Case. We shall write the Calculator program using the Switch-Case. Flowchart – C Calculator Program Code /* C Program for a Calculator using Switch-Case */ #include <stdio.h> int main() { int choice; int a, b, c; a = 10; b = 20; printf (“Enter your choice:”); scanf (“%d”, &choice); Switch (choice) { case 1: c = a + b; break; case 2: c = a - b; break; case 3: c = a * b; break; case 4: c = a / b; break; default: printf (“Wrong choice, try again!”); break; } printf (“Result = %d\n”, c); getch(); return 0; } Output The output of the program is given below. References - Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,. - Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.!
https://notesformsc.org/c-flow-control-structures-ii/
CC-MAIN-2022-33
refinedweb
481
71.34
And yes, go ahead and bring it up on python-dev. Don't bother with c.l.py unless you are particularly masochistic. --Guido On Thu, Mar 4, 2010 at 7:09 PM, Brian Quinlan <brian at sweetapp.com> wrote: > Wow, timing is everything - I sent Guido an e-mail asking the same thing < > 30 seconds ago :-) > > Cheers, > Brian > > On Mar 5, 2010, at 2:08 PM, Jesse Noller wrote: > >> *mega snip* >> >> Jeffrey/Brian/all - Do you think we are ready to move this to the >> grist mill of python-dev? Or should we hold off until I get off my >> rump and do the concurrent.* namespace PEP? -- --Guido van Rossum (python.org/~guido)
http://mail.python.org/pipermail/stdlib-sig/2010-March/000942.html
CC-MAIN-2013-20
refinedweb
114
82.24
int sum( int a, ... ); sum( 1, 2, 3, -1 ); void va_start( va_list arg_ptr, prev_param //Parameter preceding first optional argument (ANSI only). ); // (ANSI version) sum( 1, 2, 3 ); fabs abs ABuenger wrote:I would like to use the new ribbon which will be introduced in Office 2007 in one of my apps. ABuenger wrote:Maybe others would like to work on a free implementation for Codeproject? PJ Arends wrote:Sounds like a great idea, why don't you go for it? #include "library_1\includes/hA.h" #include "library_1\includes/hB.h" #include "library_1\includes/hC.h" #include "library_1\includes/hD.h" #include "library_2\includes/h1.h" #include "library_2\includes/h2.h" #include "library_2\includes/h3.h" ... hA.h h1.h /// hA.h #include "h1.h" // with the quotes. VS.net compiler cannot find h1.h Gr8Shag wrote:All objects are being deleted after use. Gr8Shag wrote:You guysare amazing. One post and the problem is solved General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/messages/1396343/re-absolute-value.aspx
CC-MAIN-2017-13
refinedweb
185
71.31
In object-oriented programming languages, the classes are the building blocks of any application. If these blocks are not strong, the building (i.e. the application) is going to face a tough time in the future. Poorly designed applications can lead the team to very difficult situations when the application scope goes up, or the implementation faces certain design issues either in production or maintenance. On the other hand, a set of well designed and written classes can speed up the coding process, while reducing the tech debt and the number of bugs in comparison. In this tutorial, We will learn the SOLID principles which are 5 most recommended design principles, that we should keep in mind while writing our classes. Table Of Contents What are SOLID Principles Single Responsibility Principle Open Closed Principle Liskov's Substitution Principle Interface Segregation Principle Dependency Inversion Principle Introduction to SOLID Principles SOLID is the acronym for a set of practices that, when implemented together, makes the code more adaptive to change. Bob Martin and Micah Martin introduced these concepts in their book ‘Agile Principles, Patterns, and Practices’. The acronym was meant to help us remember these principles easily. These principles also form a vocabulary we can use while discussing with other team members or as a part of technical documentation shared in the community. SOLID principles form the fundamental guidelines for building object-oriented applications that are robust, extensible, and maintainable. Single Responsibility Principle We may come across one of the principles of object-oriented design, Separation of Concerns (SoC), that conveys a similar idea. The name of the SRP says it all: “One class should have one and only one responsibility” In other words, we should write, change, and maintain a class only for one purpose. A class is like a container. We can add any amount of data, fields, and methods into it. However, if we try to achieve too much through a single class, soon that class will become bulky. If we follow SRP, the classes will become compact and neat where each class is responsible for a single problem, task, or concern. For example, if a given class is a model class then it should strictly represent only one actor/entity in the application. This kind of design decision will give us the flexibility to make changes in the class, in future without worrying the impacts of changes in other classes. Similarly, If we are writing service/manager class then the class should contain only that part of methods and nothing else. The service class should not contain even utility global functions related to the module. Better to separate the global functions in another globally accessible class. This will help in maintaining the class for that particular purpose, and we can decide the visibility of class to a specific module only. Example We can find plenty of classes in all popular Java libraries which follow single responsibility principle. For example, in Log4j the Person class, and so on. In the given example, we have two classes Person and Account. Both have single responsibility to store their specific information. If we want to change the; } Open Closed Principle OCP is the second principle which we should keep in mind while designing our application. It states: “Software components should be open for extension, but closed for modification” It means that the application classes should be designed in such a way that whenever fellow developers want to change the flow of control in specific conditions in application, all they need to extend the class and override some functions and that’s it. If other developers are not able to write the desired behavior due to constraints put by the class, then we should reconsider refactoring the class. I do not mean here that anybody can change the whole logic of the class, but one should be able to override the options provided by software in a non harmful way permitted by the software. a front controller for String based web applications. To use this class, we are not required to modify this class. All we need is to pass initialization parameters and we can extend its } } Liskov’s Substitution Principle LSP is a variation of previously discussed open closed principle. It says: “Derived types must be completely substitutable for their base types” LSP means that the classes, fellow developers created by extending our class, should be able to fit in application without failure. This is important when we resort to polymorphic behavior through inheritance. This requires the objects of the subclasses to behave in the same way as the objects of the superclass. This is mostly seen in places where we do runtime type identification and then cast it to appropriate reference type. if any class extends PropertyEditorSupport class, then it can be substituted by everywhere the base class is required. For example, every book has an ISBN number which is always in ""; } } } Interface Segregation Principle This principle is my favorite one. ISP is applicable to interfaces as a single responsibility principle holds to classes. ISP says: “Clients should not be forced to implement unnecessary methods which they will not use” Take an example. Developer Alex created an interface Reportable and added two methods generateExcel() and generatedPdf(). Now client ‘A’ wants to use this interface but he intends to use reports only in PDF format and not in excel. Will he be able to use the functionality easily? NO. He will have to implement both the methods, out of which one is an extra burden put on him by the designer of users to use only the required functionality only. a corresponding listener and implement it. public class MouseMotionListenerImpl implements MouseMotionListener { @Override public void mouseDragged(MouseEvent e) { //handler code } @Override public void mouseMoved(MouseEvent e) { //handler code } }. Example The classical use of this principle of bean configuration in Spring framework. In the spring framework, all modules are provided as separate components which can work together by simply injecting dependencies in other modules. This dependency is managed externally in XML files. These separate components are so well closed in their boundaries that we can use them in other software modules apart from spring with the same ease. This has been achieved by dependency inversion and open closed principles. All modules expose only abstraction which is useful in extending the functionality or plug-in in another module. These were 5 class design principles, also known as SOLID principles, which makes the best practices to be followed to design our application classes. Happy Learning !! Feedback, Discussion and Comments Pankaj Sharma. Nesree Fawzy C can replace A and B. This is the concept. Sarah Zheng Lokesh Gupta I do not see any violation here. sandeep Just a suggestion why can’t you use factory pattern instead of abstract class if possible as per solid design pattern i don’t see any problem but use of abstract classes should be avoided Shakunthala Thank you for the simple explanation with necessary points to understand the concept. Mukesh Sharma Would suggest try to have some uml diagram along with pictorial representation . Also some code examples as well. well explained here with examples . Siddharth Singh Noreply Talk about something you do everyday, otherwise just read and leave the place instead of criticising. Sarah Zheng I think the rules Siddharth Singh mentioned like software designing result. The SOLID principles more like methods or some lessons can lead us to the result. Abhash HI Lokesh, in the summary image (), there is a spelling mistake under What is says. “Reasonability” should be replaced by “responsibility” Prakash K. Devendra Gohey Nice write-up, need more detailed on Open & Closed principle. Varun Vats. Linh Nguyen That ‘s really useful. Great works! Kiran Kumar Awesome explanation! Nilesh Kathoke You done great job Lokesh !!! Please take a look : Pratap Shinde Good job. Would be great if each had a brief scenario/example vijay Jayaram Hi Lokesh Gupta, This is a good read no doubt! however, shouldn’t we mention UncleBob for S.O.L.I.D. Regards, Vijay Jayaram Lokesh Gupta I have never heard of him. Did he originally wrote these principles? vinodh sarcasm Rishi I think No. these are 5 SOLID principals used or taking care during software designing. Deepak Please, Explain with example … dilani vivid clear description..thank you 🙂 st . Lokesh Gupta oops, typo. Corrected. It is “can not change their core logic”. Thanks for bringing into notice. st Thanks for the quick reply! Keep up the great work. Cheers! naseer nice post.. can you please explain with some real world examples.. Amrita nice post Jueser I agree i need a some examples to understand very well, I little bit confused with some principles.but thank you so much! Shamra I think OCP is explained wrong would be more clear with example code. Lokesh Gupta Which sentence you think is wrong? I will try to explain in more detail. kk Thank you it helps great!! Sumeet Singh Good stuff… can you also explain Dependency Injection in detail? mbudur Good one! Bhaskar Thanks !! for sharing great stuff.. praveen If some sample code are there it will be more beneficial and easy to understand. eminkirac6emin This one is good for guide, but this article more useful with sample codes nadeem It would be better, if you give small examples with SOLID.
https://howtodoinjava.com/best-practices/solid-principles/
CC-MAIN-2021-04
refinedweb
1,555
55.74
pcap_next_ex(3) pcap_next_ex(3) NAME pcap_next_ex, pcap_next - read the next packet from a pcap_t SYNOPSIS #include <pcap/pcap.h> pcap_next_ex(3) *p, struct pcap_pkthdr **pkt_header, const u_char **pkt_data); const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h); DESCRIPTION pcap_next_ex(3). The struct pcap_pkthdr and the packet data are not to be freed by the caller, and are not guaranteed to be valid after the next call to pcap_next_ex(3), pcap_next(), pcap_loop(), or pcap_dispatch(); if the code needs them to remain valid, it must make a copy of them.(3),() routine when handed the pcap_t value also passed to pcap_loop()_next_ex(3) returns 1 if the packet was read without problems, 0 if packets are being read from a live capture and the packet buffer time- out ``savefile.'' Unfor- tunately, there is no way to determine whether an error occurred or not. SEE ALSO pcap(3), pcap_geterr(3), pcap_dispatch(3), pcap_datalink(3) 20 January 2017 pcap_next_ex(3) libpcap 1.9.0 - Generated Sat Jul 28 16:10:39 CDT 2018
http://manpagez.com/man/3/pcap_next_ex/
CC-MAIN-2018-43
refinedweb
168
58.52
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. surf - simple webkit-based browser ================================== surf is a simple Web browser based on WebKit/GTK+. Requirements ------------ In order to build surf you need GTK+ and Webkit/GTK+ header files. In order to use the functionality of the url-bar, also install dmenu[0]. Installation ------------ Edit config.mk to match your local setup (surf is installed into the /usr/local namespace by default). Afterwards enter the following command to build and install surf (if necessary as root): make clean install Running surf ------------ run surf [URI] See the manpage for further options. Running surf in tabbed ---------------------- For running surf in tabbed[1] there is a script included in the distribution, which is run like this: surf-open.sh [URI] Further invocations of the script will run surf with the specified URI in this instance of tabbed. [0] [1]
https://bitbucket.org/va7sdf/surf
CC-MAIN-2018-26
refinedweb
159
64.81
For up-to-date information please follow to corresponding WebStorm blog or PhpStorm blog. PHPStorm6 on Ubuntu is telling me I already have the latest version when checking for an update. Will I be possible to do an in-app update or will I have to re-download and install it again? “No patch-update available for this build” in the end of the announcement means there is no patch released and it can’t be updated from within the IDE, so you need to download it at please provide update for WI-1398 & WI-6027 Please check status of these issues at and respectively. All the updates will be available there. You can star the issue and get updates. Is the issue fixed that an imported SCSS files in infile.scss has changed and then rebuild the CSS like “sass –watch infile.scss:outfile.css” can do it? We couldn’t find issue you are talking about. Could you please send us the number? If not reported, please report it at youtrack.jetbrains.com/issues/WEB Indeed, thought I saw it on the issue tracker. I have opened an issue with information about the issue. Will about bookmarks being invisible in the darcula theme be addressed in this build as well? (The PHPStorm-specific ticket about the issue was closed as a duplicate) This issue is not fixed yet. Please fix it.. I can’t see bookmarks in my dark theme for more than a year. The bookmark marks used to be dark blue.. But for some reason you guys changed it to black. Hmm, “You evalution license has expired”. But expiration date – 03 April. Please try cleaning the config directory – probably some local problems.. I think it’s really great that you guys put out the EAP releases, because it helps you develop a better product in the end. What I dislike is that all of us who take the time to download install, test and report errors for the EAP releases are left hanging for several weeks after the final release of a product. Our EAPs run out of time, and at this point we are rushing around trying to find the latest license code to make PhpStorm work again. Maybe JetBrains should have an EAP program, where developers could use the EAP year around. And for those that participate in “every” EAP, they can continue using an EAP release between complete releases. Until JetBrains does something like this, I’m going to sit out on the EAP releases. re: I’m going to sit out on the EAP releases. I don’t see the point. I had 5.0.4 installed along with a rolling last 3 EAP releases for most of the last year. When 6 came along, I installed that. Doesn’t seem much different than just having 5.0.4 and then 6.0 from a licensing perspective. Just that you miss out on participating in the EAP. OTOH, if there was always an EAP license available, what motivation would people have to buy the release? I did live in fear that another EAP wouldn’t come out in time and I would have to revert back to using 5.0.4. So it may be nice if we could apply the current license to the EAP, but I never needed to and never tried. You realize that you are complaining that a company doesn’t make its selling product free enough? Yes this is EAP and yes you participate, but come on! This message was intended for JetBrans staff. I don’t believe you understand what I’m saying. Many companies provide alpha and beta releases and have a “select group” of individuals using their product. Core users would test the software. These select users, people that use it every day could use the product and provide valuable feedback. This would take it out of the hands of the casual user, and casual users could use the 30 day trial and buy a seat if they choose. I believe this would be a benefit to JetBrains as well as their core users… We’ve had a bunch of experience with select groups of individuals getting access to our software for free in exchange for a promise to provide feedback, and it invariably ended up with nothing: the promised feedback never materialised. What we do instead is give free licenses to a few of the most active EAP members, which let them use the product once the EAP program is over. We believe that it’s the best solution for the company and for the most actively involved users. I am of the opposite opinion, I really dont like the fact that EAP releases get bug fixes while those who have paid for the product have to sit and wait for the bug fixes… the only option there is to download the EAP version, which is just a trial license. So why buy the damn thing in the first place… Have you published a changelog for this EAP? I am always happy to help run the EAP versions to assist in testing, but I do like to know what has changed! Thanks. There is a link at the bottom of download page WebStorm 6.0.1 Release Notes It’s for WebStorm, not PhpStorm. We’ll consider adding a full changelog/release notes for PhpStorm as well in the future. Thanks! Much appreciated, thank you. Is it possible to get the bug fixes for the paid version? Or do you have to download this EAP and get a time restricted copy? Just think the paid users should get the bug fixes without having to use an EAP copy. You will surely get this bug fix to your stable paid version. EAP is published earlier and can be not stable, update for a stable version is published after EAP. So please wait some time. Ditto on the changelog. I know there is somewhere in youTrack a list of what has changed, but I shouldn’t have to work so hard to be helpful. I generally give up before I find it, figuring that if you really wanted feedback, you would have provided the list. Yes, it’s in YouTrack right now. We’ll consider adding a full changelog/release notes for PhpStorm in the future. Thanks! What formatting and indentation issues have been fixed? Can you now do this? Normally that would be ugly, but it’s very useful in PHP templates. Currently, that doesn’t survive auto-formatting and gets changed to this: It seems that your message is incomplete.. Fixed issues on this topic are at least Feel free to report any issues at Thank you! Is it correct behavior that I got Update notification about PHPStorm 6.0.1 (that is still in EAP) while I am using stable public release 6.0 version (build 127.100) ? I was supposing to receive only stable public release updates. Please check Settings | Updates as it can be configured so that you get EAP notifications as well. Thank you! Still no Compass support? What were the “SASS inspections” improvements then? Using PhpStorm for editing Compass-powered SASS code in no different from using a notepad. PhpStorm considers all my variables and mixins to be undefined. And of course, all refactoring-related operations are failing. Here’s just one example:. The only difference between the IDE and a notepad is that PhpStorm warns me about every freaking variable that it might not be resolved in production. Wow, what a sincere concern! Compass is THE industry standard for SASS development and it is ridiculous that PhpStorm can’t handle even the most basic things like variable and mixin names autocompletion. Even vim can do that! I started using PhpStorm only because i needed SASS support, and only after purchase i discovered that SASS support is broken (or, more precisely, it never existed). I feel deceived. I’ve got one question: when PhpStorm and other JetBrains IDEs will have a full-fledged Compass support? The corresponding ticket has been around for two years already and still pending. The work on this is currently in progress. The fix version in the issue is 7, so it means it most probably will be available in the next major release – PhpStorm 7. Do you have the strange reording on automatic namespace use statements on your radar? E.g. I have a file: <php namespace \foo\bar; /******************** * License & copyright **********************/ /** * class comment */ class someclass extends other class { If PhpStorm now inserts use statements, then the comments will be reversed: <php namespace \foo\bar; /** * class comment */ use \other\bar; /******************** * License & copyright **********************/ class someclass extends other class { This is rather confusing Actually I either want the comments to stay in the right order or to have use statements below the namespace line, before the license header. This is a bug. We’ve reported it at Thank you!
http://blog.jetbrains.com/webide/2013/03/phpstorm-6-0-1-eap-started-build-129-91/
CC-MAIN-2015-11
refinedweb
1,493
73.88
I can connect to mysql with with "Connection con" if I'm writing a windows application. But if I try to make a windows console application I cannot use "Connection con" to connect to the mysql database. Anybody no why? here's my include: #include <windows.h> #include "resource.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <iomanip> #include <mysql++> #include <mysql++.h> #include <conio.h> #include <string.h> here's the part I get an error on: Connection con("my_database"); This is the only part I have as far as connecting for now. I just want to see if I can connect before I can continue. Am I missing something? The error I get is this: C:\MySource\sorcehelp\source\source\ctl_one\ctl_on e.cpp(134) : error C2360: initialization of 'con' is skipped by 'case' label C:\MySource\sorcehelp\source\source\ctl_one\ctl_on e.cpp(130) : see declaration of 'con' Error executing cl.exe. -Thanks
http://cboard.cprogramming.com/cplusplus-programming/24375-mysqlplusplus-cplusplus-windows-programming.html
CC-MAIN-2014-15
refinedweb
158
63.25
pam_get_user man page pam_get_user — get user name Synopsis #include <security/pam_modules.h> int pam_get_user(const pam_handle_t *pamh, const char **user, const char *prompt); Description The pam_get_user function returns the name of the user specified by pam_start(3). If no user was specified it what pam_get_item (pamh, PAM_USER, ... ); would have returned. If this is NULL it obtains the username via the pam_conv(3) mechanism, it prompts the user with the first non-NULL string in the following list: - The prompt argument passed to the function. - What is returned by pam_get_item (pamh, PAM_USER_PROMPT, ... ); - The default prompt: "login: " By whatever means the username is obtained, a pointer to it is returned as the contents of *user. Note, this memory should not be free()'d or modified by the module. This function sets the PAM_USER item associated with the pam_set_item(3) and pam_get_item(3) functions. Return Values - PAM_SUCCESS User name was successful retrieved. - PAM_SYSTEM_ERR A NULL pointer was submitted. - PAM_CONV_ERR The conversation method supplied by the application failed to obtain the username. See Also pam_end(3), pam_get_item(3), pam_set_item(3), pam_strerror(3) Referenced By pam(3), pam_get_item(3).
https://www.mankier.com/3/pam_get_user
CC-MAIN-2017-43
refinedweb
184
58.28
Pagination is a very common and widely-used navigation technique, and with good reason. First of all, consider performance. Loading all the available records in a single query can be very costly. Moreover, a user may be interested only in a couple of the most recent records (i.e., the latest posts in a blog) and does not want to wait for all records to load and render. Also, pagination makes reading the page easier by not flooding it with content. Nowadays, many websites use a slightly different technique, called infinite scrolling (or endless page). Basically, as the user scrolls down the page, more records are loaded asynchronously using AJAX. In this manner, scrolling seems more natural and can be easier for a user than constantly clicking on a ‘Next page’ link. In this article, I am going to explain how to implement infinite scrolling in place of classic pagination. First, we will prepare our demo project, implementing basic pagination using the will_paginate gem. This pagination will become infinite scrolling as we work through the tutorial. This will require writing some JavaScript (and CoffeeScript) code, along side our Ruby. The provided solution will fallback to the default pagination if a user has javascript disabled in the browser. Finally, our view will require virtually no modifications, so you can easily implement this on any website. Other items that will be covered: - How to implement a “Load more” button instead of infinite scrolling, much like the one used on SitePoint. - Some gotchas and potential problems, specifically, how the History API and scroll spying can help us. The working demo can be found at. The source code can be found on GitHub. Sound good? Let’s get rolling! Preparing the Project For this article I will be using Rails 3.2.16 but you can implement the same solution with Rails 4. Lets create a very simple blog. For now, it will only display demo posts. $ rails new infinite_scrolling -T -T here means that we want to skip generating a test suite (I prefer RSpec but of course you can omit this flag). We are going to hook up some gems that will come in handy: Gemfile gem 'will_paginate', '~> 3.0.5' gem 'betterlorem', '~> 0.1.2' gem 'bootstrap-sass', '~> 3.0.3.0' gem 'bootstrap-will_paginate', '~> 0.0.10' will_paginate will, well, paginate our records. I will go into more detail about this gem in the next section. betterlorem generates demo text in our records. There are other similar gems that produce “Lorem Ipsum” text, but I’ve found this one to be the most convenient for our case (we are going to use it in seeds.rb, not in the view). There is no point to create an award-winning design, so as a fast and easy (though not the smallest, considering the weight) solution we will use Twitter Bootstrap 3. The bootstrap-sass gem adds it into our Rails project. bootstrap-will_paginate contains some Bootstrap styling for the pagination itself. Do not forget to run $ bundle install Now add //= require bootstrap to the application.js and @import "bootstrap"; to the application.css.scss to include all the Bootstrap styles and scripts. Of course, in the real application you would choose only the required components. The Model There will be only one table: Post. It will be dead simple and contain the following columns: id(integer, primary key) title(string) body(text) created_at(datetime) updated_at(datetime) Running $ rails g model Post title:string body:text $ rake db:migrate will create an appropriate migration and then apply it to the database. The next step is to produce some test data. The easiest way to do this is to use seeds.rb. seeds.rb 50.times { |i| Post.create(title: "Post #{i}", body: BetterLorem.p(5, false, false)) } This creates 50 posts with the body generated by BetterLorem. Each set of generated content consists of 5 paragraphs. The last two arguments tell BetterLorem to wrap the text in a p tag and include a trailing period. Running $ rake db:seed will populate our database with some test posts. Awesome! The last thing is to create a PostsController with index and show methods, along with the corresponding views ( index.html.erb and show.html.erb). Also, do not forget to set up the routes: routes.rb resources :posts, only: [:index, :show] root to: 'posts#index' Finally, if you’re using Rails 3, be sure to delete the public/index.html file. The Controller We are ready to move to the fun part. At first, let’s display some paginated posts with a truncated body. For this, we are going to use will_paginate – a simple yet convenient gem by Mislav Marohnić that works with Ruby on Rails, Sinatra, Merb, DataMapper and Sequel. There is an alternative to this solution – kaminari by Akira Matsuda that is more powerful and more sophisticated. You can also give it a try. Basically, it doesn’t matter which gem you use. In our controller: posts_controller.rb @posts = Post.paginate(page: params[:page], per_page: 15).order('created_at DESC') The call to the paginate method accepts a page option telling it which GET parameter to use to fetch the required page number. The per_page option specifies how many records should be displayed per page. The per_page option can be specified for the whole model or for the whole project like this: post.rb class Post self.per_page = 10 end will_paginate.rb (in an initializer) WillPaginate.per_page = 10 The paginate method returns a an ActiveRecord::Relation so we can chain on a call to the order method. The View index.html.erb <div class="page-header"> <h1>My posts</h1> </div> <div id="my-posts"> <%= render @posts %> </div> <div id="infinite-scrolling"> <%= will_paginate %> </div> A page header is specified with the help of a Bootstrap class. The next block, #my-posts, contains our paginated posts. Using render @posts displays each post from the array using the _post.html.erb partial. The last block, #infinite-scrolling, houses the pagination controls. Note that will_paginate is clever enough to understand that we want to paginate @posts. You can specify it explicitly like this: will_paginate @posts. Here is our post partial. _post.html.erb <div> <h2><%= link_to post.title, post_path(post) %></h2> <small><em><%= post.timestamp %></em></small> <p><%= truncate(strip_tags(post.body), length: 600) %></p> </div> We wrap every post with a div, then display the title that acts as a link to read the whole post. The timestamp indicates when the post was created. This timestamp method is defined inside the model like this: post.rb def timestamp created_at.strftime('%d %B %Y %H:%M:%S') end Lastly we use the strip_tags method to remove all the tags from the post and truncate to strip all but the first 600 symbols. This ends our work with the views (I have omitted markup for the layout.html.erb and show.html.erb as it is not that important; you can check it in the GitHub repo). Infinite Scrolling We are ready to transform our pagination to infinite scrolling. jQuery will help us with this task. Create a new file pagination.js.coffee inside the javascripts directory. pagination.js.coffee jQuery -> if $('#infinite-scrolling').size() > 0 $(window).on 'scroll', -> more_posts_url = $('.pagination .next_page a').attr('href') if more_posts_url && $(window).scrollTop() > $(document).height() - $(window).height() - 60 $('.pagination').html('<img src="/assets/ajax-loader.gif" alt="Loading..." title="Loading..." />') $.getScript more_posts_url return return Here we are binding a scroll event to the window, only if the pagination is present on the page. When the user scrolls, fetch the link to the next page – visiting it will make Rails load the records from that page (we still need to make some modifications to the controller to get this working). Then, check that the URL is present and the user scrolled to the bottom of the page minus 60px. This is when we want to load more posts. This value of 60px is arbitrary, and you’ll probably want to change it for your case. If these conditions are true we are replacing our pagination with a “loading” GIF image that can be freely downloaded at ajaxload.info. The last thing to do is to actually perform an asynchronous request using the URL that we’ve fetched previously. $.getScript will load a JS script from the server and then execute it. Note the two return instructions. By default, CoffeeScript will return the last expression (the same concept applies to Ruby) but here we do not want the jQuery function or event handler to return anything so specifying return means “return nothing”. The PostController#index method should respond to both HTML and JavaScript. We are going to use respond_to to achieve that: posts_controller.rb @posts = Post.paginate(page: params[:page], per_page: 15).order('created_at DESC') respond_to do |format| format.html format.js end The last thing to do is to create a view that will be rendered when responding with JS: index.js.erb $('#my-posts').append('<%= j render @posts %>'); <% if @posts.next_page %> $('.pagination').replaceWith('<%= j will_paginate @posts %>'); <% else %> $(window).off('scroll'); $('.pagination').remove(); <% end %> We are rendering more posts by appending them to the #my-posts block. After that, check to see if there are more pages left. If so, replace the current pagination block (which at this point contains “loading” image) with a new pagination. Otherwise, we remove the pagination controls and unbind the scroll event from window, as there is no point in listening to it anymore. At this point, our infinite scrolling is ready. Even if a user has JavaScript disabled in the browser, it will be presented with the default pagination that has some styling applied thanks to the bootstrap-will_paginate gem. One thing worth mentioning is that scrolling will fire loads of scroll events. If you want to delay handling of this event you can use an OpenSource library BindWithDelay written by Brian Grinstead. To use it, simply download it and include it in the project. Then, make the following modifications to the script: pagination.js.coffee $(window).bindWithDelay 'scroll', -> # the code , 100 This will delay firing the event by 100ms. $(window).off('scroll'); inside the index.js.erb will still unbind the event, so no modifications is needed there. This ends the first part of the article. In the next part we are going to talk about the “Load more” button and some problems that arise when using infinite scrolling. Thanks for reading and see you soon! - heel - tomwardrop - Ilya Bodrov - Irakli Koridze - Ilya Bodrov - denny - PSR - Ilya Bodrov - Yumiko Huang - Marko Ćilimković - Marko Ćilimković - Ilya Bodrov - Armando Braun - Armando Braun - Ilya Bodrov - Armando Braun - Ilya Bodrov - RailsZilla - mikbe - Ilya Bodrov - mikbe - Hahns - Mike Bethany - dnd - Ilya Bodrov - mikbe - rmagnum2002 - Johnjay - stumped - PSR - blue - Guest - Rue - Andrew - Szilard Magyar - Ilya Bodrov - Szilard Magyar - Ilya Bodrov - gautamkathrotiya
http://www.sitepoint.com/infinite-scrolling-rails-basics/
CC-MAIN-2016-18
refinedweb
1,810
67.25
Count The Number Of Players Who Need Training And Have Strictly Less Power And Endurance Than Any Other Player Introduction In this article, we are going to solve a problem based on a greedy approach. Let’s proceed deeper into the Problem statement and its solution approach. Problem Statement We are given a 2D array consisting of three components [power, endurance, id]. A player needs training if its power and endurance are strictly less than the power and the endurance of any other player. The task is to find the number of players who need training with their ids. Example: INPUT: {{1, 2, 1}, {2, 3, 2}, {3, 4, 3}} OUTPUT: 2 1 2 Explanation: Below are the players who need training Player with id = 1, having power = 1 and endurance = 2 is strictly less than player with id = 3. Player with id = 2, having power = 2 and endurance = 3 is strictly less than player with id = 3. Approach: Greedy Method We can use Greedy Approach to solve the problem. Suppose we have two players X and Y. Player X needs training if there exists a Player Y such as the power of Player X < Power of Player Y and endurance of Player X < endurance of the Player Y. We can sort the array on the basis of two parameters, Power and Endurance in non-decreasing order. That is first we will compare power, If power is the same then we will compare endurance and sort according to decreasing order of endurance. In the C++ Sort function, we can custom sort using our own comparator function. Algorithm - Write a custom comparison function that compares two entities, power and endurance such that power will be in increasing order and when power of two players are same then sort them according to endurance in decreasing order. - Sort the input array according to the comparison function mentioned above. - Iterate through the players[][] array from the right side, keeping account of the maximum previous endurance. - If any player is eligible for training, store its id. - If the current player's endurance is less than the previous maximum endurance value, increase the player count. - Otherwise, the maximum endurance value should be updated. - Return an array containing the ids of all players who require training. Code #include <iostream> #include <bits/stdc++.h> using namespace std; vector<int> CountOfPlayers(vector<vector<int> >&players) { int count = 0; int n = players.size(); sort(players.begin(), players.end(),[](vector<int>& v1, vector<int>& v2) { // If power value is equal // for both elements // Sort in descending order // according to endurance value if (v1[0] == v2[0]) return v2[1] < v1[1]; else return v1[0] < v2[0]; }); // Keep track of maximum // endurance value in right side int ma = 0; vector<int> res; // Traverse the array players for (int i = n - 1; i >= 0; i--) { // If current endurance // value is smaller than // max then we will // increment the count int id = players[i][2]; if (players[i][1] < ma) { // Adding player res.push_back(id); // Increase the count count++; } // Update max endurance value ma = max(ma, players[i][1]); } return res; } // Driver Code int main() { vector<vector<int> > players = {{1, 2, 1}, {2, 3, 2}, {3, 4, 3}, {3,3,4}}; vector<int> ans = CountOfPlayers(players); cout << ans.size() << "\n"; for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " "; } return 0; } Output 2 2 1 Complexity Analysis Time Complexity: O(N*logN) Because sorting takes O(NlogN) time for N items and here we are sorting players array with N items. Space Complexity: O(1) Some variables are used which use only O(1) constant space. Frequently Asked Questions - What is the time complexity of the STL sorting algorithm in C++? The common STL sorting algorithm in C++ in O(NlogN) in time complexity. - What are the best-case and worst-case time complexity of Quick Sort? The best-case scenario is when the list is generated completely at random which is O(NlogN) time complexity. The worst-case scenario is when the array is already either sorted in ascending or descending order which is O(N2) time complexity. Key Takeaways In optimization problems, a greedy algorithm is a straightforward, intuitive solution. It tries to find the overall best solution to the problem, the algorithm takes the best decision at each phase. If you wish to learn more about greedy algorithms, you can visit Greedy Algorithms in Array. Although it is always suggested that solving the problem using a naive approach but observing the solution and problem carefully can yield great results. Observation is a great tool in developing the most efficient solutions and can improve our problem-solving skills. Happy Coding!
https://www.codingninjas.com/codestudio/library/count-the-number-of-players-who-need-training-and-have-strictly-less-power-and-endurance-than-any-other-player
CC-MAIN-2022-27
refinedweb
781
60.04
Both compilers support compile time extended codeblocks which allow to use statements but with a little bit different syntax. Harbour uses standard Clipper codeblock delimiters {}, f.e.: ? eval( { | p1, p2, p3 | ? p1, p2, p3 return p1 + p2 + p3 }, 1, 2, 3 ) and xHarbour <>, f.e.: ? eval( < | p1, p2, p3 | ? p1, p2, p3 return p1 + p2 + p3 >, 1, 2, 3 ) In Harbour extended codeblocks works like nested functions and support all functions attributes, f.e. they can have own static variables or other declarations which are local to extended codeblocks only and do not effect upper function body. In xHarbour the compiler was not fully updated for such functionality and extended codeblocks were added to existing compiler structures what causes that not all language constructs work in extended codeblocks and creates a set of very serious compiler bugs, f.e., like in this code with syntax errors but which is compiled by xHarbour without even single warning giving unexpected results at runtime: #ifndef __XHARBOUR__ #xtranslate \<|[ ]| => {| | #xcommand > [<*x*>] => } #endif proc main() local cb, i for i:=1 to 5 cb := <| p | ? p exit return p * 10 > ?? eval( cb, i ) next return It's possible to create many other similar examples which are mostly caused by missing in the compiler infrastructure for nested functions support. This can be fixed if someone invest some time to clean xHarbour compiler. This is the successor to Clipper... Clipper... Clipper, a popular & well-linked CA-Clipper website which I started in 1995 and which went offline in 2002 Wednesday, March 2, 2011 Harbour/xharbour Diff (3/57) - EXTENDED CODEBLOCKS by Przemyslaw Czerpak<<
http://cch4clipper.blogspot.com/2011/03/harbourxharbour-differences-extended.html
CC-MAIN-2018-30
refinedweb
265
53
Efficient way to access maps inside maps and handle possible exceptions Efficient way to access maps inside maps and handle possible - Using a for comprehension : type MMMap[K1, K2, K3, V] = Map[K1, Map[K2, Map[ K3, V]]] def getFromMMMap[K1, K2, K3, V]( mmmap: Handling checked exceptions in Java streams - Get the O'Reilly Programming Newsletter Here you'll see three primary ways to handle exceptions in a stream pipeline and each The map method takes a Function , one of the new functional interfaces in the The easiest answer is to embed a try/catch block inside the pipeline, as shown in Example 2. Exception Handling in Java Streams - We take a look at exception handling in Java Streams, focusing on As you all probably know, it is not possible to call a method that throws a checked exception from a lambda . .map(wrap(item -> doSomething(item))) . want to use existing methods that throw a checked Exception inside a lambda right? Elegant error handling with the JavaScript Either Monad - Exceptions and trycatch blocks serve a purpose but they have some issues. And they are not the only way to handle errors. Don't worry if you get confused at first. .. ¹ In JavaScript, we do this by creating objects that have methods .. So , if we use .map() we end up sticking an Either inside an Either. Functional Exceptions In Java - This post will suggest how to handle exceptions seamlessly in functional Java code, from a catch block inside the lambda (substituting flatMap for map ) On top of being safer, Optional also has methods which make it easy to Before we get into designing a functional, error-handling API in Java, let's see Functional error handling in Scala - But of course you can still have exceptions when you try to access servers that are This lesson demonstrates the techniques of functional error handling in Scala. There are quite a few ways to work with the results of a Try — including the Scala best practice: How to use the Option/Some/None pattern. Exception Handling in Spring MVC - At start-up, Spring Boot tries to find a mapping for /error . @RequestMapping( value="/orders/{id}", method=GET) public String Exception handling methods // Convert a predefined exception to an Instead, setup a model inside the method using a ModelAndView as shown by handleError() above. Why you should ignore exceptions in Java and how to do it correctly - In this article, I will show how to ignore checked exceptions in Java. can force its caller to deal with the occurrence of potential exceptions. is to “label” methods that can potentially throw exceptions. Function , which is the parameter of the map method. createURL(url)).get()) .collect(Collectors. Exceptions in Lambda Expression Using Vavr - To get more information about Vavr and how to set it up, check out this article. We can use the above method inside a lambda expression without handling the IOException: or the wrapper methods, we can still call exception throwing methods inside a .map(CheckedFunction1.lift(i -> readFromFile(i))). Exception handling vs. hasNext() - try { widgetMap.get(it.next()).hide(); } catch(Exception e) { if(e instanceof StopIteration) {. } } Omitting hasNext() forces developers to use exception handling for One benefit of StopIteration is that code inside map/some/every etc can just throw a .. This is best: How is it possible to iterate over the keys in a Map? I'd like java stream runtime exception Exception Handling in Java Streams - The Stream API and lambda’s where a big improvement in Java since version 8. As you all probably know, it is not possible to call a method that throws a checked exception from a lambda directly. In some way, we need to catch the exception to make the code compile. Exceptions in Java 8 Lambda Expressions - Overview. In Java 8, Lambda Expressions started to facilitate functional Handling Unchecked Exceptions . throw new RuntimeException(e);. Aggregate runtime exceptions in Java 8 streams - In this simple case where the doStuff method is void and you only care about the exceptions, you can keep things simple: myObjs.stream() . Handling checked exceptions in Java streams - Know your options for managing checked exceptions in Java 8's UnsupportedEncodingException e ) { throw new RuntimeException ( e ); RuntimeException (Java Platform SE 8 ) - Constructs a new runtime exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled. How to Throw Exceptions (The Java™ Tutorials > Essential Classes - The Java Tutorials have been written for JDK 8. Before you can catch an exception, some code somewhere must throw one. by someone else such as the packages that come with the Java platform, or the Java runtime environment. Repackaging Exceptions In Streams - How to repackage checked exceptions that get thrown in a Java stream pipeline so that Handling Exceptions In Streams: Catch and handle exceptions on the spot, . If you really want to throw, wrap in a runtime exception. Why you should ignore exceptions in Java and how to do it correctly - We can wrap the exception into a RuntimeException, which is an unchecked exception. This has the In Java 8, our example above looks like: RuntimeException - RuntimeException. public class RuntimeException extends Exception Object. ↳, java.lang.Throwable. ↳, java.lang.Exception. ↳, java.lang.RuntimeException Checked Exceptions and Streams - This is likely to become more of a pain with Java 8, where the Streams . This approach involves wrapping all checked exceptions in runtime exception handling in java Exceptions in Java -. Exception Handling in Java - Exception Handling in Java or Java Exceptions with checked, unchecked and errors with example and usage of try, catch, throw, throws and finally keywords. Java Exceptions - Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java. Checked exceptions − A Java Exception Handling: How to Specify and Handle Exceptions - Errors happen all the time. Java provides a powerful exception handling mechanism that allows you to handle or propagate them. Exception Handling in Java - Learn the basics of exception handling in Java as well as some best and worst practices. Lesson: Exceptions (The Java™ Tutorials > Essential Classes) - The Java programming language uses exceptions to handle errors and other exceptional events. This lesson describes when and how to use exceptions. Exception handling in java with examples - Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. In this. Exception Handling in Java - Exception Handling in Java is a very interesting topic. Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Exception Handling in Java: A Complete Guide with Best and Worst - Overview. Handling Exceptions in Java is one of the most basic and fundamental things a developer should know by heart. Sadly, this is often Try Catch in Java: Exception Handling Example - Learn exception handling, try catch, exception hierarchy and finally block with examples in this tutorial. java 8 exception handling Exception Handling in Java - Learn the basics of exception handling in Java as well as some best and 8. Exception in thread "main" java.nio.file.NoSuchFileException: Exceptions in Java 8 Lambda Expressions - In Java 8, Lambda Expressions started to facilitate functional programming by providing a concise way to Handling Unchecked Exceptions. 9 Best Practices to Handle Exceptions in Java - Exception handling in Java isn't an easy topic. .. 8. Don't log and throw. That is probably the most often ignored best practice in this list. Lesson: Exceptions (The Java™ Tutorials > Essential Classes) - The Java Tutorials have been written for JDK 8. Examples and practices This section covers how to catch and handle exceptions. The discussion includes the Java 8 Functional Interfaces and Checked Exceptions - How to work with Java 8 Functions and Functional interfaces that throw This post will present one option for handling checked exceptions in Exception Handling in Java Streams - We take a look at exception handling in Java Streams, focusing on API and lambda's where a big improvement in Java since version 8. Exceptional Exception Handling in JDK 8 Streams - In my last blog entry, I used a small piece of code I was working on to demonstrate how pre-JDK 8 code using external iteration could be 7. Exception Handling - Java 8 Pocket Guide [Book] - Chapter 7. Exception Handling An exception is an anomalous condition that alters or interrupts the flow of execution. Java provides built-in exception handling to Handling checked exceptions in Java streams - Know your options for managing checked exceptions in Java 8's functional approach. Java Catch Multiple Exceptions, Rethrow Exception - Java catch multiple exceptions, java rethrow exceptions, java 7 feature to In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. In Java 8 exception parameter can be changed in multi catch block ? how to handle exception in foreach Java 8: How do I work with exception throwing methods in streams - 7 Answers. You need to wrap your method call into another one, where you do not throw checked exceptions. You can still throw anything that is a subclass of RuntimeException . Then you can call it with: as.forEach(this::safeFoo) . Exceptions in Java 8 Lambda Expressions - In this article, we'll explore some ways to deal with exceptions when writing lambda forEach(lambdaWrapper(i -> System.out.println( 50 / i))); Handling checked exceptions in Java streams - Know your options for managing checked exceptions in Java 8's functional approach. Exception Handling in Java Streams - We take a look at exception handling in Java Streams, focusing on wrapping it into a RuntimeException by forEach(System.out::println);. How to Handle Checked Exceptions With Lambda Expression (Part - In Java, we can only handle exceptions through the try-catch block, URL object and then passed it to the forEach method, which saves it in a functional programming - If the calling-code is to handle the checked exception you MUST add it . forEach (Cocoon.consumer(MyClass::methodThatThrowsException)) ;. Repackaging Exceptions In Streams - How to handle checked exceptions in stream pipelines is one such problem. Handling Exceptions In Streams: Catch and handle exceptions on the spot, possibly by deferring error handling. . forEach(System.out::println);. Java 8 Functional Interfaces with Exceptions - Consider a lambda of Function where you need to deal with an Currently, if needed checked exceptions thrown inside a forEach or map Better Exception Handling in Java 8 Streams Using Javaslang - In this post I will provide tips for better exception handling in Java 8 streams using Javaslang forEach(System.out::println); // Print } }. This will Exception Handling: foreach With try-catch Block - Exception Handling: foreach With try-catch Block. Suppose we have multiple independent objects, and we are given a task to clone those objects. We fetch
http://www.brokencontrollers.com/article/31723487.shtml
CC-MAIN-2019-39
refinedweb
1,799
50.67
Domains I've always thought that domain squatting was an unethical way to make money, but had only heard stories of it before now. Anne suggested that it might be nice to pick up the gearon.com domain, if it was available. After all, I normally take up a lot of the first result page at Google when you type in my surname. (Just looked, and today I don't! I really need to blog more often.) OK, so I'm not a commercial entity, but everyone recognizes .com, while people often look at me funny when I say .org or .net. The .com thing has brand recognition. So I had a look, and discovered that the domain is already registered, but it is for sale. It turns out that it's available for purchase through the bidding process available at Afternic.com. The minimum bidding price was way more than I'd have liked to spend, but it's my name, so why not? A week later I discovered the bid was rejected. I asked Afternic what a decent price is supposed to be (according to their market analysis). Their response was that the current market value is $200. Still far too much, but it gave me confidence to ask the current domain holder how much they would like. The answer? $2950. Quoting from the email: Price is very low for a family name. Huh? Whose family? The Rockefellers? I didn't care about the domain all that much (it should probably go to a more commercial interest, like something run by Michael Gearon or Tierney Gearon), but registering a name and then charging to give it back to an owner of that name is a principle I find rather offensive. I suppose I should be grateful she was asking for $3000 and not $30,000. I resolved it by registering gearon.org for $8.20. UIMA The other day I followed a link over to IBM's DeveloperWorks, and found that they have an RSS feed for their tutorials. I was pleased to find a simple Python tutorial that I'm using to finally introduce myself to that language. But more importantly, I found a tutorial for generating a UIMA annotator. The UIMA docs are very verbose, and a tutorial like this has been great for cutting through the chaff. It's still full of stuff I don't need (mostly because I've already learnt it from the official UIMA docs), but it's still been a real help. My biggest problem at the moment is that UIMA wants all my annotations in character offsets. Unfortunately the library I'm using is providing my information in word offsets. That's trivial to convert when words are separated by whitespace, but punctuation leads to all sorts of unexpected things, particularly since the grammar parser treats some punctuation as individual words, while others get merged into existing words. I'm starting to wonder if I need to re-implement the parser so I know what the character offsets of each word will be. Either that, or I'll be doing lots of inefficient string searching. I don't find either prospect enticing. Maybe if I sleep on it I'll come up with something else. Thursday, December 29, 2005 Domains Wednesday, December 28, 2005 Gödels Theorem I was just looking at the fascinating exhibit of equations by Justin Mullins. I'm not sure if I see the exhibit as art, since the visual appearance evokes little in people who do not understand the equations (with the possible exception of the Four Color Theorem), but they are certainly beautiful. I particularly loved the end of the narrative for Gödel's theorem: Others have wondered what Gödel’s theorem means for our understanding of the human mind. If our brains are machines that work in a consistent way, then Gödel’s theorem applies. Does that mean that it is possible to think of ideas that are true but be unable to prove them? Nobody knows. Note the sentence that I highlighted. If it is true, then that sentence is an unprovable idea. I love it. Posted by Paula G at Wednesday, December 28, 2005 0 Saturday, December 17, 2005 Qubytes Lots of places are commenting on the new quantum memory chips in silicon. I'm surprised at this. I expected that embedding quantum devices in silicon would be done with quantum dots, rather than ion traps. It is probably better than it was done with ion traps as there seems to have been more research into quantum processes using this technology. After all, what good is a quantum state if you can't apply transformations on it without collapsing the state? All the same, a chip like this is just a first step in a long line of problems to be solved. There is no discussion about setting up quantum states, nor reading them back. There is no discussion about the ability to entangle the qubits on the chip, and how far that will scale. Transformations will eventually have to be built in to the chip. But if research has taught me anything, it's that the big problems are usually solved by lots of people chipping away at the little problems. By the time the final solution comes around, it doesn't seem like a big deal any more. Tracker The little tracker icon I have on this page is a link to a service that tells me how many hits the blog is getting (but not the RSS feed). I haven't bothered to look at the stats in a long time. After all, I'm rarely writing, so why would anybody (beyond my friends) bother to read? Apparently I was wrong in that assessment. I'm averaging over 20 hits a day, with peaks over 40, and I'm writing less that once a week. My infrequency is due to lack of time. Given how many people are reading so little here, I'm wondering if anyone else suffers the same problem. :-) Posted by Paula G at Saturday, December 17, 2005 0 Thursday, December 15, 2005 Blogging I notice a new post on the Google Blog describing a new tool for Firefox. When installed, a small message will appear on any page you visit, showing a list of blogs which refer to that page. Sounds cute. I normally browse with Safari (gotta love those native widgets), but I keep Firefox installed (after all, some pages have extra features when viewed with Firefox). So here was a chance to upgrade my version of Firefox (I hadn't picked up 1.5 yet) and install Google's new tool. So where should I go first to check out the comment? Well obviously my usual home page of Google comes up, and there are ample comments. How about the page talking about the new tool? Lots of comments there too. Oh, I know! How about this blog? :-) Unfortunately the list of comments was a little disappointing, mostly including my friends. That will teach me to not blog regularly. However, I did find one blog on semantic web development that I found really interesting. I was just disappointed that he didn't have a lot of incoming links (though there was one worth checking out). All in all, it's a tool that I like. In fact, I wouldn't mind a similar tool that did a link: search on Google, rather than just in the bloggosphere. Posted by Paula G at Thursday, December 15, 2005 0 Tuesday, December 13, 2005 Modeling Talk Last week I was invited along to a talk given by Bob at SAP. I enjoy seeing what Bob's working on when I'm not discussing OWL with him. He's a clever guy, and understands modeling quite well. I just wish I'd written about it sooner, as I won't be so clear anymore. Probably the most important thing I got out of his talk was an overview of category theory. Andrae and Simon have both spoken about it, and I've come to understand that it's relevant, but as yet I haven't learnt anything about it. Bob gave the 30 second overview for computer scientists, which I found quite enlightening. I finally got my copy of Types and Programming Languages (otherwise known as TAPL), and have been looking forward to reading it. But when ordering this book I discovered that Benjamin Pierce has also written a much smaller book called Basic Category Theory for Computer Scientists. I had considered getting this book (at only 117 pages, it looks like a relatively quick read), and Bob's talk has now convinced me. The only problem is that I'll have to put the order off until we move to the States... whenever that happens. modeling Speaking of books, I also picked up a copy of MDA Distilled, Principles of Model-Driven Architecture. Some of the work I did with SAP came out of this book (virtually guaranteed when you work with one of the authors), and it talks about the kind of dynamic modeling that I've been talking about investigating with OWL. I haven't been through all of it before now, so I thought it would be worthwhile reading it in detail. Coincidentally, I was explaining some of my ideas to someone at work today (Indy), and referred to this book to describe some of the background. I had some idea that Herzum Software worked with MDA (which is why I thought they might be interested in this work), but I had never thought of it as a formal association. Indy quickly made it very clear that Herzum Software specifically put themselves out there as an MDA company. That makes perfect sense as it aligns with what I already knew, but being in my own little corner of the world has kept me isolated from the advertising of it. Anyway, it's nice to know that the direction I'm moving in is paralleled by the work of my new employer. RDFS Entailment I've also been in an email discussion about entailment on RDFS. It seems that the following statements: will lead to an entailment of:will lead to an entailment of: <camera:min> <rdfs:range> <xsd:float> <_node301> <camera:min> '15.0'^^<xsd:float> It seems that I didn't cover all the possible rules which could lead to a literal in the subject position. It's quite annoying, as these are completely valid entailments, according to RDF semantics. Making special cases to avoid particular results seems like a hack.It seems that I didn't cover all the possible rules which could lead to a literal in the subject position. It's quite annoying, as these are completely valid entailments, according to RDF semantics. Making special cases to avoid particular results seems like a hack. <xsd:float> <rdfs:subClassOf> <rdfs:Resource> '15.0'^^<xsd:float> <rdf:type> <xsd:float> '15.0'^^<xsd:float> <rdf:type> <rdfs:Resource> In a similar way, it seems wrong to not allow entailments about blank nodes. I should re-visit the decision there. I think I need to re-read the semantics document to see if I can get further enlightenment. At the least, I know that I can't entail a statement with a blank node as the predicate. Like the problem with literals, the semantics document appears to justify this sort of statement, but the RDF syntax doesn't allow for it. I know this is a particular bugbear for Andrae. Posted by Paula G at Tuesday, December 13, 2005 0 Catch Up I've been wanting to write for nearly a week now. Every time I try to sit down for it I've had a work task, family needs, or packing to take priority over this blog. I ended up having to write little notes to myself to remind me of what I wanted to blog about. JNI and Linux Having made the Link library work on Mac OSX using JNI, I figured it would be easy to get it working on Linux as well. Unfortunately it didn't work out that way. To start with, I got an error from the JVM saying that it could not find a symbol called "main" when loading the library. This sounded a little like dlopen loading an incorrectly linked file. I'm guessing that the dlopen procedure found what it thought was an executable, and therefore expected to see a main method. Googling confirmed this, but didn't really help me work out the appropriate flags for linking to fix this. I had compiled the modules for the library using -fPIC (position independent code). I then used a -Wl,-shared flag to tell gcc to pass a -shared flag to the linker, in order to link the modules into a shared library. However, it turned out that I really needed to just use -shared directly on gcc. I've still to work out what the exact difference is, but that's not a big priority for me at the moment, since I have it working. According to DavidM there is something in the gcc man page about this, so at least I know where to look. After linking correctly, the test code promptly gave a Hotspot error, due to a sigsegv. This meant that there was a problem with the C code. This had me a little confused, as it had run perfectly on OSX. Compiling everything in C and putting it all in a single executable demonstrated that the code worked fine on Linux, so I started suspecting that the problem might be across the JNI interface. This ended up being wrong. :-) There are not many differences between the two systems, with the exception of the endianess of the CPUs. However, after looking at the problem carefully, I could not see this being the problem. The initial error included the following stack trace: The only code I had real control of was inThe only code I had real control of was in C [libc.so.6+0xb1960] C [libc.so.6+0xb4fcb] regexec+0x5b C [libc.so.6+0xd0a98] advance+0x48 C [liblink.so+0x19f9d] read_dictionary+0x29 C [liblink.so+0x1d705] C [liblink.so+0x1d914] dictionary_create+0x19 C [liblink.so+0x286c9] Java_com_link_Dictionary_create+0xc1 Java_com_link_Dictionary_create, dictionary_createand read_dictionary. I started by looking in Java_com_link_Dictionary_createand printing the arguments, but everything looked fine. So then I went to the other end and looked in read_dictionary. I was a little curious about how read_dictionarywas calling advance, as I hadn't heard of this function before. Then I discovered that the function being called was from the Link library, and has a signature of advance(Dictionary). This didn't really make sense, as my reading of the stack trace above said that advancecame from libc and not the Link library (liblink). This should have told me exactly what was happening, but instead I tried to justify what I was seeing. I convinced myself that the function name at the end of each line described the function that had called into that stack frame. In hindsight, it was a silly bit of reasoning. I was probably just tired. So to track the problem down I start putting printf()statements through the code. The first thing that happened was that the hotspot errors changed, making the error appear a little later during execution. So that meant I had a stack smash. Obviously, one of the printf()invocations was leaving a parameter on the stack that helped the above stack trace avoid the sigsegv. OK, so now I'm getting some more info on the problem. It all came together when I discovered that I was seeing output from just before read_dictionary()called advance(), and from just after it, but not from any of the code inside the advance()function. At that point I realised that the above stack trace didn't need a strange interpretation, and that the advance()that I was calling was coming from libc and not the local library. Unfortunately, doing a "man advance" on my Linux system showed up nothing. Was I wrong about this method? I decided to go straight to the source, and did a "nm -D /lib/libc.so.6 | grep advance". Sure enough, I found the following: So what was this function? Obviously something internal to libc. I could download the source, but that wasn't going to make a difference to the problem or the solution. I just had to avoid calling it.So what was this function? Obviously something internal to libc. I could download the source, but that wasn't going to make a difference to the problem or the solution. I just had to avoid calling it. 000b9220 W advance My first approach was to change the function inside Link to advance_dict(). This worked perfectly, and showed that I'd found the problem. However, when the modules were all linked into a single executable it had all worked correctly, and had picked up the local function, rather than the one found in libc. Why not? I decided that if I gave the compiler a hint that the method was local, then maybe that would be picked up by the linker. So rather than renaming the function to advance_dict(), I changed its signature from: to:to: int advance(Dictionary dict) I didn't know that this would work, but it seemed reasonable, and certainly cleaner since it's always a bad idea to presume that your name is unique (as demonstrated already). Fortunately, this solution worked just fine.I didn't know that this would work, but it seemed reasonable, and certainly cleaner since it's always a bad idea to presume that your name is unique (as demonstrated already). Fortunately, this solution worked just fine. static int advance(Dictionary dict) DavidM explained to me that staticmakes a symbol local to a compilation unit (which I knew) and was effectively a separate namespace (which I also knew). He also explained that this "namespace" has the highest priority... which I didn't know, but had suspected. So I learned something new. David and I also learnt that libc on Linux has an undocumented symbol in it called advance. This is worth noting, given how common a name that is. As shown here, it is likely to cause problems on any shared library that might want to use that name. There's more to write, but it's late, so I'll leave it for the morning. Posted by Paula G at Tuesday, December 13, 2005 0 Sunday, December 04, 2005 Blogging I'm a little annoyed at myself for lack of blogging recently. This is particularly the case as I see mainstream media commenting on people's online presence more and more. I almost feel like I'm missing out on something. Yes, I know that's a ridiculous concern, but I'm allowed to worry about anything I want to. :-) Other than the restrictions imposed on me by my recently expanded family, my main problem with blogging recently has been lack of material. I don't mean that I have nothing to say. Instead, I'm limited by what is appropriate to put into a public forum. It was much easier when I worked on Open Source software all the time. For instance, this last week has had me reviewing software produced by a group of academics at another company. My review is for my employer, so I obviously can't publish it (otherwise, why would he be paying me?). Also, any review will naturally say both good and bad things. The good may be OK, but saying something bad in public is obviously inappropriate. After all, these guys are out to impress customers and make money too. So I'm left having to write about what I do out of hours. That's all well and good, but having a young family reduces the time for that. I could always write a few opinion pieces. Australian federal politics has had me feeling frustrated for some time now, and I definitely have things to say on the topic. But that's not what this particular blog is about. I could always start a parallel blog, but then, who would really want to know what I think about Brendan Nelson and higher education in Australia? It would be cathartic for me, but not so much that I think it's really worthwhile. All the same, I might consider a second blog to contain random musings (like this one). Maybe one evening when I'm not feeling like going to bed, and I have something I feel I want to say. I could be a mix of my daily life, frustrations, and comments on the oft explored experience of fatherhood. I'm not sure it will be good reading, but I may have fun coming back to it in a few years to see just how naive I really was back in 2005. :-) Grammar Meanwhile, I'm back to grammar parsing, using Link. I was a little chuffed to get the JNI all working, particularly when I was able to rewrite some of the test code in Java and have it all run correctly. I still need to test that it runs fine on Linux, but I don't have any real concerns there. Making it run on Windows will be another story. Ideally, I'll be able to use MingW as the compiler, as it should help keep the codebase and build process consistent. I just hope I won't have to jump through too many hoops to generate a DLL file. I could always ask someone at work if we have an MS commercial compiler, but we may not. I have my own, but I'm notlicensedd to use it for work. It amazes me that people are concerned about the restrictions of Open Source licensing, when commercial licensing can be far worse. Weather I'm a little obsessed with the weather at the moment. I enjoy our sub-tropical climate here, and it's going to be a rude shock to land in Chicago in the middle of Winter. As a result, I'm enjoying every minute here that I can. I'm also comparing the weather between the two cities on a day-by-day basis. The huge difference fascinates me, but the guys at work are probably annoyed with me by now. According to AccuWeather.com, Chicago is currently well below zero Celsius), and will be staying that way all week. The town I grew up in (Chinchilla) often goes below zero during Winter, but that only happens overnight. Chinchilla also hasn't had snow since the early 1900's (1915 rings a bell for some reason). Brisbane has been my home for the last 17 years, and it has never been below freezing (at least, not in recorded history). So I really haven't experienced anything like Chicago before. Can you blame me for paying attention to the differences? In the meantime, Brisbane is just starting on its first heat wave for the Summer. Fortunately, it's not supposed to get as high as 40C (104F) over the coming week, but it won't be far off. The prediction is 37C (99F). Not too bad, but unpleasant all the same. Overnight minimums are over 20C (68F), so Luc isn't sleeping too well. This is a far cry from Chicago, where the highest maximum for the coming week is -4C (24F). This will certainly add some excitement to the move! Posted by Paula G at Sunday, December 04, 2005 0 Thursday, December 01, 2005 Bytecodes DavidM helped me to find a slew of bytecode libraries (many of which are here). Some of these are better than others, but I was surprised to discover that none of them work from the basis of an AST. That means a lot of work gluing an AST onto an appropriate bytecode library, which reduces the advantages of using third party libraries. That leads me back to looking at an existing compiler, as these must already go from AST to bytecode. All I'm trying to achieve beyond this is the ability to persist and retrieve the AST in RDF, and a public API for modifying the AST. So maybe I should be going directly to a compiler like the one built into Eclipse? Types and Computer Languages One of DavidM's first suggestions to me was to use the expression library from Kawa. While it doesn't express an AST either, it does meet much of the criteria of what I'm looking for. However, it is really centered around providing support for Scheme in a JVM. I don't really know Scheme, and my first thought was that this would be something else I'd rather avoid learning (there's so much to learn these days - I have to be discriminatory). However, Andrae was quick to point out that it's a type of Lisp, and that I already have the basics in the lectures on "Structure and Interpretation of Computer Programs" (which I have the video files for). He also pointed out that given the Lisp heritage of OWL that I'd do well to learn Scheme. So I decided to pull the lectures back out, dust them off, and watch them right through (I'd only seen the first 4 before). It's not always easy to find the time, but I have to say that I enjoy watching them. Fortunately, I have a new iPod (yes, that involved some wrangling with Anne), so I've converted all the lectures over to it (courtesy of FFmpeg) and can watch it whenever I have a spare moment. It's just a shame that the battery can only handle a couple of hours of video. While discussing languages with Andrae, he mentioned Types and Computer Languages by Benjamin Pierce. I've always been impressed with Andrae's knowledge of the theoretical underpinnings of languages, and had put it down to extensive reading on the topic. This book is apparently one of the central sources for the information, so I'm thinking I'd like to read it. I went looking around the appropriate bookstores in Brisbane yesterday, and half of them did not even have access to a distributor for this book. When I finally found one, they told me it would take 6 weeks to come in from America, and would cost $185 AUD. Looking at Amazon, I'm able to purchase the book and its sequel for only about $165 AUD (and that's probably a similar shipping time). So I'd be buying the book from there, if it weren't for the fact that we're about to move! Would I ship the book here, to my in-laws near Melbourne (where I'll be working for a couple of weeks around Christmas), or to the office in Chicago? The visa paperwork is very frustrating. It would be nice to know when I'm moving for real. <sigh> In the meantime I'm reading Java Puzzlers in my Copious Free Time, and enjoying it thoroughly. It's the puzzles that I couldn't answer on my own that I enjoy the most. I've been bugging all my friends with them. :-) The best part is that it's finally encouraged me to read the JVM specification. Knowledge Mining Today I dropped into UQ for a short seminar by Osmar Zaiane, which he presented on Knowledge Mining. I'm glad I went, as it discussed several techniques of semantic extraction. In particular, it described the details of several methods based on Apriori. It also served to remind me about how much I really remember about neural networks (more than I care to admit), and that they're still considered the best solution to some classification problems. Perhaps I should revisit them. Some of these techniques, plus a few others that were mentioned, may help me to boost the level of semantic extraction I've been able to get so far at Herzum. I'll have to look into this area a little more. While at the university I dropped in a form to defer my enrolment for a couple of months. With the new job, the new baby, Christmas, and the impending move to Chicago, I figured I might be able to use a short break. Bob agreed that it sounds like a good idea. So I'm officially off until April, though I expect to be working on Kowari and OWL a little in the meantime. Posted by Paula G at Thursday, December 01, 2005 0
http://gearon.blogspot.com/2005_12_01_archive.html
CC-MAIN-2017-09
refinedweb
4,813
71.65
SYNOPSISAll the functions in this class are thread-safe when Qt is built with thread support.</p> #include <qmutex.h> Public Members QMutex ( bool recursive = FALSE ) virtual ~QMutex () void lock () void unlock () bool locked () bool tryLock () DESCRIPTIONThe QMutex class provides access serialization between threads. The. MEMBER FUNCTION DOCUMENTATION QMutex::QMutex ( bool recursive = FALSE )Constructs a new mutex. The mutex is created in an unlocked state. A recursive mutex is created if recursive is TRUE; a normal mutex is created if recursive is FALSE (the default). With a recursive mutex, a thread can lock the same mutex multiple times and it will not be unlocked until a corresponding number of unlock() calls have been made. QMutex::~QMutex () [virtual]Destroys the mutex. Warning: If you destroy a mutex that still holds a lock the resultant behavior is undefined. void QMutex::lock ()Attempt to lock the mutex. If another thread has locked the mutex then this call will block until that thread has unlocked it. See also unlock() and locked(). bool QMutex::locked ()Returns TRUE if the mutex is locked by another thread; otherwise returns FALSE. Warning: Due to differing implementations of recursive mutexes on various platforms, calling this function from the same thread that previously locked the mutex will return undefined results. See also lock() and unlock(). bool QMutex::tryLock ()Attempt to lock the mutex. If the lock was obtained, this function returns TRUE. If another thread has locked the mutex, this function returns FALSE, instead of waiting for the mutex to become available, i.e. it does not block. If the lock was obtained, the mutex must be unlocked with unlock() before another thread can successfully lock it. See also lock(), unlock(), and locked(). void QMutex::unlock ()Unlocks the mutex. Attempting to unlock a mutex in a different thread to the one that locked it results in an error. Unlocking a mutex that is not locked results in undefined behaviour (varies between different Operating Systems' thread implementations). See also lock() and locked().mutex.3qt) and the Qt version (3.3.8).
http://manpages.org/qmutex/3
CC-MAIN-2017-47
refinedweb
340
58.79
. using the first example I was wondering if I could expand it to calculate full mathematical expressions Are you talking about parsing and calculating the answers to arbitrary mathematical expressions? If so, I don't think you have all the tools that would be required for that. At the very least, I'd expect you'd need to know more about std::string and loops, which are covered in upcoming chapters. Ok thank you for telling me this Hello, Alex Thanks for this great tutorial! I have a stupid question. For the sake of clarification i want to ask. I understood what you gave explained above, but i have a question regarding to data types for floating point numbers. Can i use float data type instead of declaring float point numbers as a double and using Knuth's method. I do agree if i need more precision in case scientific calculation or which needs more precision. I am a new in C++. What is your advise? May be we should avoid using float data type other suggestion ? Below is given program, can be a example. #include<iostream> int main() { float d1(100-99.99); // should equal 0.01 float d2(10-9.99); // should equal 0.01 std::cout<<d1<<" "<<d2<<std::endl; if (d1 == d2) std::cout << "d1 == d2" << "\n"; else if (d1 > d2) std::cout << "d1 > d2" << "\n"; else if (d1 < d2) std::cout << "d1 < d2" << "\n"; return 0; } > Can i use float data type instead of declaring float point numbers as a double and using Knuth’s method No. Floats and doubles have the same limitations/problems with comparison operators. The only difference between floats and doubles is the range, precision, and size (in bytes). All other issues with floating point numbers are identical between floats and doubles. Personally, I favor double over float unless there's a specific reason to use float (e.g. the size is relevant for a given use case). i dont get what it means when you use "else if" multiple times, why dont you use "if"? whats the difference? If you use separate if statements, then the program will execute each one in turn. Multiple if statements may resolve to true. If you chain if-else statements together, then the program only execute the next if statement if the previous one was false. As soon as it finds one that is true, it will stop executing. Consider the difference between these two programs: [code] int x = 17; if (x > 20) // this is false std:cout < < "x > 20" < < '\n'; // so this doesn't print if (x > 10) // this is true std::cout < < "x > 10" < < '\n'; // so this prints if (x > 5) // this is also true std::cout < < "x > 5" < < '\n'; // so this prints [code] This program prints: x > 10 x > 5 If your goal is to select one and only one result, if-else is a better choice for two reasons: 1) It makes it clear that you're intending to select only one result 2) It's more efficient I understand. Thank you very much! i modified your code to see the output at the end only the main function....but it does not print anything:(:( [/code] int main() { // if the distance between a and b is less than epsilon, then a and b are "close enough" double a=12.0; double b=11.99; double epsilon=10; return fabs(a - b) <= epsilon; std::cout<<fabs(a-b); } Of course it doesn't -- you're returning before your code ever gets to the print statement. Here's what your program should look like: i think i have to pass the values for the bool isAlmostEqual() so the code would be modified like this.... if i am not mistaken [/code] #include <iostream> #include <cmath> // for fabs() int main() { bool isAlmostEqual(double a, double b, double epsilon) isAlmostEual(12.0,12.1,11.999); // if the distance between a and b is less than epsilon, then a and b are "close enough" return fabs(a - b) <= epsilon; } Error: C:\Users\maria\Desktop\c++\precision\main.cpp|11|error: 'a' was not declared in this scope| C:\Users\maria\Desktop\c++\precision\main.cpp|11|error: 'b' was not declared in this scope| C:\Users\maria\Desktop\c++\precision\main.cpp|11|error: 'epsilon' was not declared in this scope| i can't evaluate the problem plz help:( Yes, you need to pass in values for all three parameters (a, b, and epsilon). Your call to isAlmostEqual looks correct (minus the typo in the name), but your compiler is confused because you put the definition of function isAlmostEqual() in the wrong place. why do we need to compare it in the return function??? return fabs(a - b) <= epsilon; can't i do it in a different way bcoz it tried to compile ur same code and another question does epsilon holds a constant value in the library or we r passing any values from another file?? [/code] #include <iostream> bool isAlmostEqual(double a, double b, double epsilon) // if the distance between a and b is less than epsilon, then a and b are "close enough" return fabs(a - b) <= epsilon; } ERROR: C:\Users\maria\Desktop\c++\precision\main.cpp|10|error: a function-definition is not allowed here before 'return'| You don't need to do the comparison in the return statement -- you could do it on the line before, temporarily store the result, and return the temporarily stored result. But that just accomplishes the same purpose and doesn't really make your code any clearer for such a simple function and statement. Your problem here is that you're trying to put a function inside a function. You can't do that in C++. Put function isAlmostEqual() before function main() and you should be fine. Can Fabs Return Any No. Except for 1 or 0 ? I Think No because it is used in context with the relational operators and these operators dont return anything else except for true or false ? But whats the problem in Asking ! fabs() can return any double value. The relational operators themselves are what evaluate to true or false. While describing the example of "Comparison of floating point values", the values of d1(100 - 99.99) & d2(10 - 9.99) are shown as d1 = 0.0099999999999997868 and d2 = 0.0100000000000005116 But in my attempt to print I find the values as Precise value of d1: 0.010000000000005116 Precise value of d2: 0.0099999999999997868 This may also change the output of the example to -> " d1 > d2 " Thank you for your time. Yup, looks like I transposed the values. Thanks for bringing this up. I've fixed the example. I don't like Knuth's algorithm because it fails for a certain range of values; surely it's better to always use absolute epsilon but modify the epsilon based on the application it's being used for? I would intuitively think of 'close enough' as 'a certain number of decimal places are equal', not a small percentage difference (which is meaningless near to zero. I do believe there is a typo. "This program prints an unexpected result: d1 > d2" The ">" should be "<", because you go on to say that d1 is less than d2. Thanks for catching that! Fixed. why in donald knuth's algorithm we are multiplying (fabs(a)*epsilon) if 'a' is greater than 'b' and not (fabs(b)*epsilon) if 'a' is smaller than 'b'.from what i am getting is multiplying fabs(a) with epsilon i.e (fabs(a)*epsilon) we are trying to make interval even smaller and then comparing with the result of equation on the left handside.so the whole thing could also be written as something like: return fabs(a - b) <= (fabs(a) < fabs(b) ? fabs(b)*epsilon : fabs(a) * epsilon); please correct me if i am getting this wrong. Yes, all you've done is distribute the epsilon. Hey Alex! I made a similar 'close enough' program using Knuth's algorithm and every thing was working fine but I was curious to know the value of the epilson and I can't use debugger (I haven't figured it out in xcode of how to use the debugger). The program was : The value of epilson came out to be 4.94066e-324! Now 3 questions 1 Is this epilson default value ? 2 I use d1 and d2 values to be the same(-2), then how is the conditional statement suppose to work? 3 I also checked Smokeycow program and your reply to it so I thought shouldn't his version and knuth version work the same if both d1 and d2 values were to be same (say -2). Epsilon is something that needs to be set by you, based on how much tolerance you need. Your epsilon is uninitialized, which means whatever garbage was in the memory allocated to epsilon is now being interpreted as a double. That's why you're getting 4.94066e-324. Try initializing epsilon to something small, like 1.0e-12. wow man starting to lose hope with all the math examples. ): How much math do you think is needed for Isometric 2D games? > How much math do you think is needed for Isometric 2D games? Totally depends on what type of isometric game you're interested in creating. For a simple tile-based game, probably not so much. For a shooter or other physics-based game, probably a lot. Isometric games aside, you'll use relational operators in almost every program you write, so make sure you understand them. 🙂 Thnx Alex...:-) You said that the d1evaluates to 0.0099999999999997868 and d2 to 0.0100000000000005116 in the above program. But when I use cout to print the value of d1 and d2, the program gives me 0.01 as output for both variables. Please let me know if I m missing something. I m not sure but I think you missed your else statement in the following program: If the code is okay, then what will happen if the if's expression evaluates to true. Yes..it will return true. But what after that. Does the compiler then Ignores the line 10 where we are returning Knuth's method. std::cout prints variables to 6 significant digits by default. You can see their actual values by using std::setprecision() to ask std::cout to show more precision, or by looking at them in a debugger. There's no need for an else statement in approximatelyEqualAbsRel. If the return statement is executed, the function returns a value to the caller right then and there, and the rest of the function does not execute. So effectively, everything after the if statement is essentially the else case, just implicitly. I'm trying to fully understand what is going on with both the fabs() function call and the way it works in Knuth's "close enough" bool function. It didn't seem clear why a fabs() call is necessary so many times so I removed them from the conditional operator statement where they did not seem needed ( to me at least! ) and ended up with this: My own version appeared to work fine until I changed the double values a and b to a negative decimal. If I do this and run the program it returns an incorrect bool value of false in a program where variables a and b are both the same. Knuth's version has no such problem and returns the correct value of true when using a negative decimal. I believe the problem to be my understanding of the fag() function call but I could be completely wrong! If you could shed some light on this that would be great. Nice investigative work. You almost reached the conclusion yourself. fabs() returns the absolute value of its parameter. Knuth's algorithm doesn't care whether the numbers are negative or positive -- it only cares how large they are (in terms of absolute value). Your version only considers which value is greater. Consider the case where a = -50 and b = 2. Knuth's version uses 50 * epsilon (because a has a magnitude of 50), whereas your version uses 2 * epsilon (because b is greater than -50). This makes your algorithm incorrect, because a clearly has a greater magnitude than b in this case. Essentially, Knuth's algorithm uses fabs() to handle both positive and negative numbers. I still dont get it, why we have to take: Thanks in advance... Thank u i'll surely go through all the previous tutorials. Thanks got it. one question are my questions too preliminary level ? still , Thanks. A lot of the stuff you've been asking has been covered in previous lessons. For example, the above question of yours was covered in section 1.7 -- Forward declarations. But there's so much to learn, I'm not surprised it doesn't all stick. I'd definitely recommend re-reading through the old lessons again just to make sure you're comprehending everything. In my compiler "Dev C++" the above programs aren't compiling giving an error In function 'int main()': [Error] 'approximatelyEqual' was not declared in this scope [Error] 'approximatelyEqualAbsRel' was not declared in this scope recipe for target 'Untitled5.o' failed What must have gone wrong? Did you copy the code for approximatelyEqual() and approximatelyEqualAbsRel() into your code file? If so, are they above main()? Here’s an alternative function I've come up with: Not sure if that's more/less efficient, but it's lightweight and easier to read if you're not good with math. Apparently editing comments breaks code formatting - Sorry that I posted and deleted this several times. It would also appear that I made an error in the above code, this should be correct: Notice that the function as incorrectly labeled was double rather than bool. A note to all comment readers: All comments above this point refer to an old example, which was slightly inferior to the one now in place. Happy learning! Knuth's version introduces an error with significant digits when dX > 1, so I've updated the code to correct the error. I also noticed my first attempt introduced a new error for dX < 1, so set it to an if statement so it only applies the fix if dX > 1, solving both issues. =3 I'd highly recommend always using the updated code over Knuth's, as Knuth's will invariably cause issues for almost any dX > 1, often returning incorrect answers due to (dEpsilon * fabs(dX)) introducing extra significant digits when unintended. I'm a little iffy on if dX++ would work or not; it's not needed in this case, so I left it out rather than risk having dX++ be applied twice and affecting both instances of dX. Safer to just flat out tell it exactly what's to be added in this case than trying to automate it.; do not use dX++ due to risk of doubling the effect else return fabs(dX - dY) <= dEpsilon * fabs(dX); // runs if no <1 errors would occur } I keep thinking about this thing, and keep coming up with more errors. If dY is a negative number, but still small, between but not equal to 0 and -1, it breaks anyway. Any negative numbers break regardless, but the >-1 <0 range is a pain since I can't think of a way to get around it yet. At least not fully, anyway, not without introducing another error. I can fix numbers <-1 but not in that little gap... seriously need to think on this some more. I've been thoroughly nerd sniped, boo. =P I'm going to dig through some of the previous lessons again, since I think there's a function in there that may help me solve the problem. I, of course, would not mind if anyone else picks at it some. =P For reference, the issues come down largely to dealing with (dX - dY) having problems with negative numbers (semi-easily fixed), but especially breaking down if dX is close to dY and positive, but dY is negative. Application of fabs() seemed like the obvious fix, but it breaks because it would think 0.999 == -0.999, which... clearly isn't the case. Maybe I'm just too tired to think about it anymore. Time for bed, I'll worry about it tomorrow and maybe dream up something overnight to fix it. Or just forget the problem exists entirely. I'd rather not, though. It bothers me greatly that I *KNOW* there's a bug in the program, but that I don't know how to fix it. XD this is probably a silly question, but i keep reading this thinking i'm missing something really obvious. when you use maths in your program, after some point 2+2 will no longer equal 4? .. i like to think of a computer as a pretty dependable calculator, so this discussion of two numbers being "close enough" within a margin of 1% is blowing my mind. Yeah, it's pretty trippy. Integer 2 + 2 will always = 4. Floating point 2.0 + 2.0 may or may not = 4.0. It really all comes down to the way the numbers are stored internally. Integers always store precise values. Floating point numbers trade some precision for a much greater range. Please can anyone specify why we multiply dEpsilon with dX? What is the purpose? Thanks. Note: Even if you see this message has been sent out quiet long time ago, your answer will be ok for me. bool IsEqual(double dX, double dY) { const double dEpsilon = 0.000001; // or some other small number return fabs(dX - dY) <= dEpsilon * fabs(dX); } The idea behind the function is simple as we look at it geometrically. The module of |dX - dY| represents the units between the two numbers, in other words it is an interval of numbers, which shows us how far away the two numbers are (real numbers and their representation on the real axis). This comes directly from calculus, if we multiply epsilon, a very small number with the module of dX we make the interval of dX even smaller, assuming dX is the number with higher value, hence we see if |dX - dY| is an interval so small, that it "fits" somewhere in dEpsilon * |dX|. If it does, it means the two numbers are very close since epsilon can be as small as we want it, even if they are not equal. What you have to understand is the idea behind the module and its geometric use. If |dX - dY| are indeed very close, by substracting them we get a very small interval. Guys, I'll tell you what I think, if I may. The function that Knuth made has one problem to my mind: it takes only the first value passed in into consideration when calculating the relative distance between the variables. As a mathematician, I think it should take both of them but - attention! - instead of using (x+y) it should make use of max(|x|,|y|). Therefore, you look for this piece of code, I believe: By the way, I'm sure there must be some kind of max function in C++ but don't know in which library. I have not analysed the function thoroughly as it should be but I think it's the best version so far. Will gladly see a better one. This seems to be best function. I think there is max function somewhere nearby, probabaly in stdlib.h but it can be easily written off: You may have missed a bracket pair in Knuth's algorithm above. What you have written is equivalent to that code - but perhaps more readable. I find it very curious that "absolute value" is a function in the standard library, but not a built-in operator in C++. You would think that the (otherwise useless) unary "+" operator would be assigned as the operator for the absolute value function. In other words, it seems logical that the expression +(x - y) should evaluate to the absolute value of (x - y). In any case Alex, I think it would be better to introduce the absolute value function in section 3.2 with the Operators. Keep up the good work. + doesn't absolute value things in normal mathematics. For example, if x = -3, then +x = -3, not 3. C++ turning the unary plus operator into an absolute value operator would diverge from common mathematics. What I find weird is the lack of an exponent operator. Who made _that_ decision? 🙂 I dont get it. If we have this for example And we test with x=20.111 and y=20.1101 (close enought) we get this: that equals true. But lets use smaller numbers, that are close to each other as on the first example: x=0.001, y=0.0001, we get this: that equals false. For me personaly, in both examples the numbers are satisfying close. If i would need to compare two close floating point values, i would go for this: If i need more precission i would increase the nFloatPPrecis depending on how much digits i would need. What do you think? The issue honestly seems to be that when you're using numbers lower than 1, any time you multiply them against the dEpsilon value, you're also adding in extra significant digits that shouldn't be there. In your examples above, here's what I see: 20.001-20.0001 <= 0.0001*20.001 0.0009 <= 0.0020001<!--formatted--> You start with two numbers with 5 and 6 significant digits. It evaluates to 5 significant digits. The 0.0001*20.001 returns 0.0020001 which is quite a few extra significant digits in theory, but in practice it's honestly really only important out to 0.002; the remainder is irrelevant. In the latter example of: 0.001-0.0001 <= 0.0001*0.001 0.0009 <= 0.0000001<!--formatted--> You start with two numbers with 4 and 5 significant digits. The comparison function, due to multiplying a number below 1 with another below 1 means you increased it to 0.0000001, or 7 significant digits. As such, the accuracy is now greater than the numbers you started with. To correct this issue, all you'd have to do is rewrite it like this: bool IsEqual(double dX, double dY) { const double dEpsilon = 0.000001; // or some other small number return fabs((dX+1) - (dY+1)) <= dEpsilon * fabs((dX+1)); } I was going to use ++ instead of +1, but then realized that could cause issues if dX is evaluated twice with ++ which would break the equation. Same dealie with only having ++ on one side; dX++ - dY++ doesn't work either if you don't include fabs(dX++), and the reverse also causes issues, so the (+1) will have to apply. What this means now, though, is that you get: 1.001-1.0001 <= 0.0001*1.001 0.0009 <= 0.0001001<!--formatted--> The left side remains exactly the same, and the right side retains 4 significant digits of actual value, where it basically ends at 0.0001. This method ensures that, for numbers less than 1, dEpsilon will always resolve to the same number of significant digits. Yes, there's the 0.0001(001) tacked onto the end, but the important part is the 4th significant digit which will always be what matters when comparing two numbers that are below 1. As such, dEpsilon resolves to whatever you tell it to without adding erroneous extra significant digits. In this case, it returns false because the error rate is larger than the 4 significant digits requested by dEpsilon, not because you accidentally added more significant digits by multiplying 0.1 by 0.1 and getting 0.01. The original code by Donald Knuth works just fine but bugs out as soon as you get to any value below 1 because multiplying values less than 1 is the same as dividing numbers larger than 1. However, this introduces a problem where a dX value greater than 1 introduces inaccuracy. As such, the following is my updated version which only removes the <1 error if it occurs, and doesn't mess with anything otherwise. else return fabs(dX - dY) <= dEpsilon * fabs(dX); // runs if no <1 errors would occur } Gawd, it took me like 30 seconds to figure out how to fix the problem and over an hour trying to test the code because I couldn't figure out how to read the return from the bool again. I don't really understand what is happening with fabs(). For example if dX = 2 and dY = 3 how would I figure what the result of fabs(dX), or fabs(dX - dY) would/should be. The sentence that states that fabs() is a function that returns the absolute value of it’s double parameter leads me to believe that dX would evaluate to 4 and dY to 6 in this case, but when compiled and ran with the above values and sending fabs(dX) or fabs(dY) to the screen using cout I get whatever the value of dX or dY was to begin with. When doing the same with fabs(dX - dY) however I get a value of 1, which would be the same as (dX - dY) anyway. (scratches head) Heh, that's not what he meant. 🙂 The double parameter he was referring to was the double float point variable that is provided to fabs as a parameter. So fabs doesn't return double the value put into it, it just returns the absolute value of the number sent to it. You can think of fabs doing something similar to this, though this is REALLY simplified: And remember, when you're using functions, the mathematical expressions inside their parameters are evaluated before the function call is, for example using "fabs(-4 - 6)" is the same as "fabs(-10)". If a float is generally accurate to 7 decimal places, and a double is at 16, if I were working with figures with 2 or 4 decimal places, would the accuracy ever really be an issue? For example, would I see something like (.0095 * 36.75) > 34.90 equate to false since it uses less than the 7 decimals that floats tend to be accurate to? A float is not accurate to 7 decimal places. A float is accurate to approximately 7 significant digits. A significant digits is any digit that is not a placeholder 0, including ones on the left side of the decimal. For example, .0095 has two placeholder zeros, and so is only 2 significant figures. 34.90 has 4 significant figures. There are two types of errors we need to watch out for with floating point values: rounding errors, and precision errors. Rounding errors can happen with numbers of any length, because some numbers have infinite representations in binary (0.1 for example), and those representations will be truncated. Rounding errors typically make your answer wrong by 0.000001, or some small number like that. The second and more potentially serious error are precision errors, where your number can't be stored because the floating point representation doesn't have enough memory. Precision errors are more serious because they can affect your answer by a much larger degree of magnitude than rounding errors. 0.0095 * 36.75 = 0.349125, which is 6 significant figures, so in this case, you'll probably be fine in terms of precision errors. Consequently, your answer will only be affected by small rounding errors. But consider a case like: 0.0095 * 36.7513. Even though 36.7513 is 4 decimal places, it's 6 significant digits. When multiplied by 0.0095, the answer is 0.34913735. A float will truncate this to 0.349137. Once you get into larger dollar amounts, floats are even less suitable. Consider $100264.75. This is a number with 8 significant digits, even though it only uses 2 decimal places. Already a float is not going to be able to hold this number. As you do mathematical operations on it, it's going to drift farther and farther from your intended answer. In short, if accuracy is important, use double. Only use floats when accuracy is not that important (eg. in games, where it doesn't really matter if your character has 137.24 or 137.25 strength). doesn't 34.90 have 3 significant digits? I know math teachers usually say that the last zeros don't matter after a decimal, but when you're talking about precision they do. In sciences when you're taking measurements a .39 may be the same value as .3900000 mathematically speaking, but the latter is more precise to 7 significant figures. With the .39 value you cannot be assured the number in the thousandths place is 0. No,... 34.90 has 4 significant figures. 3.94 has 3 significant figures 03.94 has 3 significant figures .00000000394 = 3.94 E-9 has 3 significant figures But 34.90 only has 3 significant figures; especially since 34.90 = 34.9 In terms of value, 34.90 is the same as 34.9. We're used to dropping trailing zeros when dealing with values. However, in terms of precision, 34.9 is less precise than 34.90. If I tell you that I walked "34.9 miles", maybe I walked 34.85 miles and rounded up, or 34.94 miles and rounded down. But if I tell you I walked "34.90 miles", you know I walked somewhere between 34.895 and 34.904, and that provides more accuracy. The other posters are correct: 34.90 has 4 significant digits. I talk about significant digits in lesson 2.5 -- Floating point numbers. Name (required) Website
http://www.learncpp.com/cpp-tutorial/35-relational-operators-comparisons/comment-page-1/
CC-MAIN-2018-13
refinedweb
4,992
73.27
Segmenting Data by Application or Customer. This tutorial shows you how to segment data using Zones. Consider the following scenarios where segmenting data by application or customer may be necessary: - A database serving multiple applications - A database serving multiple customers - A database that requires isolating ranges or subsets of application or customer data - A database that requires resource allocation for ranges or subsets of application or customer data This diagram illustrates a sharded cluster using zones to segment data based on application or customer. This allows for data to be isolated to specific shards. Additionally, each shard can have specific hardware allocated to fit the performance requirement of the data stored on that shard. Scenario¶ An application tracks the score of a user along with a client field, storing scores in the gamify database under the users collection. Each possible value of client requires its own zone to allow for data segmentation. It also allows the administrator to optimize the hardware for each shard associated to a client for performance and cost. The following documents represent a partial view of two users: Architecture¶ The application requires adding shard to a zone associated to a specific client. The sharded cluster deployment currently consists of four shards. Zones¶ For this application, there are two client zones. - Robot client (“robot”) - This zone represents all documents where client : robot. - FruitOS client (“fruitos”) - This zone represents all documents where client : fruitos. Write Operations¶ With zones, if an inserted or updated document matches a configured zone, it can only be written to a shard inside that zone. MongoDB can write documents that do not match a configured zone to any shard in the cluster. Read Operations¶ MongoDB can route queries to a specific shard if the query includes at least the client field. For example, MongoDB can attempt a targeted read operation on the following query: Queries without the client field perform broadcast operations. Balancer¶ The balancer migrates chunks to the appropriate shard respecting any configured zones. Until the migration, shards may contain chunks that violate configured zones. Once balancing completes, shards should only contain chunks whose ranges do not violate its assigned zones. Adding or removing zones or zone ranges can result in chunk migrations. Depending on the size of your data set and the number of chunks a zone or zone range affects, these migrations may impact cluster performance. Consider running your balancer during specific scheduled windows. See Schedule the Balancing Window for a tutorial on how to set a scheduling window. Security¶ For sharded clusters running with Role-Based Access Control, authenticate as a user with at least the clusterManager role on the admin database. Procedure¶ You must be connected to a mongos associated to the target sharded cluster to proceed. You cannot create zones or zone ranges by connecting directly to a shard. Disable the Balancer¶ The balancer must be disabled on the collection to ensure no migrations take place while configuring the new zones. Use sh.disableBalancing(), specifying the namespace of the collection, to stop the balancer.. Run sh.status() to review the zone configured for the sharded cluster. Define ranges for each zone¶ Define range for the robot client and associate it to the robot zone using the sh.addTagRange() method. This method requires: - The full namespace of the target collection - The inclusive lower bound of the range - The exclusive upper bound of the range - The name of the zone Define range for the fruitos client and associate it to the fruitos zone using the sh.addTagRange() method. This method requires: - The full namespace of the target collection - The inclusive lower bound of the range - The exclusive upper bound of the range - The name of the zone The MinKey and MaxKey values are reserved special values for comparisons. MinKey always compares as lower than every other possible value, while MaxKey always compares as higher than every other possible value. The configured ranges captures every user for each client. Enable the Balancer¶ Re-enable the balancer to rebalance the cluster. Use sh.enableBalancing(), specifying the namespace of the collection, to start the balancer. Use sh.isBalancerRunning() to check if the balancer process is currently running. Review the changes¶ The next time the balancer runs, it splits and migrates chunks across the shards respecting the configured zones. Once balancing finishes, the shards in the robot zone only contain documents with client : robot, while shards in the fruitos zone only contain documents with client : fruitos. You can confirm the chunk distribution by running sh.status().
https://docs.mongodb.com/v3.6/tutorial/sharding-segmenting-shards/
CC-MAIN-2021-43
refinedweb
752
53.1
I am an absolute newbie in the field of web scraping and right now I want to extract visible text from a web page. I found a piece of code online : import urllib2 from bs4 import BeautifulSoup url = "" web_page = urllib2.urlopen(url) soup = BeautifulSoup(url , "lxml") print (soup.prettify()) /usr/local/lib/python2.7/site-packages/bs4/__init__.py:282: UserWarning: "" looks like a URL. Beautiful Soup is not an HTTP client. You should probably use an HTTP client like requests to get the document behind the URL, and feed that document to Beautiful Soup. ' that document to Beautiful Soup.' % decoded_markup <html> <body> <p> </p> </body> </html> Try passing the html document and not url to prettify to: import urllib2 from bs4 import BeautifulSoup url = "" web_page = urllib2.urlopen(url) soup = BeautifulSoup(web_page , 'html.parser') print (soup.prettify())
https://codedump.io/share/qBOsR0i9ZG0a/1/scraping-visible-text
CC-MAIN-2016-50
refinedweb
137
51.04
Twelve days ago, we took our first step into linked open data. Since then we’ve received much great feedback on how best to improve our Linked Data Service. Based on this feedback, we are making several changes to the structure of our linked data documents. The first change you’ll notice is that each document now contains two resources. The reason for this is as follows. Lets pretend we have a resource with the URI that is served from a file named. In our original release this document contained a single resource. Since we attached licensing information to this resource and declared it to be owl:sameAs external resources, an inference engine could conclude that The New York Times was asserting ownership and license terms over data that didn’t belong to us. Since it was never our intention to do anything of this sort, we have revised our documents to contain two resources. The document now contains resources and. Licensing information is now attached to the resource ending in “.rdf” and owl:sameAs assertions are made in the resource. To make clear the relation between these two resources, the resource ending in “.rdf” is asserted have foaf:primaryTopic “ foo.” We believe that this approach both avoids unwanted propagation of license terms yet preserves the clarity of the license information. So that’s the big change. We have also made several smaller updates. 1. The predicates 'time:start' and 'time:end' have been replaced with 'nyt:first_use' and 'nyt:last_use' respectively. The intent of the 'time:[start|end]' triples was to express the time a subject heading was first and last used in the Times. Unfortunately, these triples were ambiguous, so we have decided to extend the 'time:[start|end]' predicate with our own predicates which we will define to have the above semantics. 2. The 'nyt:topicPage', 'cc:attributionURL', and 'cc:license' triples now refer to resource URIs , rather than literal URLs. 3. The incorrectly stated 'cc:Attribution' predicate has been replaced with the correct 'cc:attributionURL' predicate. 4. The incorrectly stated 'cc:License' predicate has been replaced with the correct 'cc:license' predicate. (capitalization) 5. We have resolved issues with content negotiation on our server. 6. An XML declaration was added to the top of the rdf documents. 7. The freebase namespace declaration 'xmlns:fb="http:// rdf.freebase.com/ns/"' was removed from the RDF declaration as it is not used in any statements contained in our document. 8. Freebase resources are now linked using the URI structure rather than. This URI structure permits freebase’s servers to perform content negotiation on the requested URI, leading to a better user experience for human readers. 9. We have added a “dcterms:modified” triple to the resource that indicates the time at which the resource was last updated. 10. Creative Commons branding has been added to the HTML renderings of our resources. So these are today’s changes, but there are several more updates still in the pipeline. These include: 1. New York Times namespace documentation 2. More mappings from subject headings to dbpedia and freebase. 3. Sample applications of data. Almost every change announced today is the result of community feedback. We really mean it when we say that we appreciate and value your comments, criticisms and suggestions. So please, keep them coming. Thanks Ivan -- Ivan Herman Bankrashof 108, 1183NW Amstelveen, The Netherlands tel: +31-641044153; URL: - the class specification has to be on the top level and not as a child of owl:Ontology (this led to syntax errors with parsers) - the usage of rdf:ID was incorrect; indeed, the default namespace does not apply to the value of rdf:ID - the namespace used in nytd2.rdf was not the same as the ontology URI But these are mini issues. Once these were handled (I attach the files as I used them) it works. The nice thing is that OWL 2 RL (ie, the rule engine profile of OWL) also applies to this solution. Ie, running the two files through my OWLRL reasoner (there is an online service at [1]) you do get triples like: <> a <> "The New York Times Company"^^xsd:string, <> ; <> "The New York Times Company"^^xsd:string ; <> "2009-11-11"^^xsd:date ; <> "The New York Times Company"^^xsd:string ; .... which is what you wanted. And I would expect such RL based reasoners to come to the fore more. That being said, I am not sure that the 'modified' date should be part of NYTimesDescription class. This looks like something much more malleable than the rest. But I may be wrong. Cheers Ivan [1] > er...@hellman.net <mailto:ope...@gmail.com> Richard Cyganiak wrote.+1 As much as I like OWL, reasoning simply cannot be a pre-requisite for publishing Linked Data. Reasoning is a subjective act, and there are other ways of injecting OWL into the mix, unobtrusively. This is ultimately what makes the RDF data model so powerful i.e. Schema comes last, and from a perspective of the Linked Data beholder (consumer). You cannot model data perfectly for cognitive beings, that's just the way it is -- we are all wired to see the same things differently :-) KingsleyBest,Richard -- Regards, Kingsley Idehen Weblog: President & CEO OpenLink Software Web:. Best, Richard Eric Hellman wrote:Interesting perspective.In your scenario, is there any way that any end user or participant in the linked data distribution chain would see licensing or attribution data?Yes, by de-referencing the HTTP URI associated with the License Data Item (which would be associated with the RDF doc via a triple), that's the beauty of Creative Commons Licenses, they have URIs [1] :-) Links: 1. 2. Kingsley On 18 Nov 2009, at 21:55, Eric Hellman wrote:But in the current form of the data, the licensing and attribution is "hidden" by the need to dereference the ".rdf" URI's; otherwise there is no way to know what triples are covered by the license and attribution. I don't get your point. If you want to use the data, you have to dereference the .rdf URI anyway, because that's how you get the data. You get the license packaged along with the data. In what way is this “hiding” the license? Richard
https://groups.google.com/g/nyt_linked_open_data/c/Yp1WH-qc3CU
CC-MAIN-2021-43
refinedweb
1,044
64.91
NAME round, roundf, roundl - round to nearest integer, away from zero SYNOPSIS #include <math.h> double round(double x); float roundf(float x); long double roundl(long double x); double round(double x); float roundf(float x); long double roundl(long double x); Link with -lm. Feature Test Macro Requirements for glibc (see feature_test_macros(7)): round(), roundf(), roundl(): _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE; or cc -std=c99 DESCRIPTION. RETURNround(3) instead. SEE ALSO ceil(3), floor(3), lround(3), nearbyint(3), rint(3), trunc(3) COLOPHON This page is part of release 3.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
https://linux.fm4dd.com/en/man3/round.htm
CC-MAIN-2021-49
refinedweb
112
64
MenuBar size Hi all, I'm very new in Qt and I do not work with Qt, I would like only to learn for fun, but I have almost no time to research about my doubts (I have only some minutes per day) and my test program is progressing very slow. In order to increase developing speed I will ask some questions here. First, I would like to know how can I adjust width of a menu bar according the form size that this menu bar is inside. Does anybody could help me? Thanks in advance, Hcts - Hareen Laks I'm also new one to Qt. According to my knowledge I think by default menubar width is set to the form width. isn't it? Hi hcts! Show us your code. The tool bar is adjustable by the minimumSize option etc. The icons, or text in the toolbar determine the size of the toolbar. Greetz oh, sorry, My mistake, you discussed the menuBar!! The menuBar size is changeable with the font point size for example. The menuBar is resized with the contents just like the toolbar. Icons or text size determine the size of it. Greetz Hi, Thanks for all answers. I'm creating the QMenuBar at runtime, like this: QMenuBar MenuObject = new QMenuBar(this); HeaderArea->addWidget(MenuObject); where HeaderArea is QHLayoutBox. Regards, Hcts Oke, the size of the QMenuBar can be set runtime, no problem, but if the answers where enough, mark this post as [SOLVED] Hi, How can I do that a t runtime, could give me an example? Regards, Hcts Hi all, It seems that the QMenuBar width is by default according to parent widget size. My problem was that the QMenu inside the QMenuBar was in a different color in comparison of QMenuBar and QWidget. QMenu was gray and QWidget and QMenuBar were white. The result of this is that the QMenuBar finished at the middle of parent QWidget. The code below shows the QMenuBar using all parent QWidget size as your own size, when the size of widget is changed by the user, QMenuBar size change too. #include <QtGui/QApplication> #include <QMenuBar> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *x = new QWidget(); x->setGeometry(30,30,600,600); QMenuBar * q = new QMenuBar(x); q->addMenu("Test"); q->setStyleSheet("background-color: white"); x->show(); return app.exec(); } So, my problem is solved only changing the color of QMenu. Thanks
https://forum.qt.io/topic/27730/menubar-size
CC-MAIN-2018-13
refinedweb
407
79.9
Python Screening Interview question for DataScientists Julien Kervizic Originally published at Medium on ・6 min read Python Screening Interview questions for DataScientists DataScience requires an interdisciplinary set of skills, from handling databases, to running statistical model, to setting up business cases and programming itself. More often than not technical interviews for data-scientists assess more the knowledge of specific data manipulation APIs such as pandas, sklearn or spark, rather than a programming way of thinking. While I think that a knowledge of the more “applied” APIs is something that should be tested when hiring data-scientist, so is the knowledge of more traditional programming. String Reversal & Palindrome String reversal questions can provide some information as to how well, certain candidates have been with dealing with text in python and at handling basic operations. Question 1 : Question: Reverse the String “ “the fox jumps over the lazy dog” Answer: a = "the fox jumps over the lazy dog" a[::-1] or ''.join(x for x in reversed(a)) [less efficient] or ''.join(a[-x] for x in range(1, len(a)+1)) [less efficient] Assessment: - This is more of a warmup question than anything else and while it is good to know the shortcut notation, especially as it denotes some knowledge of how python deals with strings (eg substr a[0:7] for the fox) it is not necessary for most data-science’s purpose Question 2: Question : identity all words that are palindromes in the following sentence “Lol, this is a gag, I didn’t laugh so much in a long time” Answer: def isPalindrome(word: str) -\> bool: if(word == word[::-1]): return True return False def getPalindromesFromStr(inputStr: str) -\> list: cleanStr = inputStr.replace(",","").lower() words = set(cleanStr.split(" ")) wPalindromes = [ word for word in words if isPalindrome(word) and word != "" ] return wPalindromes getPalindromesFromStr(“Lol, this is a gag, I didn’t laugh so much in a long time”) Assessment: - Does the candidate thinks about cleaning his/her inputs? - Does the candidate know the basic or word processing in python such as replace / split / lower? - Does the candidate know how to use list comprehension? - How does the candidate structure his/her code? FizzBuzz FizzBuzz is a traditional programming screening question, that allows to test if a candidate can think through a problem that is not a simple if else statement. The approach that they take can also shed some light to their understanding of the language. Question: Write a program that prints the number for 1 to 50, for number multiple of 2 print fizz instead of a number, for numbers multiple of 3 print buzz, for numbers which are multiple of both 2 and 3 fizzbuzz. Answer: def fizzbuzzfn(num) -\> str: mod\_2 = (num % 2 == 0) mod\_3 = (num % 3 == 0) if (mod\_2 or mod\_3): return (mod\_2 \* 'Fizz') + (mod\_3 \* 'Buzz') return str(num) print('\n'.join([fizzbuzzfn(x) for x in range(1,51)])) Assessment: - Do they know the modulo operator and are able to apply it? - Are they storing the result of the modulo operators in variables for re-use? - Do they understand how True/False interact with a String? - Are they bombarding their code with if statements? - Do they return a consistent type or mix both integer and string? First Duplicate word First finding of duplicate word allows to identity if candidates know the basic of text processing in python as well as are able to handle some basic data structure. Question 1 Question: Given a string find the first duplicate word, example string: “this is just a wonder, wonder why do I have this in mind” Answer: string = "this is just a wonder, wonder why do I have this in mind" def firstduplicate(string: str) -\> str: import re cleanStr = re.sub("[^a-zA-Z -]", "", string) words = cleanStr.lower().split(" ") seen\_words = set() for word in words: if word in seen\_words: return word else: seen\_words.add(word) return None firstduplicate(string) Assessment: - Do I have constraint I need to work with, for instance in terms of memory? - Cleans the string from punctuation? Replace or Regexp? If use regexp replace, should I compile the regexp expression or used it directly? - Knows the right data-structure to check for existence. - Does it terminate the function as soon as the match is found or? Question 2: Question: What if we wanted to find the first word with more than 2 duplicates in a string? Answer: string = "this is just a wonder, wonder why do I have this in mind. This is all that matters." def first2timesduplicate(string: str) -\> str: import re cleanStr = re.sub("[^a-zA-Z -]", "", string) words = cleanStr.lower().split(" ") seen\_words = dict() for word in words: previous\_count = seen\_words.get(word, 0) seen\_words[word] = previous\_count + 1 if previous\_count \>= 2: return word return None first2timesduplicate(string) Assessment: - Some small modification is needed to be able to accommodate that change, the main one is arising from the use of a dictionary data-structure rather than a set. Counters are also a valid data-structure for this use case. - There is little difficulty on modifying the previous function to cope with this change request, it is worth checking that the candidate does instantiate the specific key correctly, taking into account default values. Quick Fire questions Some quick fire questions can also be asked to test the general knowledge of the python language. Question 1: Question: Replicate the sum for any number of variables, eg sum(1,2,3,4,5..) Answer def sum(\*args): val = 0 for arg in args: val += arg return val Assessment: - Quick interview question to check the knowledge of variable arguments, and how to setup one of the most basic functions. Question 2: Questions around the Fibonacci series is a classic of programming interviews and candidates should in general be at least familiar with them. They allow to test recursive thinking. Question: Fibonacci sequences are defined as follow: F\_0 = 0 ; F\_1 = 1 F\_n = F\_{-1} + F\_{-2} Write a function that gives the sum of all fibonacci numbers from 0 to n. Answer: def fibonacci(n: int) -\> int: # fib series don't exist \< 0 # might want to throw an error or a null # for that if n \<= 0: return 0 if n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def naiveFibSum(n: int) -\> int: return sum([fibonacci(x) for x in range(0, n+1)]) def sumFib(n: int) -\> int: return fibonacci(n + 2) -1 Assessment: - First, is the candidate able to think recursively? - Is the candidate only thinking about a naive solution to the sum of fibonacci series or is s/he understanding that it can also summarized to a in a more effective way? Wrap up These questions are just meant to be a first screener for data-scientist and should be combined with statistical and data manipulation types of questions. They are meant to give a quick glimpse on whether a candidate has the basic minimum knowledge to go through a full interview rounds. More advanced programming questions for Python would tend to cover the use of generators, decorators, cython or the efficient use of libraries such as pandas/numpy. More from me on Hacking Analytics: - SQL interview Questions For Aspiring Data Scientist — The Histogram - Become a Pro at Pandas, Python’s data manipulation Library - E-commerce Analysis: Data-Structures and Applications - Setting up Airflow on Azure & connecting to MS SQL Server - 3 simple rules to build machine learning Models that add value Python coders, what are some exercises/activities that help you quickly get better at the basic coding?
https://practicaldev-herokuapp-com.global.ssl.fastly.net/julienkervizic/python-screening-interview-question-for-datascientists-30g4
CC-MAIN-2020-05
refinedweb
1,273
57.71
Up to [DragonFly] / src / lib / libkvm Request diff between arbitrary revisions Keyword substitution: kv Default branch: MAIN Don't forget to set internal error message in kvm_nlist(). Obtained-from: FreeBSD Some trivial changes from FreeBSD that allow to use kgdb on /dev/fwmem0.0. It also fixes an obvious typo (vmfd -> pmfd). Dragonfly-bug: <> Submitted-by: Aggelos Economopoulos <aoiko@cc.ece.ntua.gr> Obtained-from: FreeBSD When <sys/user.h> is included, it MUST be included first because it sets a preprocessor variable that effects other header files. Change kinfo_proc interface between kernel and userland. Before, we were embedding a struct proc (among others) into struct kinfo_proc. Every time we change implementation details in the kernel, userland has to be adapted (recompiled). In preparation for the coming LWP changes this interface has been reworked. Now kinfo_proc is a structure which does not depend on other structures on the kernel which are subject to change. Instead, the routines fill_kinfo_proc and fill_kinfo_lwp copy all values which are of interest between the kernel structure and the stable kinfo_proc structure. Furthermore, this change adds infrastructure to export LWP-specific data. If userland requests LWP data, it sets the flag KERN_PROC_FLAG_LWP in the sysctl oid. This leads to multiple kinfo_procs being exported. If not set, the first LWP will used. This is like FreeBSD do it, and it seems easy and simple. Note that userland was not yet adjusted to actually request LWPs and aggregate this information if necessary. Besides, the kernel does not yet have more than one LWP per process anyways. This introduces a new file, kern/kern_kinfo.c, which is shared between kernel and libkvm. This was done to avoid and remove code duplication. Now kvm_getprocs constructs a complete struct proc, including pointers, and then calls fill_kinfo_proc to do its job. In-collaboration-with: Thomas E. Spanjaard <tgen@netphreax.net> Add kvm_readstr, a convenience helper which lets you read C strings from kernel cores/kmem.@meinberlikomm.de> lvalue cast. Style(9) cleanup. - Convert K&R-style function definitions to ANSI style. - Remove `register' keywords. - Use stdarg.h instead of varargs.h for variable numbers of arguments. - #define _KERNEL_STRUCTURES when accessing kernel structures. - No functional changes. * Removed the __P macros from lib/ * Small fixups by me in lib/libcr, there was some stale ')' after the __P( was removed from the line above. Submitted-by: Craig Dooley <craig@xlnx-x.net> Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most ids have been removed from !lint sections and moved into comment sections. import from FreeBSD RELENG_4 1.12.2.3
http://www.dragonflybsd.org/cvsweb/src/lib/libkvm/kvm.c?f=h
CC-MAIN-2015-32
refinedweb
432
60.92
Getting started with COLLADA Here's some information to help if you are getting started with COLLADA. - Read the COLLADA FAQ to get a good overview. - If you want to know more about the goals, design fundamentals, and detailed information about the 1.4.x features, get a copy of the COLLADA book from AK Peters, or any other bookseller or library. - Ignore anything prior to 1.4.x. Older versions of COLLADA are no longer supported, and are not compatible with the official standard release. Contents If you want to learn about the details: - Read the COLLADA Specification, available on the official COLLADA standard web site:. - Read the release notes. Available at the same place:. Release notes contain valuable information that could not be included in the documentation in time for production. - Download the schema, from the same source - Use graphical tools such as XMLspy to browse the schema in graphical form. [Note: XML edition might complain about the include statement; you can safely comment it out on a special copy of the schema] - Look at sample COLLADA documents in the COLLADA Test Model Bank. If you are getting samples from elsewhere, make sure that you are not looking at a document for a version prior to 1.4.x. Every COLLADA document contain the version in the namespace declaration. - Ask questions about design issues in the Design Discussions forum. Importing and exporting COLLADA data If you want to use COLLADA format to import data into or export data from tools: - Go to Portal:Products directory and check whether the tool that you want is listed. Follow the instructions on how to install the plug-in if required. - Check the Portal:Products directory often to make sure that you have the most up-to-date tool. It is a good idea to subscribe to each product of interest to get an e-mail when updates are made to the product's page. - If your tool is not listed, go to the vendor's support web/e-mail and query about their COLLADA support. Many tools have COLLADA as a work in progress and may be able to provide you with early software releases. - If your product is listed, but lacks some features you need, please make a request to the tool vendor and/or the COLLADA plug-in provider. - Get COLLADA Refinery and use it to process your data further. This package also contains the COLLADA Coherency Test; you can run your exported data through these tests to detect any potential issues. - Report bugs! Please! Check reporting bugs or requests to know where to post your bugs. - Ask your questions in the relevant COLLADA forums (use the Forum link in left navigation bar at any time). - Share your experience and contribute samples! Implementing with COLLADA If you want to implement COLLADA in your project: First, some important notes: COLLADA is not designed as a game engine format; it is designed as an intermediate format for all the tools in your content pipeline, such as DCC tools and conditioners. Some applications use COLLADA as their input format, such as Google Earth, but most have a converter from COLLADA to their highly optimized binary platform and engine-specific format at the end of the COLLADA tool-chain. Consider writing such a converter in a generic way so you can get data to your application from any part of the content pipeline. Likewise, consider the capability to directly load COLLADA documents into your application, at least in the development phase, to improve productivity. Extensions COLLADA is designed to be highly flexible. It can store application-specific data using its <extra> mechanism at various places in the document. You can insert this data in your DCC tool using the user properties mechanism; the COLLADA import/export will then carry this information for you, so there is no need to change the exporter source code to carry your application/game-specific data into the COLLADA format. The COLLADA schema allows this <extra> information at a lot of places, but implementations do not support all the possibilities. Make sure you do a quick experiment first, and ask the vendor/maintainer for information about how this is currently supported. Note that this is often a limitation of the tool itself, not necessarily a limitation of the import/export process. The <extra> information that is supported will be saved in the tool native format as well, if imported from a COLLADA document. If you have your own plug-in for a given DCC tool, simply make sure that this plug-in puts the relevant information at the right place, and the already available COLLADA export/import will do the rest of the work for you. Also see the Extensions directory for details about the syntax of these <extra> extensions provided by various vendors. If you are a vendor with extensions, please consider adding to the extensions directory. Developer tools and resources - Consider using either the FCollada or the COLLADA DOM library. Both libraries are open-source and can be used in a commercial or noncommercial application without restrictions. COLLADA DOM is generated from the XML COLLADA schema and provides access to all the COLLADA elements. FCOLLADA is used by the ColladaMax and ColladaMaya plug-ins, and provides a higher-level interface. The choice of library depends on your style of programming, and how close to the schema you want to be. - Check Portal:Products directory often to make sure you have the most up-to-date library. - If you are not using C++, or do not want to use the preceding libraries, there are other libraries or sample code for Java, C#, and other languages available. Check the Contributions forum, for tools that can generate an interface in a variety of language from the Schema. - Report bugs! Please report bugs in the right place, as indicated in reporting bugs or requests. - Get COLLADA Refinery and write your own conditioners to create your content pipeline and process the data further toward the application-specific data. For instance, use this to create triangle strips, or optimized index triangle lists, out of all possible COLLADA geometries. - Use the Coherency Test (part of the Refinery package) to test your exports or the documents that you are importing. - Ask questions about implementation issues in the Implementation Discussions forum. - Feel free to update the source code of the export/import, but only if you have a good reason for it, since this is extra work. Export/Import plug-ins are usually well designed and if you make your changes in additional files should be easy to merge with updates. If you want to avoid merging with future releases, consider providing your code to the maintainer/vendor so that your code gets included in the next release. Summary If you have ideas on how to improve this guide, please sign in and edit this article or post suggestions on this article's discussion/talk page, or let us know at collada (at) collada.org. Most important, do not give up! COLLADA is not that hard, and it is rewarding and fun after you're through the learning curve!
https://www.khronos.org/collada/wiki/Getting_started_with_COLLADA
CC-MAIN-2016-44
refinedweb
1,194
51.99
hey, i am new here but i have taken a few c++ classes. im having trouble with a very easy program and i just cant figure out why its doing this. ive looked around the forum already and didnt find anything helpful so i thought id ask. include <iostream> using namespace std; int add(); int subtract(); int times(); int divide(); int main() { int a; cout<<"This program is a simple calulator. Its able to + - * or /\n"; cout<<"the below table is a 'key' enter one of the numbers\n\n\n"; cout<<" 1. add\n"; cout<<" 2. subtract\n"; cout<<" 3. times\n"; cout<<" 4. divide\n\n"; cout<<" "; cin>>a; cout<<"\n\n"; if (a==1) add(); else if (a==2) subtract(); else if (a==3) times(); else if (a==4) divide(); else cout<<"you didnt enter a valid number.\n\n"; system("PAUSE"); return 0; } int add() { int num, sum=1; cout<<"how many numbers would you like to add?\n"; cin>>num; for (int i=1;i<num;i++) { int array[i]; sum+=array[i]; } cout<<"Your new number is "<<sum<<"\n\n\n"; } its able to run, but when i enter any number for the amount of numbers to add, it prints out some long number like 257487465896546549876546 my question is why is it giving me that long number and how can i fix it?
https://www.daniweb.com/programming/software-development/threads/279777/easy-array-adding
CC-MAIN-2018-13
refinedweb
229
79.09
25 April 2011 04:50 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The two crackers – the 750,000 tonne/year naphtha cracker at Yeosu and the 1m tonne/year naphtha cracker at Daesan – are running at 100% capacity on naphtha, they added. “The switch, starting from June, will be partial. Not more than 10% of the runs will be based on LPG,” said one source, who declined to be named. The margin between LPG and ethylene was still better than that of naphtha in northeast However, the supply pool of aromatics is expected to tighten as the partial switch to LPG takes place, traders said. ($1 = €0.69) Additional reporting by Mahua Chakravarty
http://www.icis.com/Articles/2011/04/25/9454766/s-koreas-honam-to-run-naphtha-crackers-partly-on-lpg-from.html
CC-MAIN-2015-06
refinedweb
113
70.43
TODO: - Fix cmpshlib not to require #filelist and #init's to be checked in the spec file. - Added something that allows a non-existant -arch not to fail hard (NRW group request for libsys 1.0 and 2.0 compatiblity). Changes for the 5.20 release (the cctools-590.20 release): - Removed the warnings when building. Radar bug #4340147. - Added -fno-builtin-round to the Makefile. - Added unsigned to the local variables in make_oldtarget_hashtable() in cmpshlib.c .-533 release): - Changed host_byte_sex in cmpshlib.c to not be declared static to match the header file mkshlib.h . - Changed mkshlib.c to initialize the variable progname and declare it to be a __private_extern__ to avoid having a common private extern be created when built with gcc-3.5. Changes for the 5.16 release (the cctools-526 release): - Fixed warnings for the changes in mach-o headers for types changing from unsigned long to uint32_t and from long to int32_t. Radar bug #3744082. - Changed a uses of "%lu" to "%u" in cmpshlib.c .. Changes for the 5.12 release (the cctools-464 release): - Made changes to build cleanly with gcc3.3 - Removed -Wno-precomp from the Makefile and added RC_OS = macos - Fixed warnings for "comparison between signed and unsigned" in host.c, parse_spec.c, cmpshlib.c and hack_libgcc.c . Changes for the 5.11 release (the cctools-440 release): - Fixed the warnings about extra tokens at end of #endif directive in cmpshlib.c, host.c and parse_spec.c (Radar bug #3072042). Changes for the 5.10 release (the cctools-400 release): - Changed the Makefile back to again use the -dependency-file with gcc. - Changed hack_gcc.c to add the new throttle parameter to writeout(). Changes for the 5.10 release (the cctools-396 release): - Changed the Makefile to not use the -dependency-file with gcc as well as mwccppc. Changes for the 5.10 release (the cctools-391 release): - Changed the call to ofile_process() in host.c to pass FALSE for the new use_member_syntax parameter. Radar bug #2730127. Changes for the 5.10 release (the cctools-386 release): - Changed the breakout() calls in hack_gcc.c pass FALSE as the value for the new calculate_input_prebind_cksum parameter. Changes for the 5.9 release (the cctools-359 release): - Added -Wno-long-double to shutup the compiler for <architecture/m88k/fp_regs.h>. Changes the 5.3 release (the cctools-292 release): - Added the int type to max_slotnum_seen in parse_spec.c to remove a warning from the egcs compiler. - Changed the return type of main() in mkshlib.c, cmpshlib.c and hack_libgcc.c from void to int to remove a warning from the egcs compiler. Also changed the exit()'s to return()'s. Changes for the 5.3 release, MacOS X bring up (the cctools-282 release): - Made the variable errors in errors.c a private extern so to allow it to prebind with the MacOS X System framework which also defines errors. - Changed task_self() to mach_task_self() for MacOS X in host.c. Also included "stuff/openstep_mach.h" for macros to allow it to still build on Openstep. Also changed ifdef's __SLICK__ to __OPENSTEP__. - Added #include "stuff/bytesex.h" to error.c, parse_spec.c and hack_spec.c so they would compile with the MetroWerks compiler. Changes for the 5.1 release (the cctools-260 release): - Added -c to all the install commands code ifdef __TEFLON__ to ifndef __SLICK__ (where __TEFLON__ will nolonger be defined for Rhapsody builds) so the default builds will be native Rhapsody builds. The changes were to mkshlib.c . Changes for the 5.0 release (the cctools-224 release): - Changed including <ranlib.h> to <mach-o/ranlib.h> which uses unsigned long instead of off_t (64 bits on Teflon). Changes for the 5.o release (cctools-210 release): - Changed m98k to ppc. Changes for the 4.2 release (cctools-209 release): - Added the -p option to command hack_libgcc to set the private extern bit on defined libgcc symbols. Fully tested this tool with this release and it is ready to go. Changes for the 4.2 release (cctools-208 release): - Wrote the command hack_libgcc to deal with the new and old libgcc needing to be in libsys. The version in cctools-208 compiled, links and has only been lightly tested. Changes for the 4.0 release (cctools-179 release): - Fixed a bug in host.c where if an object file had a zero sized string table then the first byte of the string table was not allocated (bug #59051). Changes for the 4.0 release (cctools-175 release): - Changed the Makefile to ld -r builds because private externs were causing prebinding to fail because of overlap. Changes for the 4.0 release (the cctools-148 release): - Added the #filelist directive. It is allowed in only when #objects is in effect. The syntax is "#filelist listfile [dirname]". If a file name in list file as already been seen in the spec file it is ignored. The optional dirname is prepended, as well as a '/' if needed, to each file name listed in list file. The filenames in list file are one to a line with all other white space as part of the file name. Changes for the 4.0 release (the cctools-138 release): - Picked up a change from sparc group for cmpshlib. Changes for the 4.0 release (the cctools-135 release): - Fixed a bug in cmpshlib when the branch target had an old_name specification and there was more than one symbol at the branch table target. This happens in libMedia with: ## These two guys are indirect symbols for MxMultiply() and MxInvert(), ## respectively: _N3DMultiplyMatrix 192 old_name _MxMultiply _N3DInvertMatrix 193 old_name _MxInvert because of the indirect symbols. The fix was in check_newtarget() to detect when more than one symbol is at the branch table target and then using the on that matches the spec file's for that slot (bug #45204). Changes for the 4.0 release (the cctools-134 release): - Picked up sparc fixes to target.c which has the correct branch and branch slot size. - Fixed a typo in cmpshlib.c for sparc mask 0xffc00000 was 0xffc000000. Changes for the 4.0 release (the cctools-133 release): - Picked up sparc changes to target.c which has the branch and trap instructions implemented for sparc. - Picked up sparc changes to cmpshlib.c which implements get_target_addr() for sparc branch table targets. Changes for the 3.3 release (the cctools-122 release): - Fixed a bug in cmpshlib that had hard coded numbers for the text section and data section nsect numbers. Made open_target() return these to values. Changes for the 3.3 release (the cctools-119 release): - Picked up the changes for cmpshlib with respect to the sparc target. Changes for the 3.3 release (the cctools-110 release): - Removed a fatal() call in scan_objects_processor() in host.c that was checking for a symtab_command. With the new assembler in cctools-110 this was causing problems with valid "empty" object files. Changes for the 3.3 release (the cctools-107 release): - Fixed a problem with the true Mach-O assembler not padding the text section of the branch object by forcing the padding into the assembly source of the branch object in target.c. Changes for the 3.3 release (the cctools-102 release): - Integrated in the hppa support. different mkshlib/cmpshlib.c (integrated for cctools-102) Using cctoolshppa-37. Has hppa branch target stuff in it. different mkshlib/target.c (integrated for cctools-102) Using cctoolshppa-37. Has hppa branch target stuff in it. Changes for the 3.1 release (the cctools-16 release): - Fixed the cleanup of mkshlib so that fatal errors would do the cleanup. - Fixed a bug relating to the bug below where the subtypes of the shlibs should not have been checked. Changes for the 3.1 release (the cctools-15 release): - Fixed a bug where the -arch of a family for cmpshlib(l) would fail to pick a specific arch (bug #30835). Changes for the 3.1 release (the cctools-13 release): - Added the m98k (PowerPC) architecture. Changes for the 3.1 release (the cctools-10 release): - Fixed a bug in mkshlib(l) where because of striping the target shlib the value of the vmsize of the __LINKEDIT segment in the host libraries __.FVMLIB file could report an overlap when it does not exist. Since this can't be checked accurately at link time this feild is set to zero for the __LINKEDIT segment and it is left to be checked at runtime only. The change is in write_lib_obj() in host.c Changes for the 3.1 release (the cctools-4 release): - Changed the trap instruction for the i386 to 0xf4 a "hlt" instruction and changed it to 5 bytes instead of 6 bytes to match the "jmp" instruction size. - Added support in cmpshlib(l) to check the m88k and i386 architectures branch instructions. - Added fat file support. Switch over to error functions in libstuff and routines in there. Changes for the 3.0 release (the -55 compiler release): - Fixed a bug that caused looping if an #alias was seen before either the #private_externs or #nobranch_text. The problem was that in new_state() in parse_spec.c the oddball data structure was not set up for the #alias directive and caused a memory smasher. Changes for the 3.0 release (the -51 compiler release): - Changed mkshlib to treat all errors as fatal and exit non-zero and without creating any files (two line change in main() in mkshlib.c). (bug #17054) - Added the optional "old_name <old_funcname>" syntax to mkshlib(l) and cmpshlib(l) to allow cmpshlib to check an old name for compatiblity. (bug #17054) Changes for the 3.0 release (the -49 compiler release): - Changed the Makefile to meet the RC api. Changes for the 3.0 release (the -44 compiler release): - Switch over to the new header file organization. Changes for the 3.0 release (the -43 compiler release): - Added code in target.c to handle i386 shlibs. - Fixed warnings from new compiler about printf strings. Changes for the 3.0 release (the -36 compiler release): - Added code in target.c to handle both 68k and 88k shlibs. Changes for the 3.0 release (the -34 compiler release): - Added the -image_version argument like the -minor_version argument to mkshlib which if specified is used to set the minor version of the target shlib. - Added installsrc, installIBMsrc and installGNUsrc targets to the Makefile. Changes for the Warp ?? release (the -26 compiler release): - Fixed bugs where the a file was to be created and the create failed because the file was read-only. The fix was to unlink all files before creating them. Changes for the Warp ?? release (the -25 compiler release): - Added the -s spec_file option to cmpshlib so it can check the #nobranch_text (global const) symbols that are not #private_externs. Also data symbols that are #private_externs are not reported. - Changed mkshlib to leave around the the branch object and source when it works successfully. Changes for the Warp ?? release (the -24 compiler release): - Added two prints to cmpshlib to say what it is checking. - Added all approprate ld flags to mkshlib. - Changed to always use branch.o and branch.s so scattered loading will have a constant object file name to use. - Changed to use one array for all ld flags. - Removed the prototype for map_fd from cmpshlib.c . Changes for the 2.0 impulse X.X release (the -23 compiler release): - Added an fsync() call right before the host file is written ifdef'ed OS_BUG to work around the kernel not flushing the modification time correctly. Changes for the 2.0 impulse X.X release (the -22 compiler release): - Added the -segaddr option to mkshlib(l). Changes for the 2.0 impulse X.X release (the -21 compiler release): - Changed the name of the shared library full reference symbol from .shared_library_reference<target base name> to the target base name up to (but not including) the first '.' . This is so the name for "/usr/shlib/libsys_s.A.shlib" will be "libsys_s" etc. Changes for the 2.0 impulse X.X release (the -20 compiler release): - Fixed a bug where the rounded area of a host shared library object was not zeroed and then ld(1) would complain that the string table did not end in a '\0'. - Changed the file definition symbol names to include the base name of the target shared library. This caused a bug where libNeXT and libsys both had a file named pointers.o in them and the -20 version of the link editor would treat this as a multiply defined symbol. Changes for the 2.0 impulse X.X release (the -19 compiler release): - Added the -segprot option to mkshlib to pass through to ld(1). - Changed -segcreate to -sectcreate but still recognized -segcreate. - Added code in target.c to check for the existence of all objects before running ld(1). - Updated for the changes to CPU_TYPE and CPU_SUBTYPE with the changes to <sys/machine.h> - Added an object to the host shared library that a defined symbol in it will reference all objects in the library. Changes for the 2.0 impulse 0.01 release (the -17 compiler release): - Changed #alias from using the -a option of the 1.0 link editor to using the -i option of the new link editor. This involved causing the original name to become a private extern automaticly and to be seen in the target file. - Changed to using a section for initialization to match the removal of loader defined symbols in the new link editor. To do this without a .section directive in the assembler required writing the entire object file so while I was at it I made it write the entire host shared library archive which makes it much faster. Also added a library identification object in the target shared library to propagate the LC_IDFVMLIB load command for use with the new link editor. Also bought the code up to ANSI C (both the mkshlib and cmpshlib code) with respect to prototypes, header files and the library functions they use. Removed all a.out style shlib related code from both programs. - Added the -minor_version argument to mkshlib. Changes for the 0.96 release (the -16 compiler release) - Added the -f option to not write out the host library. Changes for the 0.91 release (the -10 compiler release) - Added allowing the '-' character in object file base names. - Fixed the data_size in the shared library struct to reflect the size of all other segments besides the text (a kluge but will get the correct overlap checking). Also added a S_FVMLIB marked segment to the __.FVMLIB object for all segments of the shared library. Changes for the 0.83 release (only a binary of cmpshlib was released) - Fixed cmpshlib to handle Mach-O symbols. Changes for the 0.83 release (the -9 compiler release): - Added the #undefined directive which passes -U <symbol name> to ld for each symbol listed. And removed the -u option (it now prints a warning). Changes for the 0.82 release (the -8 compiler release): - Fixed a bug that didn't get the cross references for undefined private externs between library members. - Added -segcreate options to be passed through to ld. - Fixed a bug in two error() messages that were missing an argument and caused a core dump. This happened when a private_extern was also in the branch table or nobranch_text (parse_spec.c line 231 and 237) - Changed the Makefile to install in /usr/local/bin. This directory gets cleaned before release. Changes for the 0.82 release (the -7 compiler release): - Removed bsearch.c and linking with it. (This must link with the ANSI C libc release 0.81 or better or bsearch will be undefined). - Change from using strtol() to strtoul() when parsing #address. (This must link with the ANSI C libc release 0.81 or better or this will be undefined). - Changed the default object file format produced by mkshlib to mach relocatable (setting of the -M flag). - Added header_addr to fvmlib id command and filled it in. Changes for the 0.81 release (the -6 compiler release): - Updated the mkshlib to take in and produce mach-O relocatable objects (with the -M flag for now). Changes for the 0.8 release: - Fixed the problem of a symbol that is both a private_externs and the alias of an aliased symbol (-aoriginal:alias) which did not get removed from objects that referenced them.
http://opensource.apple.com/source/cctools/cctools-667.3/mkshlib/notes
CC-MAIN-2016-30
refinedweb
2,744
69.28
Your message dated Mon, 08 Aug 2011 00:39:30 -0700 with message-id <address@hidden> and subject line Re: bug#6683: mktemp foo.XXXXXXXXXXX is not sufficiently random has caused the GNU bug report #6683, regarding mktemp foo.XXXXXXXXXXX is not sufficiently random to be marked as done. (If you believe you have received this mail in error, please contact address@hidden) -- 6683: GNU Bug Tracking System Contact address@hidden with problems --- Begin Message ---While looking at the random-number stuff I found a theoretical randomness bug in mktemp. The mktemp command currently uses 8 bytes of randomness to generate a file name, so with an invocation like this: $ mktemp foo.XXXXXXXXXXX the file name is not sufficiently random. There are 62 possibilities for each X, so one needs log2(62**11) random bits to generate a random 11-character value for the Xs, which is about 65.5 bits, but we are generating only 64 bits. The more Xs, the more randomness is needed, so the bug gets more "serious" as the number of Xs grows. Here's a simple patch to fix this. Should I install this by generating a new gl/lib/tempname.c.diff by hand, and pushing that? --- old/tempname.c 2010-07-20 09:41:36.774229000 -0700 +++ new/tempname.c 2010-07-20 10:14:33.391452000 -0700 @@ -245,7 +245,7 @@ gen_tempname_len (char *tmpl, int suffix XXXXXX = &tmpl[len - x_suffix_len - suffixlen]; /* Get some more or less random data. */ - rand_src = randint_all_new (NULL, 8); + rand_src = randint_all_new (NULL, x_suffix_len); if (! rand_src) return -1; Here's a fancier patch that uses fewer random bits, but on futher thought I don't think it's worth the extra machine instructions for a purely-theoretical bug: --- old/tempname.c 2010-07-20 09:41:36.774229000 -0700 +++ new/tempname.c 2010-07-20 09:45:00.685972000 -0700 @@ -19,6 +19,7 @@ #if !_LIBC # include <config.h> +# include <limits.h> # include "tempname.h" # include "randint.h" #endif @@ -189,6 +190,17 @@ check_x_suffix (char const *s, size_t le static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +/* Upper bound on the number bytes of random information needed to + generate N random letters. There are 62 letters, and 2**6 is 64, + so 6N bits = 6N/CHAR_BIT bytes is an upper bound. Return ceil (6.0 + * N / CHAR_BIT) without rounding error or overflow. */ +static size_t +randomness_bound (size_t n) +{ + return ((n / CHAR_BIT) * 6 + + ((n % CHAR_BIT) * 6 + CHAR_BIT - 1) / CHAR_BIT); +} + /* Generate a temporary file name based on TMPL. TMPL must match the rules for mk[s]temp (i.e. end in at least X_SUFFIX_LEN "X"s, possibly with a suffix). @@ -245,7 +257,7 @@ gen_tempname_len (char *tmpl, int suffix XXXXXX = &tmpl[len - x_suffix_len - suffixlen]; /* Get some more or less random data. */ - rand_src = randint_all_new (NULL, 8); + rand_src = randint_all_new (NULL, randomness_bound (x_suffix_len)); if (! rand_src) return -1; --- End Message --- --- Begin Message ---On 08/07/2011 10:04 AM, Jim Meyering wrote: > Yes, please do. OK, thanks, I installed the one-line change as change to the diff. This is the first time I've updated a diff file in a while (ever?), so I hope I did it right. I'm marking the bug done. >From 8e2767a3f0c279d355f067e53be2c63173959eb1 Mon Sep 17 00:00:00 2001 From: Paul Eggert <address@hidden> Date: Mon, 8 Aug 2011 00:29:46 -0700 Subject: [PATCH] mktemp: stir in enough entropy (Bug#6683) * gl/lib/tempname.c.diff (gen_tempname_len): Use x_suffix_len bytes' worth of entropy, not 8 bytes. --- gl/lib/tempname.c.diff | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) diff --git a/gl/lib/tempname.c.diff b/gl/lib/tempname.c.diff index fcacf53..3e30c97 100644 --- a/gl/lib/tempname.c.diff +++ b/gl/lib/tempname.c.diff @@ -100,7 +100,7 @@ index 2da5afe..562955a 100644 - } -#endif - value += random_time_bits ^ __getpid (); -+ rand_src = randint_all_new (NULL, 8); ++ rand_src = randint_all_new (NULL, x_suffix_len); + if (! rand_src) + return -1; -- 1.7.4.4 --- End Message ---
http://lists.gnu.org/archive/html/emacs-bug-tracker/2011-08/msg00070.html
CC-MAIN-2016-40
refinedweb
647
68.97
McAfee Interview QuestionApplications Developers Country: United States // ZoomBA def count_more_char( string ){ m = mset ( string.value ) // find all chars with odd frequency odds = select ( m ) :: { $.o.value % 2 != 0 } len = size(odds) // every char freq is even means //can be shuffled into a palindrome if ( 0 == len ) return 0 // because only one odd freq can be allowed //for palindrome, rest needs to be made into even len - 1 } Based on expansion of WilOzil's idea. 1. You can make use of a Hashmap for each string. Each line is a string. Use a hashmap to count all the characters. If the length is odd, 1 character can appear once, rest all have to appear or the count has to be even for other characters. The characters that fall short of this condition are the number of characters required to make the string a palindrome. The you can just go over the hashmap, use two pointers front and rear to place the elements. Time complexity O(n) for the lines, O(T) for each string, So O(Tn) for the file containing all the strings.- WilOzil November 26, 2015 2. Sort the string and count the characters. Follow similar approach as in case 1. Time complexity O(n) for lines, O(TlogT) for sorting. O(nTlogT) in total.
https://careercup.com/question?id=5636317922721792
CC-MAIN-2020-50
refinedweb
216
74.49
Unofficial Deep Learning Lecture 5 Notes Hi All, Please find the lecture 5 notes. There was a lot of great material covered today, so hoping you guys can flesh out some of the details. I tried to capture as much as I could, but there was a lot of math to absorb near the end of the lecture around the topics of momentum + Adam optimizer. Hope the notes are useful! Cheers, Tim @jeremy please convert to wiki, so all can contribute? Thanks ahead of time, great lecture today. Today we are going to start the second part of this course. Now, what we now going to do is go in reverse. We are going to go back over all of those exact same things again but this time we are going to dig into the detail of every one and we are going to look inside the source code of fastai library to see what it’s doing and try to replicate that. So, in a sense like there’s not going to be a lot more best practices to show us like Jeremy have kind of shown us the best best practices that he knows. Jeremy thinks it’s time for us to now build on top of those, to debug those models, to come back to part 2 where we’re going to kind of try out some new things. It really helps to understand what’s going on behind the scenes. MovieLens The goal here today is we’re going to try and create a pretty effective collaborative filtering model almost entirely from scratch. We will use PyTorch as a automatic differentiation tool and as a GPU programming tool and not very much else. We’ll try not to use its neural net features. We’ll try not to use fastai library anymore than necessary. Let’s look at collaborative filtering. We are going to look at Movielens dataset. The Movielens dataset is basically is a list of movie ratings by users. We go through the Jupyter notebook here. If you need to download the dataset: # !wget # !unzip ml-latest-small.zip Import the libraries: %reload_ext autoreload %autoreload 2 %matplotlib inline import torch from fastai.learner import * from fastai.column_data import * path='ml-latest-small/' ratings = pd.read_csv(path+'ratings.csv') ratings.head() movies = pd.read_csv(path+'movies.csv') movies.head() Create subset for Excel We create a crosstab of the most popular movies and most movie-addicted users which we’ll copy into Excel for creating a simple example. This isn’t necessary for any of the modeling below however. g=ratings.groupby('userId')['rating'].count() topUsers=g.sort_values(ascending=False)[:15] g=ratings.groupby('movieId')['rating'].count() topMovies=g.sort_values(ascending=False)[:15] top_r = ratings.join(topUsers, rsuffix='_r', how='inner', on='userId') top_r = top_r.join(topMovies, rsuffix='_r', how='inner', on='movieId') # pd.crosstab(top_r.userId, top_r.movieId, top_r.rating, aggfunc=np.sum) Given some ratings: Every rating is represented as a matrix cross product (random init) Note that Microsoft Office for Windows has add-ins. You can turn on the “solver” in the add-ins. This will run an iterative solver. Now we can calculate the loss And we can then optimize the ORANGE cells based on the loss, BLUE cells - RED cells. Collaborative Filtering - High Level Get a validation indexes wd- L2 regularization n_factors- embedding sizes val_idxs = get_cv_idxs(len(ratings)) wd=2e-4 n_factors = 50 ratings.csv userId movieId rating- dependent variable This movie and user, which other movies are similar to it, which people are similar to this person? cf = CollabFilterDataset.from_csv(path, 'ratings.csv', 'userId', 'movieId', 'rating') - size embedding - index - batch size - which optimizer learn = cf.get_learner(n_factors, val_idxs, 64, opt_fn=optim.Adam) Run the fit learn.fit(1e-2, 2, wds=wd, cycle_len=1, cycle_mult=2) [ 0. 0.84641 0.80873] [ 1. 0.78206 0.77714] [ 2. 0.5983 0.76338] math.sqrt(0.776) 0.8809086218218096 preds = learn.predict() y=learn.data.val_y[:,0] sns.jointplot(preds, y, kind='hex', stat_func=None); PyTorch and Linear Algebra: Dot product example T = tensor in Torch a = T([[1.,2],[3,4]]) b = T([[2.,2],[10,10]]) a,b ( 1 2 3 4 [torch.FloatTensor of size 2x2], 2 2 10 10 [torch.FloatTensor of size 2x2]) a*b 2 4 30 40 [torch.FloatTensor of size 2x2] (a*b).sum(1) 6 70 [torch.FloatTensor of size 2] Our First Custom Layer in PyTorch We are now making a basic Torch class. We are extending the nn.Module from PyTorch forward is a inherited method from the nn.Module, which is leveraged by other functions in other pytorch libraries forward<- matrix multiplication backwards<- gradients class DotProduct(nn.Module): def forward(self, u, m): return (u*m).sum(1) Create an instance of the class model=DotProduct() model(a,b) 6 70 [torch.FloatTensor of size 2] Prepare the data: - look at unique values of user_ids - make a mapping from user_id to a INT (so there’s no skipping of numbers) - do the same for movie ids Reminder: enumerate- takes in a collection, gives back the index, value for a collection lambda- python keyword for making a temporary function u_uniq = ratings.userId.unique() user2idx = {o:i for i,o in enumerate(u_uniq)} ratings.userId = ratings.userId.apply(lambda x: user2idx[x]) m_uniq = ratings.movieId.unique() movie2idx = {o:i for i,o in enumerate(m_uniq)} ratings.movieId = ratings.movieId.apply(lambda x: movie2idx[x]) n_users=int(ratings.userId.nunique()) n_movies=int(ratings.movieId.nunique()) Now lets make a more complicated Embedding Layer __init__- this function is called when the object is created. Called the constructor obj = myClass() obj = newClassImade(list) nn.Embedding- a pytorch object self.u.weight.data- initializing the user weights to a reasonable starting place self.m.weight.data- initializing the movie weights to a reasonable starting place uniform_- note that _means ‘inplace’ instead of returning a variable and doing an assignment for forward - users,movies = cats[:,0],cats[:,1] We are pulling both datasets out of the categorical variable. class EmbeddingDot(nn.Module): def __init__(self, n_users, n_movies): super().__init__() self.u = nn.Embedding(n_users, n_factors) self.m = nn.Embedding(n_movies, n_factors) self.u.weight.data.uniform_(0,0.05) self.m.weight.data.uniform_(0,0.05) def forward(self, cats, conts): users,movies = cats[:,0],cats[:,1] u,m = self.u(users),self.m(movies) return (u*m).sum(1) Prep the features and dependent variable x = ratings.drop(['rating', 'timestamp'],axis=1) y = ratings['rating'] Pull from a dataframe, with x, y, note that we bind the categorical variables together data = ColumnarModelData.from_data_frame(path, val_idxs, x, y, ['userId', 'movieId'], 64) Setup a optimizer optim- gives us an optimizer. model.parameters()this is inherited from the nn.Module. 1e-1- is the learning rate weight decay- regularization momentum wd=1e-5 model = EmbeddingDot(n_users, n_movies).cuda() opt = optim.SGD(model.parameters(), 1e-1, weight_decay=wd, momentum=0.9) Note: we are not using a Learner, we are using the low-level PyTorch fit. fit(model, data, 3, opt, F.mse_loss) [ 0. 1.68932 1.64501] [ 1. 1.08445 1.30609] [ 2. 0.91446 1.23001] ### Set the learning rate set_lrs(opt, 0.01) fit(model, data, 3, opt, F.mse_loss) [ 0. 0.69273 1.14723] [ 1. 0.72746 1.1352 ] [ 2. 0.67176 1.12943] Bias min_rating,max_rating = ratings.rating.min(),ratings.rating.max() min_rating,max_rating (0.5, 5.0) Let’s improve our model Can we squash the ratings between 1 and 5? With the sigmoid function we can multiply by our target range F - its the pytorch functional. its a large library of functions used in deep learning def get_emb(ni,nf): e = nn.Embedding(ni, nf) e.weight.data.uniform_(-0.01,0.01) return e class EmbeddingDotBias(nn.Module): def __init__(self, n_users, n_movies): super().__init__() (self.u, self.m, self.ub, self.mb) = [get_emb(*o) for o in [ (n_users, n_factors), (n_movies, n_factors), (n_users,1), (n_movies,1) ]] def forward(self, cats, conts): users,movies = cats[:,0],cats[:,1] um = self.u(users)* self.m(movies) ## add in user bias and movie bias ## squeeze is going to be broadcasting, this will replicate a vector ## and add it to the matrix res = um.sum(1) + self.ub(users).squeeze() + self.mb(movies).squeeze() ## this limits the range of the ratings res = F.sigmoid(res) * (max_rating-min_rating) + min_rating return res wd=2e-4 model = EmbeddingDotBias(cf.n_users, cf.n_items).cuda() opt = optim.SGD(model.parameters(), 1e-1, weight_decay=wd, momentum=0.9) fit(model, data, 3, opt, F.mse_loss) [ 0. 0.85056 0.83742] [ 1. 0.79628 0.81775] [ 2. 0.8012 0.80994] What’s actually written in fastai library? def get_emb(ni,nf): e = nn.Embedding(ni, nf) e.weight.data.uniform_(-0.05,0.05) return e class EmbeddingDotBias(nn.Module): def __init__(self, n_factors, n_users, n_items, min_score, max_score): super().__init__() self.min_score,self.max_score = min_score,max_score (self.u, self.i, self.ub, self.ib) = [get_emb(*o) for o in [ (n_users, n_factors), (n_items, n_factors), (n_users,1), (n_items,1) ]] def forward(self, users, items): um = self.u(users)* self.i(items) res = um.sum(1) + self.ub(users).squeeze() + self.ib(items).squeeze() return F.sigmoid(res) * (self.max_score-self.min_score) + self.min_score Let’s make a Neural Network (NN) version of this Let’s look at the Excel. All the users are compared to all movies. Why not take the embedding and make a NN out of it? Mini net Let’s prototype our Embedding NN (self.u, self.m) = [get_emb(*o) for o in..create embeddings nn.Linear(n_factors*2, 10, nh)- create our linear layers nhnumber of hidden layers torch.cat([self.u(users),self.m(movies)], dim=1)adds the two users and movies together F.relu(self.lin1(x) - linear - relu 0, or Max; truncates negative values - we have 1 layer, it is a NN, maybe not ‘deep’ per say class EmbeddingNet(nn.Module): def __init__(self, n_users, n_movies, nh=10): super().__init__() (self.u, self.m) = [get_emb(*o) for o in [ (n_users, n_factors), (n_movies, n_factors)]] self.lin1 = nn.Linear(n_factors*2, 10, nh) self.lin2 = nn.Linear(10, 1) def forward(self, cats, conts): users,movies = cats[:,0],cats[:,1] x = F.dropout(torch.cat([self.u(users),self.m(movies)], dim=1), 0.75) x = F.dropout(F.relu(self.lin1(x)), 0.75) return F.sigmoid(self.lin2(x)) * (max_rating-min_rating+1) + min_rating-0.5 wd=5e-4 model = EmbeddingNet(n_users, n_movies).cuda() opt = optim.SGD(model.parameters(), 1e-2, weight_decay=wd, momentum=0.9) We will be using MSE loss as the optimizing metric fit(model, data, 3, opt, F.mse_loss) [ 0. 1.0879 1.10568] [ 1. 0.81337 0.82665] [ 2. 0.80449 0.79857] Let’s explore the learning rate set_lrs(opt, 1e-3) fit(model, data, 3, opt, F.mse_loss) [ 0. 0.68968 0.79054] [ 1. 0.71873 0.78805] [ 2. 0.70101 0.78719] Neural Network Approach - We can add dropouts - we can use embeddings of different sizes - we can add more hidden layers with more nodes - we can add different amounts of regularization Talk about the training loop What’s happening inside? opt = optim.SGD(model.parameters(), 1e-2, weight_decay=wd, momentum=0.9) To the Excel! First create some data Can we learn the slope and intercept? Lets look at the error equation (err^2=1,849) Increasing the intercept (1.5 up from 1) changes the error (err^2=419) How can we guess where we should go next? Finite Differencing A similar related term is back-propagation (the figure on the right) Caveat: there’s a problem with finite differencing at high-dimensionality 1,000,000 ---> transformation ---> 100k When you have a high dimensional space, your gradient becomes a huge matrix. The amount of calculation computation that you need is very high. Takes up a lot of memory, a lot of time. Look up: - Jacobian - Hessian More efficient: find the derivatives analytically instead of finite differencing. Remember the chain rule from calculus (quick aside on how the chain rule works) Explaining the manual calculation of the differentials, to calculate a new a and new b (orange), then run all back again. Momentum: addressing how fast we come to a good solution - Looking at SGD de/da, we see that it is positive and negative at random. - The momentum idea is controlled by beta coefficients, will keep the differential going in the same direction, but a bit faster; will reduce the number of iterations. - Adam is much much faster, but the answers are not as good as SGD with momentum. - Recently, a newer version is out: AdamW that fixes weight decay issues. Ideally this will be fixed going forward. About Adam Optimizer: even Faster! Equals to our previous value of b, times learning rate divided by sqrt(). cellJ8= linear interpolation of derivative and the previous direction cellL8= linear interpolation of derivative squared + derivative squared from last step - this is also known as exponential weighted moving average Some intuition on this (reminder, in the denominator) - squared derivative is always positive - if there’s a big change, the squared derivative will be huge - so if there’s a big change, we divide the learning rate by a big number, (slow down) - if there’s minimal change ( we will be more aggressive in choosing a new learning rate) - adaptive learning rate - since the rate isn’t constant, but dependent the model’s optimization movements Similar idea implemented in fastai libary avg_loss = avg_loss * avg_mom + loss * (1-avg_mom) From the fit function: def fit(model, data, epochs, opt, crit, metrics=None, callbacks=None, **kwargs): """ Fits a model Arguments: model (model): any pytorch module net = to_gpu(net) data (ModelData): see ModelData class and subclasses opt: optimizer. Example: opt=optim.Adam(net.parameters()) epochs(int): number of epochs crit: loss function to optimize. Example: F.cross_entropy """ stepper = Stepper(model, opt, crit, **kwargs) metrics = metrics or [] callbacks = callbacks or [] avg_mom=0.98 batch_num,avg_loss=0,0. for epoch in tnrange(epochs, desc='Epoch'): stepper.reset(True) t = tqdm(iter(data.trn_dl), leave=False, total=len(data.trn_dl)) for (*x,y) in t: batch_num += 1 loss = stepper.step(V(x),V(y)) avg_loss = avg_loss * avg_mom + loss * (1-avg_mom) #<---------- debias_loss = avg_loss / (1 - avg_mom**batch_num) t.set_postfix(loss=debias_loss) stop=False for cb in callbacks: stop = stop or cb.on_batch_end(debias_loss) if stop: return vals = validate(stepper, data.val_dl, metrics) print(np.round([epoch, debias_loss] + vals, 6)) stop=False for cb in callbacks: stop = stop or cb.on_epoch_end(vals) if stop: break
http://forums.fast.ai/t/deeplearning-lecnotes5/8416/14
CC-MAIN-2018-30
refinedweb
2,435
50.84
UNGETWC(3P) POSIX Programmer's Manual UNGETWC(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. ungetwc — push wide-character code back into the input stream #include <stdio.h> #include <wchar.h> wint_t ungetwc(wint_t wc, FILE *stream); The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard.seeko(), fsetpos(), or rewind()) or fflush() shall discard all pushed-back characters have been read, or discarded by calling fseek(), fseeko(), fsetpos(), or rewind() (but not fflush()),: EILSEQ An invalid character sequence is detected, or a wide-character code does not correspond to a valid character. The following sections are informative. None. None. None. None. Section 2.5, Standard I/O Streams, fseek(3p), fsetpos(3p), read(3p), rewind(3p), setbufGETWC(3P)
http://man7.org/linux/man-pages/man3/ungetwc.3p.html
CC-MAIN-2017-13
refinedweb
181
56.66
Is n prime? By jmcp-Oracle on Apr 05, 2005 While I was finding the right path to travel with my assignment, I figured out a fairly efficient method of calculating whether n is prime or not: unsigned int prime(unsigned it ofn) { /\* \* :: returns 1 if ofn is prime, 0 otherwise \* \* precondition: ofn > 0 \*/ unsigned int root; /\* |_sqrt(ofn)_| \*/ unsigned int count; unsigned int mark = 1; /\* our boundary condition var \*/ /\* we only need to go to floor(sqrt(ofn)) \*/ root = (unsigned int)floor(sqrt(ofn)); for (count = 2; count <= root; count++) { if (!(ofn % count)) { /\* not prime, so escape out \*/ mark--; break; } } return (mark); }How much more efficient could I get with this routine? This is an old chestnut, going back to the ancient Greeks. Google on "Eratosthenes sieve". do 2 as a special case then start the loop at 3 and increment by 2. Saves half the divisions. next, do 2 and 3 as special cases. start the loop at 5 and increment by 6. test only count and count+2 in the loop, since count+1, count+3, count+4 and count+5 are all divisible by 2 or 3 (proof left to reader.) Now you're only testing 1/3 of the divisors, and you've "unrolled" the loop so the loop overhead is amortized over two checks instead of just one. technique can be extended but with rapidly diminishing returns (next step is to increment by 30 and test only 8 of the 30 numbers in each increment -- that only drops from .333 to .266) further speedups possible but require some fairly exotic number theory results Posted by Rich McAllister on April 05, 2005 at 04:05 AM EST # Posted by James McPherson on April 05, 2005 at 04:32 AM EST # Nice write up, it will be good to know as a software release engineer as well... time to review the makefiles that I maintain. Also, do you have any thoughts on why java would be running slower on sparc/solaris vs. opteron/solaris or xeon/linux? I have a simple sorting program that is whicked fast on the amd box we have and burries the sparc box I was running on. dl Posted by Dan Lacher on April 05, 2005 at 03:13 PM EST # Posted by Ben Cooper on April 07, 2005 at 04:47 PM EST #
https://blogs.oracle.com/jmcp/entry/is_i_n_i_prime
CC-MAIN-2015-48
refinedweb
394
75.95
Created on 2018-03-18 16:41 by mrknmc, last changed 2018-04-10 21:36 by mrknmc. This issue is now closed. Currently, one can submit a task to an executor (both ThreadPoolExecutor and ProcessPoolExecutor) during interpreter shutdown. One way to do this is to register function fun with atexit as below. @atexit.register def fun(): pool.submit(print, "apple") The future is accepted and goes into PENDING state. However, this can cause issues if the _python_exit function (located in concurrent/futures/thread.py and/or concurrent/futures/process.py) executes before function fun. Function _python_exit will shutdown the running workers in the pool and hence there will be no workers running by the time fun is executed so the future will be left in PENDING state forever. The solution submitted here is to instead raise a RuntimeException when a task is submitted during interpreter shutdown. This is the same behaviour as when the shutdown method of an executor is called explicitly. Thanks for spotting this. I will take a look soon, unless someone beats me to it. New changeset c4b695f85e141f57d22d8edf7bc2c756da136918 by Antoine Pitrou (Mark Nemec) in branch 'master': bpo-33097: Fix submit accepting callable after executor shutdown by interpreter exit (GH-6144) New changeset b26265900a18a184997c3c3a1fa6a5bf29703ec9 by Antoine Pitrou (Miss Islington (bot)) in branch '3.7': bpo-33097: Fix submit accepting callable after executor shutdown by interpreter exit (GH-6144) (GH-6445) Thanks your contribution Mark! Happy to contribute! Thanks for the review :)
https://bugs.python.org/issue33097
CC-MAIN-2021-25
refinedweb
244
58.99
Applets can be executed in two ways: from Browser or from Appletviewer. The JDK provides the Appletviewer utility. Browsers allow many applets on a single page, whereas applet viewers show the applets in separate windows. Program, named SampleApplet, demonstrates the life-cycle methods of applets: Program: A demonstration of life-cycle methods of applets. import java.awt.*; import java.awt.event.*; /*<APPLETcode = "SampleApplet" width=300 height=150> </APPLET>*/ public class SampleApplet extends Applet implements ActionListener { Button b = new Button ("Click Me"); boolean flag = false; public void init () { System.out.println ("init () is called"); add(b); b.addActionListener (this ); } public void start () { System.out.println ("start () is called"); } public void destroy () { System.out.println("destroy () is called"); } public void stop () { System.out.println("stop () is called"); } public void actionPerformed (ActionEvent ae) { flag = true; repaint (); } public void paint(Graphics g) { System.out.println ("paint () is called"); if (flag) g.drawString (''This is a simple Applet",50,50); } } For executing the program using the AppletViewer or the web browser, first the program is to be compiled in the same way as the Java application program as shown below: C:\>Javac SampleApplet.java AppletViewer is a program which provides a Java run-time environment for applets. It accepts a HTMLfile as the input and executes the <applet> reference, ignoring the HTML statements. Usually, AppletViewer is used to test Java applets. To execute any applet program using AppletViewer the applet tag should be added in the comment lines of the program. These comment lines will not be considered when the programs are compiled. The command AppletViewer <appletfile.java> is used to view the applet .To execute Program, we can invoke the same as follows: c:\>appletviewer SampleApplet.java The reader can thus execute Program. It is suggested as an exercise. The drawstring () method draws the String 'This is a sample applet' on the applet panel, starting at the coordinate (50, 50). Note that the applet panel provides a graphical environment in which the drawing will paint rather than print. Usually, the panel is specified in terms of pixels in which the upper left comer is the origin (0, 0). As mentioned earlier, applets interact with the user through AWT. In Program we have used one AWT component-button. Observe the SampleApplet class header: public class SampleApplet extends Applet implements ActionListener The ActionListener interface is implemented by a class to handle the events generated by components such as buttons. The method actionPerformed () available in this interface is overridden so that some action is performed when the button is pressed. In Program, it can be observed that when the applet is first executed, the paint () method does not display anything on the applet window. This is because flag is set to false. When the button is pressed (observe the actionPerformed () method) the flag is set to true and repaint () method is called. This time since the flag is set to true, the repaint () method will display the string 'This is a simple applet'. In Program we use the System.out.println () method to print the sequence of the methods executed when the applet is running. The output shown in the console is in the following: init () is called; start () is called; paint () is called; stop () is called; start () is called; paint () is called; stop () is called; destroy () is called; When the applet program is first executed, three methods-init (), start (), paint () are executed. Later, if the applet window is minimized, the stop () method is executed. If the applet window is maximized again, the start () and the paint () methods will be executed simultaneously, When the applet window is closed, the stop () and the destroy () methods will be called simultaneously. The browsers that support applets include Netscape Navigator, Internet Explorer and Hot Java. The applet can be viewed from a web browser by writing the APPLET tag within the HTML code. To run the Program in the web browser, the following html code has to be written: <html> <head> <title> A sample Applet</title > </head> <body> <applet code="SampleApplet" width=200 height=200> </applet> </body> </html> To run the applet, the browser, which could be the Internet Explorer for instance, has to be opened, the options File Open have to be selected. Then, the applet code HTML file is opened by using the Browse button. To show the difference between running the applet in the applet viewer and the web browser Program is modified a little to the form shown in Program: Program An alternate way of running an applet. import java.applet.*; import java.awt. *; public class SampleApplet extends Applet { String msg = “”; public void init () { msg = msg + "init ();" } public void start () { msg = msg+ "start ();" } public void destroy () { msg = msg+ "destroy ();" } public void stop () { msg = msg+ "stop ();" } public void paint(Graphics g) { msg = msg+ "paint ();" g.drawString(msg,10,20); } } The button is removed and the life-cycle methods are displayed on the applet window instead of on the console. The difference between the output of the above applet when called using the AppletViewer and the web browser is in Figure. The output of Program shows the applet with the sequence of the methods executed. When the applet program is first executed, the init (), start () and paint () methods are called. When the web browser is minimized, the paint () method is called, and when it is maximized, paint () is called again. In the case of the applet viewer the stop (), start () and paint () methods are called when the applet is maximized. The same things happen when the applet viewer and the web browser are' closed. That is, the stop () method and the destroy () method are called. When moving from the web page containing the applet to another web page and back, the start () method in the applet is
http://ecomputernotes.com/java/awt-and-applets/working-with-applets
CC-MAIN-2019-39
refinedweb
958
62.48
In the class, we discussed an implementation FixedQueue of the Queue trait using a circular buffer and a fixed-length array. Your task is to write an implementation GrowQueue in a file growqueue.scala that will grow the array when the circular buffer is full and another element is enqueued. This is very similar to what we did in GrowStack, but you have to be more careful with copying the elements, because they may not be in a contiguous interval of the array. Start by compiling the three sources (queue.scala, growqueue.scala, checksuite.scala), and run the test suite: $ fsc queue.scala $ fsc growqueue.scala $ fsc checksuite.scala $ scala org.scalatest.run QueueCheckSuite Run starting. Expected test count is: 3 QueueCheckSuite: - basic queue test - many items *** FAILED *** - interleaved enqueuing and dequeuing *** FAILED *** Run completed in 348 milliseconds. Total number of tests run: 3 Suites: completed 1, aborted 0 Tests: succeeded 1, failed 2, canceled 0, ignored 0, pending 0 *** 2 TESTS FAILED *** As usual, when you are done with your implementation, all tests should pass. Unix systems have a utility called tail that prints out the last \(k\) lines of a text file. This works well and uses little memory even for very large files, because it uses a queue. The algorithm works as follows: Create an empty queue Queue[String]. Read each line from the file, and enqueue it. If the size of the queue is now larger than \(k\), then dequeue one line. Finally, print all the lines in the queue. Note that our Queue trait doesn't have a length method, so we can't ask the queue for its current size—we have to maintain such a count ourselves. Write a compiled scala application tail.scala that compiles to an object Tail. The application takes two command line parameters: the name of a text file, and the number \(k\). For example: > fsc tail.scala > scala Tail planets.txt 4 Jupiter Saturn Uranus Neptune You can start with the template tail.scala. Your program should use the GrowQueue from the previous task. If you failed to implement that task perfectly, then use the Scala queue scala.collection.mutable.Queue. You can create it like this: val q: Queue[String] = new scala.collection.mutable.Queue[String] with Queue[String] In this task, we will work on a simulation of a waiting process. Examples are the cars waiting to pay at a highway tollgate, or the customers queuing inside a bank or post office. Simulating such a system can help us understand the process, and how it might be made more efficient. For instance, the simulation might suggest that we should open an additional counter in the post office during certain hours of the day. Simulation is also an area where object-oriented programming really helps. This is because in a simulation, we typically have several "things" (objects) that interact with each other. We can model each "thing" by a class. The interactions of the "things" with each other are called events, and are modeled by the simulation. We will keep our simulation rather simple. The objects we need are clients (customers in the post office) and servers (employees of the post office). Clients come into the post office at random time intervals (determined by the average time between clients). If a server is free, the client is directly served by this server. Otherwise the client enters at the rear of a single queue, the waiting line. Whenever a server finishes serving a client, the next client from the front of the queue comes to this server. You can download the code as simulation.zip. Compile all the files, then run the simulation, for instance as scala Simulation 3 100 12 4This will simulate for 100 ticks (a tick is the basic time interval of the simulation), with three servers. The average serving time per client is 12 ticks, and clients come in on average every 4 ticks. We model each server and each client by a Scala object. Since there could be different servers and different clients with differing behavior, we first create a Client trait and a Server trait, with all the methods needed to program our simulation. The simulation itself is controlled by a Simulation object. We implement a discrete time-step simulation, where the entire process is simulated in discrete time units (called ticks). Events, such as a client coming in or leaving, can only occur in these discrete time steps. The method Simulation.simulate is called once for each tick, and controls the entire simulation: for (t <- 0 until timeSteps) sim.simulate(t)The implementation of the method Simulation.simulate(t: Int) is as follows: def simulate(t: Int) { println("Time " + t + ": ") checkClientArrival(t) for (j <- 0 until servers.length) { val s = servers(j) if (s.client != null && t == s.client.stopTime) s.stopServing(t) if (s.isIdle(t) && !queue.isEmpty) { val client = queue.dequeue() s.startServing(client, t) } } } The method checkClientArrival uses a random number to determine the arrival time of the next client. (The arrival of clients is usually modeled as a Poisson process—you will run into this if you learn more about probability and statistics). For simplicity, we do not consider the case where more than one client comes in at the same tick. The method simply adds the new client to the rear of the waiting queue. We then check all the servers: if its client is done, the client leaves. If the server is now idle, it starts serving the first client from the queue. Note that all the client and server methods called by the simulation are methods of the Client and Server trait. This will allow you to add different kinds of clients and servers in this task. In the original code, there is only one kind of client (SimClient), and only one kind of server (SimServer), which perform only basic functions and output. Your task is to implement the new server class CoffeeDrinkingServer (in the file coffeeserver.scala) and the new client class DemandingClient (in the file demandingclient.scala). A CoffeeDrinkingServer needs a five-tick coffee break after each client. That means, the method isIdle will return false for four ticks even after the last client has left. A DemandingClient simply needs much more time: His service time is always the meanServiceTime of the simulation plus 10 ticks (so there is no randomness at all). The toString methods of the two new classes indicate the different server/client type by puttin a star after the client number/server letter. The CoffeeDrinkingServer should print a message while it is drinking coffee (you can do this in the isIdle method), like this: Time 62: Time 63: Client 18 arrived Server B* stopped serving Client 15 Time 64: Server B* is drinking coffee. Time 65: Client 19 arrived Server B* is drinking coffee. Time 66: Server B* is drinking coffee. Time 67: Client 20* arrived Server B* is drinking coffee. Time 68: Server B* finished drinking coffee. Client 17 waited 9 ticks. Server B* started serving Client 17 and will finish at time 95 You must not modify any of the existing classes. Only work on CoffeeDrinkingServer in the file coffeeserver.scala, and on DemandingClient in the file demandingclient.scala. Do not change any other file! (In any case, you will only submit the two files coffeeserver.scala and demandingclient.scala.) You can test your new servers and clients with the two extra arguments to the Simulation object. For instance, if you run the simulation as scala Simulation 3 100 12 4 2 0then every second server is a coffee-drinking server (that is, servers B, D, F, etc.). If you run it as scala Simulation 3 100 12 4 0 5then every fifth client (that is, clients 0, 5, 10, 15, etc.) is a demanding client. And of course you can combine these to have both coffee-drinking servers and demanding clients: scala Simulation 3 100 12 4 2 5Experiment with different numbers of coffee-drinking servers and demanding clients.
http://otfried.org/courses/cs206scala/pp5.html
CC-MAIN-2018-05
refinedweb
1,344
73.98
Introduction: In the previous article we discussed the DOM 0 Level model, DOM 2 Level model and also discussed the internet explorer event model. Now in this article we are going to discuss the event model of jQuery. Here we will see how events are created and how they are handled using the jQuery model. It exhibits the following features: Well, jQuery is going to make our lives simpler by hiding these browser disparities or lack of similarity from us as much as it possibly can. Let's see how! Step 1: Firstly we have to create a web Application Step 2: Secondly you have to add a new page to the website Step 3: In this step we will discuss about the features of the jQuery event model Let see the DOM level 2 shortcomings towards event propagation, the advanced Level 2 Model also provides this bubbling phase but ups with an additional phase: capture phase.. Binding event handlers using jQuery: Here we will discuss about the binding in jQuery by using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() command. Consider the following simple example: $('img').bind('click', function (event) { alert('Hi dear!'); }); This statement binds the supplied inline function as the click event handler for every image on a page. The full syntax of the bind() command is as follows: bind(eventType,data,listener): I would like to describe that the command named as bind will Establishes a function as the event handler for the specified event type on all elements in the matched set. whose Parameters the first one named as eventType (String) Specifies the name of the event type for which the handler is to be established. This event type can be namespaced with a suffix separated from the event name with a period character. See such as click or onmouse like that. Further the second one parameter whose named as data (Object) Caller supplied data that's attached to the Event instance as a property named data for availability to the handler functions. If omitted, the handler function can be specified as the second parameter. At last parameter named as listener (Function) The function that's to be established as the event handler. The return type of such type of function is the wrapped set. Let we will examine that by taking a example which is given below: Script: Example: <%@ Page <html xmlns=""> <head runat="server"> <title></title> <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript"> $(function () { $('#plane') .bind('click', function (event) { fgh('Hiiiiiiii!'); }) .bind('click', function (event) { fgh('Hellooooooo!'); }) .bind('click', function (event) { fgh('Hwzzzzz uuuuuuuu!'); }) .bind('click', function (event) { fgh('F9 thank you!'); }); }); function fgh(s) { $('#divtxt').append('<div>'+s+'</div>'); } </script> </head> <body> <form id="form1" runat="server" style="background-color: #FFFF99"> <img src="images/plane.gif" id="plane" alt="Image" /> <div id="divtxt" style="font-family: 'Comic Sans MS'; color: #FFFF00; background-color: #008000"></div> </form> </body> </html> Output: Description: Here there are few changes not all changed the changes to this code, limited to the body of the ready handler, are minor butsignificant. In this script We create a wrapped set consisting of the target <img> whose id is id="plane" element and apply four bind() commands to it, Further we all know that jQuery chaining lets us apply multiple commands in a single statement each of which establishes a click event handler on the element. Here we see another event handling extra features that jQuery provides for us is the ability to group event handlers by assigning them to a namespace. For a while let see an example, a page that has two modes: a display mode and an editmode. When in edit mode, event listeners are placed on many of the page elements, but these listeners are not appropriate for display mode and need to be removed when the page transitions out of edit mode. We could namespace the edit mode events with code such as given below: $('#id1').bind('click.editMode',listner1); $('#id2').bind('click.editMode', listner2); and so on... But to remove all click.editmode listner we will use the syntax given below: $('*').unbind('click.editMode'); Further, In addition to the bind() command, jQuery model provides a handful of shortcut commands to establish specific event handlers. The syntax of each of these commands is identical except for the method name of the command, by using it we will save some space and present them all in the following single syntax descriptor, let see this specific addition whose syntax is given below eventTypeName(listener): Here it is used to like an addition to the jQuery which establishes the specified function as the event handler for the event type named by the method's name. The supported commands are as follows: Note that when using these shortcut methods, we cannot specify a data value to be placed in the event.data property. there is only one parameter named as listener which is the function that's to be established as the event handler. it also return the wrapped set. Further we will see that jQuery also provides a specialized version of the bind() command, named one(), that establishes an event handler as a one shot deal. It's have alogic that Once the event handler executes the first time, it's automatically removed as an event handler. Its syntax is similar to the bind() command and given below which is as follows, let see the command syntax of it one(eventType,data,listener): It is also used to establishes a function as the event handler for the specified event type on all elements in the matched set. Once executed, the handler is automatically removed. It also have three Parameters the first one name is eventType (String) Specifies the name of the event type for which the handler is to be established. The second one named as data (Object) which is used to Caller supplied data that's attached to the Event instance for availability to the handler functions. If omitted, the handler function can be specified as the second parameter. The third and last one named as listener (Function) The function that's to be established as the event handler. Having it's Return type also the wrapped set. Removing event handlers: In this we will discuss an example that why would necessary to remove an event handler Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. With in certain criteria it may be removed. Consider, for example, a page where multiple steps are presented, and once a step has been completed, its controls revert to read-only. For such cases, it would be advantageous to remove event handlers under script control. We've seen that the one() command can automatically remove a handler after it has completed its first (and only) execution, but for the more general case where we would like to remove event handlers under our own control, jQuery provides the unbind() command. The syntax of unbind() command is given below which is as follows: unbind(eventType,listener): unbind(event): It is used to removes events handlers from all elements of the wrapped set as specified by the optional passed parameters. further If we are not providing any parameters then, all listeners are removed from the elements. Here the first parameter named as eventType (String) If provided, which specifies that only listeners established for the specified event type are to be removed. the second one named as listener (Function) If provided, identifies the specific listener that's to be removed. the third one is the event which removes the listener that triggered the event described by this Event instance. it will also returns the wrapped set. Another event related commands: Here we will discuss about some extra or related event command in the jQuery model which provide us some extra feature named as toggle event .Let's see the description about it's syntax and parameters given below: toggle(listenerOdd,listenerEven): it is also another event command to establishes the passed functions as click event handlers on all elements of the wrapped set that toggle between each other with every other trigger of a click event. there are two Parameters, the first one named as listenerOdd which is a function that serves as the click event handler for all odd numbered clicks (1,3,5...) and the second one named as listenerEven which is a function that serves as the click event handler for all even numbered clicks (2,4,6,.....). It will also returns the wrapped set. Let clear it by taking an example which is given below: Example: <%@ Page <html xmlns=""> <head runat="server"> <title></title> <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript"> $(function () { $('#plane').toggle( function (event) { $(event.target) .css('opacity', 0.4); }, function (event) { $(event.target) .css('opacity', 1.0); } ); }); </script> </head> <body> <form id="form1" runat="server"> <div> <img src="images/plane.gif" id="plane" alt="Image" /> </div> </form> </body> </html> Output1: Output2: Output3: ©2016 C# Corner. All contents are copyright of their authors.
http://www.c-sharpcorner.com/UploadFile/sapnabeniwal/event-model-of-jquery/
CC-MAIN-2016-44
refinedweb
1,542
51.38
Created on 2012-05-14 07:43 by ncoghlan, last changed 2013-03-19 00:25 by gregory.p.smith. Reading, it occurred to me that there are various tracing and profiling operations that could be cleanly handled with significantly less work on the part of the tracing/profiling tool authors if the interpreter supported a "-C" operation that was like the existing "-c" option, but *didn't* terminate the options list. The interpreter would invoke such commands after the interpreter is fully initialised, but before it begins the processing to find and execute __main__. Then, to use subprocess coverage with coverage.py as an example, you could just run a command like: "python -C 'import coverage; coverage.process_startup()' worker.py" Other things you could usefully do in such an invocation is reconfigure sys.std(in|out|err) to match the settings used on the invoking side (e.g. to ensure Unicode data is tunnelled correctly), configure the logging module with a custom configuration, configure the warnings module programmatically, enable a memory profiler, etc. Providing a function that could be called from -C and then uses an atexit() handler to do any necessary post-processing may be significantly simpler than trying to use runpy.run_(path|module) to achieve a similar effect. It would be nice to have a comparison of the available alternatives. It's not obvious that asking people to type some "-C ..." boilerplate to get code coverage is very user-friendly. Or am I misunderstanding the request? This can be achieved without intoducing a new interpreter option, using special module. python -m prerun <code> <script> <args>... (It may also be a runpy option). The difficulty that coverage faces is not measuring python programs started from the command line like this, you can use "coverage run myprog.py" or "python -m coverage run myprog.py". The difficulty is when there are subprocesses running python programs. Read for the two current hacks used to invoke coverage on subprocesses. If -C is implemented, it should have a PYTHONRUNFIRST environment variable (or the like) to make these hacks unnecessary. As Ned notes, to cover *implicit* creation of Python subprocesses an environment based solution would be needed to ensure the subprocesses adopt the desired settings. The advantage that has over the current workarounds is that it can be scoped to only affect the parent process when it is executed rather than affecting an entire Python installation. As Serhiy notes, for *direct* invocation, you could use a custom module, but that wouldn't help with the subprocess case. In terms of implementation strategy, as with the -m switch, I'd probably bootstrap into runpy as soon as "-C" is encountered anyway to avoid the need for additional complexity in the C code. One thing that would be useful with this is that it would eliminate some of the demand for -X options, since anything with a Python level API could just use -C instead. To use faulthandler as an example: Current: "python -Xfaulthandler" Alternate: "python -C 'import faulthandler; faulthandler.enable()'" While the second is longer, the advantage is that it's the same as the way you enable faulthandler from Python, so there's no need to learn a special command (and, since its a -X option, the current way doesn't show up in the output of "python --help"). This would also cleanly resolve the request in issue 6958 to allow configuration of the logging module from the command line by allowing you to write things like: python -C "import logging; logging.basicConfig()" script.py The interaction with other logging configuration is obvious (it follows the normal rules for multiple configuration attempts) and doesn't require the invention of new complex rules. Warnings ends up in a similar boat. Simple options like -Wall, -Wdefault or -Werror are easy to use, but more complex configuration options are tricky. With "-C" you can do whatever you like using the Python API. Other tricks also become possible without the need for launch scripts, like testing import logic and fallbacks by messing with sys.path and sys.modules, or patching builtins or other modules. > As Ned notes, to cover *implicit* creation of Python subprocesses an > environment based solution would be needed to ensure the subprocesses > adopt the desired settings. So why aren't you proposing an environment-based solution instead? :) To use the "-C" option, you have to modify all places which launch a Python subprocess. Because I was thinking about a specific case where I *could* configure how the subprocesses were invoked (launching a test server for a web application). It took Ned's comment to remind me of the original use case (i.e. coverage statistics for a subprocesses created by an arbitrary application, *not* a custom test harness). What this would allow is the elimination of a whole class of ad hoc feature requests - any process global configuration setting with a Python API would automatically also receive a command line API (via -C) and an environment API (via PYTHONRUNFIRST). Some existing options (like -Xfaulthandler) may never have been added if -C was available. That's why I changed the issue title (and am now updating the specific suggestion). Actually, there's another use case for you: export PYTHONRUNFIRST="import faulthandler; faulthandler.enable()" application.py All subprocesses launched by the application will now have faulthandler enabled, *without* modifying the application. Doing this in a shell session means that faulthandler will be enabled for all Python processes you launch. Obviously, care would need to be taken to ensure PYTHONRUNFIRST is ignored for setuid scripts (and it would respect -E as with any other environment variable). For faulthandler and coverage would be more convenient option "-M" (run module with __name__='__premain__' (or something of the sort) and continue command line processing).. I've switched back to being -1 on the PYTHONRUNFIRST idea. There are no ACLs for environment variables, so the security implications scare me too much for me to support the feature. The simple -C option doesn't have that problem, though, and could be used as infrastructure in a process infrastructure framework to provide enhanced configuration of Python subprocesses. > I've switched back to being -1 on the PYTHONRUNFIRST idea. There are > no ACLs for environment variables, so the security implications scare > me too much for me to support the feature. I'm quite sure PYTHONHOME and PYTHONPATH already allow you to mess quite freely. That's why we have the -E flag. I'm -0.5 myself, though, for the reason that it complicates the startup process a little bit more, without looking very compelling. It smells disturbingly like LD_PRELOAD to me. > The simple -C option doesn't have that problem, though, and could be > used as infrastructure in a process infrastructure framework to > provide enhanced configuration of Python subprocesses. What do you mean exactly? Nothing too complicated - just noting that a test suite like ours that launches Python subprocesses to test process global state handling could fairly easily arrange to pass appropriate -C options to trigger things like recording coverage data or profiling options. I'll also note that if you put a "preinit.py" on sys.path (e.g. in the current directory if using -m for invocation), you could easily do "-C 'import preinit'" to do arbitrarily complex custom setups, including preconfiguring your test framework. A lot of my thoughts on this come out of looking into migrating the various stdlib modules like trace, pdb and profile over to supporting everything that runpy (and hence the main executable) supports, and a lot of the complexity lies in the mechanics of how to daisy chain the two "__main__" modules together. Running a bit of extra code in __main__ as supplied on the command line before kicking off the full import process helps avoid a lot of pain. >. We are looking for ways to make this as transparent as possible to the tests themselves, just as coverage measurement is now for test suites that don't spawn python subprocesses. describes the two current hacks people can use to invoke coverage on subprocesses. I was hoping for a cleaner more natural solution. > >. Ok, sorry then, I retract what I said. I agree the use case is legitimate. Ned, two questions: in the scenario you just described, is it a requirement that your test suite's code need not be modified (even minimally) to support coverage of subprocesses? And can the solution assume that the test suite is spawning the Python processes in certain standard ways, or must it address all possible ways (even convoluted ones)? If the former, what are the standard ways? I am referring to things like the path to the Python interpreter invoked and how that is obtained, whether the subprocess module is always used, etc. These questions are meant to help pin down the scope of what needs to be satisfied. Chris: The real problem is that it isn't the "test suite" that spawns the processes, the tests invoke product code, and the product code spawns Python. So modifying the Python-spawning really means modifying the product code to do something different under coverage, which most developers (rightfully) won't want to do. My preference is not to assume a particular style of spawning subprocesses, since coverage.py tried quite hard to be applicable to any Python project. I understand that. Sorry, I meant to say "code under test." If you make no assumptions about spawning subprocesses, does this mean, for example, that the solution must satisfy the case of subprocesses invoking a different version of Python, or invoking the same version of Python in a different virtual environment? Chris, I'm not sure how to answer your questions. The more powerful and flexible, the better. There is no "must" here. I'm looking for a way to avoid the hacks coverage.py has used in the past to measure coverage in subprocesses. A language feature that allowed me to externally configure the interpreter to run some of my code first would allow me to do that. Okay, then in the interest of understanding why various alternatives fail, I'll just throw out the suggestion or question that I had in mind because I don't see it mentioned above or on the web page. Why wouldn't it work to define an alias or script that invokes the desired "python -m ...", and then when you call your test suite (using a potentially different "-m ..."), you set sys.executable to that script so that subprocesses in your code under test will invoke it? (coverage.py could do all of this under the hood so that the user need not be aware of it.) Or would this work just fine, but that it's an example of the kind of hack that you're trying to avoid? There are two different use cases here. "-C" tackles one of them, "PYTHONRUNFIRST" the other. My original use case came from working on the Python test suite. In that suite, we have "test.script_helper" which spawns Python subprocesses in order to test various aspects of the startup machinery. I can easily modify script_helper to pass an extra -C argument when gathering coverage data, so I don't need any implicit magic. The -C option also simplifies a whole host of things by letting you use the Python API to perform preconfiguration of various subsystems before executing __main__ normally rather than having to either write a custom launch script (difficult to do with full generality) or adding even more arcane command line options.. Scoping it to a venv would also lessen many of my security concerns with the idea. A simple way to do this would be if pyvenv.cfg could contain a customisation snippet that was executed prior to __main__ invocation (building off the -C machinery) Le lundi 30 juillet 2012 à 00:55 +0000, Nick Coghlan a écrit : >. Well, it shouldn't if you don't start doing "export PYTHONRUNFIRST=...", but instead set it from the calling Python process (possibly from coverage itself). Having to create virtual environments and whatnot just to enjoy this feature sounds terribly tedious. > However, the -C option doesn't cover the case of *implicit* invocation of subprocesses. This is where the PYTHONRUNFIRST suggestion comes in Would a more general solution than PYTHONRUNFIRST be something like a suitably named PYTHONRUNINSTEAD? This would be an arbitrary script to run in place of python any time python was invoked. Alternatively (and less powerfully), it could be a default set of command options to pass to the Python executable. Both of these seem more general than PYTHONRUNFIRST because the 'runas' command could itself be `python -C $PYTHONRUNFIRST ....` > unless -E is specified, then -C $PYTHONRUNFIRST would be implied. To be honest, I *don't* think this latter capability should be built into the core implementation.... so that it doesn't inadvertently affect invocation of other applications (like hg) It seems what you're saying is that you'd want PYTHONRUNFIRST to run only in special situations, rather than as the default. Is there a sense then in which a functionality inverse to -E could be provided? The idea would be that, when running Python, you could somehow instruct that an option like PYTHONRUN* would take effect only for the subprocesses spawned by the main process you're invoking (kind of like a context manager for the invocation of Python itself)? The advantage of this approach would be that a special PYTHONRUNFIRST setting wouldn't take effect unless you explicitly say so. I agree with Antoine: I don't see why this should be a feature of virtualenvs. It's easy to use environment variables in a tightly-controlled way. We don't worry that any of the other environment variables that affect Python execution will somehow escape into the wild and change how Mercurial (or anything else) works. offtopic: Noticed something pretty annoying: If a package uses relative imports, e.g. from . import sibling_module, then it is impossible to run that package as a script, even with the __main__ trick. Why post that complaint here? If there's a case where__main__.__package__ isn't being set correctly by -m, file a separate bug.
http://bugs.python.org/issue14803,
CC-MAIN-2014-35
refinedweb
2,372
53.71
29 July 2009 08:50 [Source: ICIS news] By Salmon Aidan Lee SINGAPORE (ICIS news)--The polyester industry in China is currently in its longest sustained boom, mainly due to easy credit, and the market expects the rally to continue in the near term, sources said on Wednesday. Except for brief periods lasting no more than four weeks in February and mid-May to early-June, prices of polyester grades have maintained an upward trend. Between June and July, prices of almost all grades of polyester rose about yuan (CNY) 200-300/tonne ($30-44/tonne) each week. “This is nothing short of a miracle. The last time we saw such a positive market for such a long, sustained period was in 2002-2003, when the polyester industry was booming,” said a source from Zhejiang Yuan Dong Polyester, a leading producer of synthetic fibres based in eastern China. Polyester producers have maintained healthy margins and reported favourable sales this year, traders said. Prices of partially oriented yarn (POY) 100 denier / 96 filament and polyester staple fibre 1.4 denier rose overall in the past six months, accumulating whopping gains of as much as CNY6,000-8,000/tonne, according to ICIS pricing. Other grades of filament yarns registered even more spectacular gains. For example, drawn texturised yarn 75 denier / 36 filament spiked more than CNY1,000/tonne within a week in late April, and fully drawn yarn 150 denier / 96 filament surged CNY900-1,000/tonne in the first week of April. “We’ve generally seen sales [against daily output] higher than 100%, or at worst, 80-90% in the past few months,” said a source from South Holdings, a producer of filament yarns in eastern ?xml:namespace> “There were occasions of poor sales, when [sales against daily output] fell to around 50-60%, but they were the exceptions rather than the norm and made us wonder if polyesters are truly oversupplied,” said a source from Jiangyin Hua Hong, a producer of polyester fibres in Jiangsu in eastern China. Because of positive sales figures, and profitability sustained by the price spikes, polyester operating rates had also risen significantly in Most market watchers estimated prevailing polyester operating rates in “Previously, in 2004, 2005 or 2006, producing around 70% was considered acceptable, and anything more than that would be a bonus [to the polyester producers],” said a Chinese trader working for Samsung Corp, a South Korean trading house. Product inventories among these polyester producers have also been low, averaging no more than 15 days’ worth for most of the past six months, market observers said. “That’s fantastic, as operating rates [of polyester plants] are actually higher and yet we see brisk sales and low stocks,” said a China-based trader from Shanghai Bulk Chemical. Another trader in “The [local] banks are disbursing loans almost totally freely, and businesses want to keep producing, keep operating in order to keep getting the loans, or even more loans,” the trader said. This has come despite a gradual fall in fabric transaction levels at the benchmark As of 28 July, transaction levels were struggling to be above 3m metres per day. In June, transactions hovered around 4.5m-5m metres per day, while for the most of March, April and May, transaction levels were no less than 5m metres per day. “You can say demand for fabrics, from an ailing textile sector, is not strong. But we would keep producing, keep the stocks as the banks are in no hurry to get back the loans anyway,” said a Chinese trader of filament yarns and fabrics. “This is very weird; “It might be a time bomb. Easy credit is making everybody work overtime and pushing prices up, and end-users, traders all chase after galloping costs of [purified terephthalic acid and monoethylene glycol],” said the official. But like most other market players, the official could not predict when this demand-induced boom would end. “There’s now no peak season, no low season [for the textile industry], just up and up as the downstream markets keep producing, and buying keeps continuing,” said a trader with Zhejiang Material Industry. ($1 = CNY6.83) Yu Guo contributed to this article For more on polyesters,
http://www.icis.com/Articles/2009/07/29/9235740/chinas-polyester-sees-longest-boom-since-03-rally-to.html
CC-MAIN-2014-52
refinedweb
705
53.65
Hi, I upgraded Spiceworks from version 7.5.00074 to 7.5.00101 last week and incoming email stopped working in Helpdesk. We're using Exchange/outlook web access and the only thing that has changed is the aforementioned Spiceworks upgrade. I've reset the email account password and confirmed we can log on OK. When I reset the credentials in Spiceworks Helpdesk settings I get the following error: "Failed to receive email from exchange server .... Message: Undefined namespace prefix" I tried clearing the email server settings and re-entered them - same problem. I also tried a reboot of the server. After this I found the email settings were blank - i.e. they had been cleared. After the reboot I get a different error when I re-enter the email settings, as follows: "Error on incoming settings: unexpected response from the Exchange server received. Are you sure you entered the correct address" I've tried a number of combinations/formats of user name and confirmed they all work in owa - none work in Spiceworks. Finally, I've switched protocol to IMAP and this works fine. What could have caused the problem and what can I do to fix it and switch back to Exchange/owa? Regards, Iain. 1 Reply Aug 17, 2017 at 11:20 UTC Is your OWA server 2003, if so this is no longer supported and wont work. If it is Exchange 2007 this is also no longer supported IMAP will remain your only supported option until you move away from either of the above
https://community.spiceworks.com/topic/2034423-helpdesk-incoming-email-stopped-working-after-spiceworks-upgrade
CC-MAIN-2018-17
refinedweb
258
72.97
Marla Sukesh"> This article is a continuation article of the series “Learn MVC project in 7 days”. Note: In this series I am not going to create a complete project using Web API and angular. I am going to start a new series for that soon. Here we will just cover following three things. I request you to jump to the respective section directly based on your interest. We are pleased to announce that this article is now available as hard copy book you can get the same from and Web API is an Asp.Net technology for creating HTTP based services. Just like Web Forms and Asp.Net MVC, Web API is a flavour of Asp.Net hence it automatically get many abilities of Asp.Net like Forms Authentication, Exception handling etc. Let’s answer couple of questions about Web API. If you are not interested in theory of Web API I recommend you to directly jump to the lab. We are very clear about the purpose of Asp.Net. It’s meant for creating web applications. Web applications are applications which can be accessed via Web. It’s never been sentenced that “Web Applications must have UI”. They can be just some business applications which exposes data via web. Asp.Net Web Forms and Asp.Net MVC are the flavours of Asp.net which caters the UI part. It will be used to create Web based UI applications. Web Service and WCF Service does the same thing. It exposes data to the outside world. Then how come Web API is different from them? Short answer is “Web Services and WCF Services are SOAP based services. Here HTTP will be just used as a transport protocol. Web API is purely HTTP based service. Here there will not be any SOAP involvement”. Let’s understand it in detail. In order to understand this let’s talk about a scenario. We want to send some data from Technology1 to Technology2 where Technology2 is a WCF/Web Service and Communication must happen via internet/web. Web means HTTP. HTTP will let us make requests to a particular URL and with that request it let us pass some data as well. Now as per the data transmission discussion we had in Day 7, Technology1 will convert its data to XML string (or JSON string mostly) and then send it to Technology2. Note: When .Net Web services or WCF services is the point of communication, data will be always formatted as XML string. Point’s worth discuss How Service extracts different parts from incoming data? Now as per our final discussion, When Technology1 send data to service, data will actually contain three things – Actual Data, Validation credentials and method name. At service side it will be very difficult for a service framework to understand each part independently because Service is a universal thing and it should work for everyone. Secondly client can send data in any format. Example, client can send complete data in “Data|Credential|MethodName” format or can send in “Credential|Data|MethodName” format. There is no fixed format. Solution - Standard envelop To tackle this problem industry came up with a standard envelop concept called SOAP envelop. SOAP is nothing but a specialized XML which will encapsulate everything which need to be sent but in standard format. HTTP will send SOAP envelop from client to service and vice versa. Below is the sample SOAP xml for the reference. <?xml version="1.0"?> <soap:Envelope xmlns:soap="" soap: <soap:Body xmlns: <m:MyMethodName> <m:MyData>Data in Json or XML format</m: MyData > </m: MyMethodName > </soap:Body> </soap:Envelope> Note: SOAP is XMLat the end of the day, so it causes two issues. Solution will be pure HTTP based services. Services where there will not be any SOAP envelop. HTTP will directly transfer data from one location to another. This is where REST principle comes to picture. REST says use the existing features of the web in more efficient manner and create services. It say transfer data in the format they represented instead of putting them in SOAP envelop. HTTP based services are completely based on REST principle hence they are also called as REST based services. What are the existing features of web? Solution for Method Name Now in case of SOAP based service (Web and WCF service) every service is identified by an URL. In the same way REST service will be identified with the help of an URL. Difference will be in case of REST service, the way we defined methods is going to be different. In either of the case sending method name as a parameter from client side is not required. Solution for security When we say HTTP, we have a concept of HTTP header and HTTP body both of which have the ability to carry some information. We can always pass credentials as a part of header and data as part of body. To make sure that nobody able to see the data in header and body during transmission we can implement SSL. It make one thing clear, Security will not be an issue. What about the passing data? In this case data will passed directly by HTTP in JSON or XML format. Mostly it will be JSON. WCF Rest was an earlier Microsoft implementation for creating REST based services. WCF was never meant for REST. Its sole purpose was to support SOA. Creating REST services using WCF involved too many steps and adding new feature in the future would have been big issue for Microsoft. A Non WCF developer will not be able create WCF REST service. Asp.Net Web APIwill be much simpler and even a Non WCF developer will be able to create HTTP based service using it. Step 1 - Create a Web API project Step 1.1 Open Visual studio and Click on File>>New>>Project. Select “Asp.Net Web Application” from the dialog box, put some name and click Ok. Step 1.2 Select Empty option,Web API checkbox in the next dialog box and click Ok. Now before we proceed I would like to talk more about above this dialog box. In Day 1 where we started our MVC project I purposely skipped the discussion on this dialog box. Now in future there is not going to be separate Asp.Net MVC, Web API or Web Forms Project. We have Asp.Netand we will create Asp.Net project. In a single Asp.Net project at the same time we may have couple of options of type Web Forms and couple of options of type MVC. There are two sections in dialog box – Template and References. Explanation 1 Let’s say we choose Empty template in the beginning. Now if you want to create a MVC option you have to add couple of references in the project. So manually right click the project, select add reference, choose System.Web.MVC and click Ok. Now do the same for some more references. Instead of that simply check MVC checkbox in the dialog box. Above two options will create an empty project with all the referencesrequired for Asp.Net MVC project. If you believe that your project is also going to contain Web Forms or Web APIsthen simply check the corresponding checkbox as well. Explanation 2 Now you might be wondering what the other templates in the dialog box are? It’s simple. Microsoft believe every project is going to ahve few things common. Like every project is going to have Login screen, master or layout page, error page etc. Microsoft says instead developer go and create them manually every time in every project let visual studio create it automatically. If you take Web Forms template all these common files will be created in Web Forms style. If you take MVC template all these common files will be create in MVC style. Step 2 –Create API Right click the controller folder and select Add>>Controller. This time choose “Web API 2 controller – Empty” option and click Add. Put name of the controller as EmployeeController and click Add. You will notice that a new class get created inheriting from ApiController. It’s going to be our Web API. Step 3 – Create Model Create a new class called Employee inside Model folder as follows. namespace WebAPISample.Models { public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public int Salary { get; set; } } } Step 4 – Create GET action Open EmployeeController put using statement as follows. using WebAPISample.Models; Now create GET action as follows. public Employee GET() { Employee e = new Employee(); e.FirstName = "Sukesh"; e.LastName = "Marla"; e.Salary = 25000; return e; } Step 5 – Execute and Test Press F5 and execute the application. Make request to “/api/Employee” from browser. Note: Above output will be applicable for only chrome browser. We will talk about in detail in next section. Why Api keyword is specified in the URL? Open Global.asax file. Application_Start will be defined as follows. protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } In the project, in App_Start folder you will find a file called WebApiConfig.cs. Open it. It contains following code. namespace WebAPISample { } ); } } } As you can see, Web API specific route is defined inside it. This is the reason why “api” keyword is required. How come GET method got invoked? In this case our HTTP service“Employee” is considered as a resource which will be identified by an URL “”. When HTTP request is sent to this URL, Web API engine check the type of request. In our case type of request is “Get” hence Web API engine make Get method got invoked. How come the request type becomes Get? In this example we are using browser’s address bar to make the request. Request made by browsers address bar will always leads to get request. What about other requests? In Web API simply create four methods named GET, POST, PUT, DELETE respectively. Each method will depict one request type. Now from a testing point of view GET method can be tested easily via browser’s address bar but POST, PUT, DELETE cannot be directly requested via browser.Wehave to use some tool or some UI which will does that for us with the help of some coding. We are going to have a practical lab on same soon. What if we want to define custom methods? In real time scenario we always want to create more than one kind of Get/post/put/delete functions. Example – GetCustomers, GetCustomerById, GetCustomerByDepartment. In that case we have to define multiple routes or we have to change the default route. Look at the following example. config.Routes.MapHttpRoute( name: "SecondRoute", routeTemplate: "api/GetCustomerById/{id} ", defaults: new {controller= "Customer", action= "GetCustomerById" } ); config.Routes.MapHttpRoute( name: "ThridRoute", routeTemplate: "api/{controller}/{action}" );//generic route like Asp.Net MVC How come it’s confirmed that its REST service? Look at the response. There is no SOAP tags involved. We got direct data. Similarly at the time of request we didn’t sent any SOAP XML. Simply made the request using HTTP and done. Why XML is returned as a response? When we made a request to the service, it returned data in the form of XML. Before I answer this, let me make you clear one thing. Yes, data is in XML format but SOAP envelop is gone☻ Now as per the XML format is concerned, data cannot be send between different technologies directly. It must be converted to either XML or JSON string and then transferred. In case of Web API we have returned pure employee data which will get converted to XML string by Web API engine and returned. Do you think it’s an issue? Actually it’s a feature ☻ Web API have a very nice feature called Content negotiation. Client can negotiate for the output content. If client asks for XML, Web API will return XML and if client asks for JSON, Web API will return JSON. In the last test I have used chrome browser. Check the same example in Internet explorer. You will get JSON as response. Does it mean that my web application will have compatibility issues? No. Basically end user will never access Web APIs directly via browser’s address bar. They will use some UI. UI will talk to Web API with the help of some programming languages like C#, JavaScript etc. It means background code which access Web API is always going to be same. When we access Web API using C# or JavaScript by default we get JSON but we can also specify response content type and get XML. We use JavaScript to make static HTML dynamic. With JavaScript we change appearance, value or structure of the existing HTML dynamically. Angular is one of the most demanding JavaScript framework in industry now a days. So I believe at least you should know the basics about it. Angular is a JavaScript framework introduced by Google mainly focusing at Single Page Applications. Note: in this series I am just trying to make all of you familiar with AngularJS. It won’t contain detailed angular topics. Is AngularJS a library? No it’s a framework. What’s the difference between library and Framework? Library provides the set of reusable APIs whereas framework does some special automation along with providing reusable APIs. Example – JQuery is a reusable library which provides set of functions and make dom manipulation and dom traversing easier. .Net is Framework which provides reusable functionalities but it also handles compilation, execution, it makes garbage collection run in the background and make sure unused memory get cleared. So Framework is something which does many things by its own. In order to understand this we have to understand the problems of traditional JavaScript programming. (Read the following explanation again after completion of all the labs in this article) I think you will be able to answer it well after looking at following sample. <!DOCTYPE html> <html xmlns=""> <head> <title></title> <script> var SomeValue; function SetValue() { SomeValue= "Initial Value"; document.getElementById('MyTextbox').value = SomeValue; } function UpdateValue() { SomeValue = "New Value"; } </script> </head> <body > <input type="text" id="MyTextbox" value="" disabled /> <input type="button" id="BtnClick" value="Click Me" /> </body> </html> What we are trying to achieve in above demo? Now let’s understand the problems with above sample code or in simple words traditional JavaScript programming. Solution - angular With Angular we get an ability where we will write our HTML and write JavaScript independent of HTML. At runtime angular will connect JavaScript to HTML dynamically Angular creates a two way binding between UI and JavaScript at runtime. Thus any change in UI value will automatically JavaScript variables and any JavaScript change automatically reflect in UI. Binding is completely runtime hence we get a clear separation between presentation (HTML) and logic (JavaScript). Angular brought MVW architecture in JavaScript programming world. For working with angular we need two thingsJavaScriptand HTML Here is the step by step explanation on working of angular. Don’t worry if you won’tunderstand it 100%,complete the demo and read it again. Step 1 – Download a Angular We will use the same Web API project created in last labfor this demo. Right click the project and select “Manage Nuget Packages”. Search for angular in online section and install “AngularJs core”. Step 2 –Create HTML Create a new folder called HTML in the project and create a new HTML file called SimpleAngular.html as follows. <!DOCTYPE html> <html xmlns=""> <head> <title></title> </head> <body> </body> </html> Step 3 – Include Angular Include Angular.js file in Simple.html file as follows <script src="../Scripts/angular.js"></script> Step 4 - Create Angular module <script> var MyModule = angular.module("MyAngularModule", []); </script> As you can see angular.module function takes two parameter. First parameter is the name of the module and second parameter will be used to specify other dependent modules. We will not get into the second parameter in this series. Note: “MyAngularModule” is the name of the angular module where as “MyModule” is just a JavaScript reference object, Step 5–Create HTML appliaction Attach ng-App directive to body tag as follows. </script> </head> <body ng- </body> As you can see this time entire body is considered as oneapplication. Step 6–Create Controller Create a controller inside module as follows. var MyModule = angular.module("MyAngularModule", []); MyModule.controller("MyController", function ($scope) { }); </script> For now just take $scope as a variable which will encapsulate all the models required for view. We will talk about it in detail soon. Step 7 – Attach Controller to View Simply define a sub section inside body with the help of ‘Div’ tag and attach controller to it. <body ng- <div ng- </div> </body> Step 8 – Define Model data In the controller function defined model data as follows. <script> var MyModule = angular.module("MyAngularModule", []); MyModule.controller("MyController", function ($scope) { $scope.CustomerName = "Sukesh Marla"; $scope.Designation = "Corporate Trainer"; }); </script> Step 9 – Display Model data in View Use following HTML in view to display model data <body ng- <div ng- <span>{{CustomerName}}</span> <span> - </span> <i>{{Designation}}</i> </div> </body> Step 10 – Execute and Test Press F5 and execute the application. Put the physical URL of the html file and check the output. What is $scope It’s a child scope. When angular parser find ng-Controller it creates two things. This new child scope is made available as an injectable parameter to the controllers constructor function as $scope. We define everything which is required for UI (view) as a member of this $scope. What was {{}} signifies? It’s called expression in angular. Angular parser will get the value of variable specified between {{ and }} from current child scope and displays it. What is MVW? We will talk about this at end of the lab3 on angular In this lab we have a small change requirement. Our requirement says “Display CustomerName in disabled textbox”. Step 1 – Change UI design to follows. <body ng- <div ng- <input type="text" value="{{CustomerName}}" disabled /> <span> - </span> <i>{{Designation}}</i> </div> </body> Step 2 – Execute and Test As you can see, change in the UI no more affects JavaScript code. In this lab we will just take the above lab into next level. Requirement Step 1 –Change the UI part Change the body content to following. <div ng- <input type="text" ng- <span>{{CustomerName}}</span><br /> <input type="button" value="Update" ng- </div> As you can see two new directives are introduced. Step 2 – Redefine controller Redefine controller code to following <script> var MyModule = angular.module("MyAngularModule", []); MyModule.controller("MyController", function ($scope) { $scope.CustomerName = "Sukesh Marla"; $scope.Designation = "Corporate Trainer"; $scope.UpdateValue = function () { $scope.CustomerName = "New Updated Value"; } }); </script> Step 3 – Execute and Test In angular View means UI with which user will interact and Model means data required for View. Now let’s talk a little about Controller. This is why we call it Model-View-Whatever. Whatever that can connect view and model. Again this lab is going to be an upgrade for previous lab. In this lab, Step 1 – Create Web API model Create a new class called Customer in Model folder as follows. namespace WebAPISample.Models { public class Customer { public string CustomerName { get; set; } public string Designation { get; set; } } } Step 2 – Create Web API Controller Create a new Web API called Customer in Controller folder. Step 3 – Create GET action Open CustomerController.cs file and put using statement as below. Now create a new action method called GET inCustomerController. Overall picture looks like this. namespace WebAPISample.Controllers { public class CustomerController : ApiController { public Customer GET() { Customer c = new Customer(); c.CustomerName = "Sukesh Marla"; c.Designation = "Corporate Trainer"; return c; } } } Step 4 -Change Controller code in AngularJs side MyModule.controller("MyController", function ($scope,$http) { $http.get("/api/Customer").then ( function (r) { $scope.Customer = r.data; } ); $scope.UpdateValue = function () { } }); What is $http? To make life easier angular provides several useful services. Services are just wrapper over some reusable functionalities. Example $http service will let us make call to Server APIs. When does the instance of $http get created? Angular will create an instance of controller and new child scope when it finds the ng-controller directive. Although services are injected into controller like $scope, services won’t get instantiated in the beginning. It will get instantiated when it is first used. Note: Instance of service will be created only once.After that same object will be reused across all references. It strictly follows singleton pattern. What is $http.get? $http.get will make a get request to server APIs. It is going to be an asynchronous call. In simple words next line after $http.get will execute even before server execution completes. What is the purpose of “then” function used with $http.get? As I said before $http.get makes service call asynchronously. So instead of returning an actual value it will return a special object called Promise object. Promise object exposes a function called “then” which will expect a parameter of type function. Function passed to the “then” function will be executed automatically when execution of Web API completes. Step 5 – Change UI Change the contents in the body section to following markup. <div ng- <input type="text" ng- <input type="text" ng- <input type="button" value="Update" ng- </div> Step 6 – Execute and Test Note: You may get a little delay to textbox to get populate with values Step 7 – Create POST action Create a new action method called POST in CustomerController as follows. public Customer POST(Customer c) { c.CustomerName += " New"; c.Designation += " New"; return c; } Step 8 – Change UpdateValue function Change the UpdateValue function in angular side as follows. <script> var MyModule = angular.module("MyAngularModule", []); MyModule.controller("MyController", function ($scope,$http) { $http.get("/api/Customer").then ( function (r) { $scope.Customer = r.data; } ); $scope.UpdateValue = function () { $http.post("/api/Customer", $scope.Customer).then ( function (r) { $scope.Customer = r.data; } ); } }); </script> Just like GET, POST will return promise object and everything else is same $http.post will send post request to Web API and at server side Web API engine will make POST action get executed. Step 8 – Execute and Test Complete magic of two way binding. In case you want to start with MVC 5 start with the below video Learn MVC 5 in 2 days. Here will complete our Bonus day article - Introduction to Web API and angular. Your comments, Mails always motivates us to do more. Put your thoughts and comments below or send mail to SukeshMarla@Gmail.com Connect us on Facebook, LinkedIn or twitter to stay updated about new releases. For Offline Technical trainings in Mumbai visit StepByStepSchools.Net For Online Trainings visit JustCompile.com or This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Nice Article General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/1012532/Learn-MVC-Project-in-Days-Bonus-day
CC-MAIN-2022-33
refinedweb
3,837
67.55
The Bot Framework used to give you session storage out-of-the-box for free, including once it had been deployed to Azure. With the recent changes to the Bot Framework and Azure that saw the launch of the Azure Bot Service, you have to manage your own storage. This is especially important for session storage, since you will utilize the session in order to store information about the user, helping bot interaction. Luckily, storage management is easy, especially since Microsoft provides libraries for you to easily manage your bot storage in Azure. The first thing you will need to do is download the appropriate Node.JS module: npm install botbuilder-azure --save Then we will add the triple slash directive at the top of the file: /// <reference path="../node_modules/botbuilder-azure/lib/botbuilder-azure.d.ts" /> ...and of course, then we need to import: import * as azure from "botbuilder-azure"; As of the time of this writing, there is a noted bug in the type definition for the botbuilder-azure module that will cause TypeScript transpilation to fail. If you have this issue, instead of import you will need to do a standard JavaScript require(), which will mean no language service support. The other thing you are going to want to do is set up some environment variables. This will rely on the dotenv-extended module: npm install dotenv-extended --save ...and then require it: require("dotenv-extended").load(); As of the time of this writing, the dotenv module does not have a TypeScript definition file. Underneath your require() statement, you can then create a couple of constants: const TABLENAME = process.env.TABLENAME; const STORAGENAME = process.env.STORAGENAME; const STORAGEKEY = process.env.STORAGEKEY; The TABLENAME is the table storage you create in your Azure Storage instance to house this data. The STORAGENAME is the name of your storage instance. Lastly, the STORAGEKEY is one of the keys provided in the properties tab of your storage instance. To instantiate this storage for your bot, right before you create your UniversalBot object, add the following lines of code: var tableClient = new azure.AzureTableClient(TABLENAME, STORAGENAME, STORAGEKEY); var tableStorage = new azure.AzureBotStorage({ gzipData: false }, tableClient); After that, it is just a matter of setting the storage on the bot: var bot = new builder.UniversalBot(conn).set("storage", tableStorage); The added bonus of setting up your own storage is that if you are hosting your bot on Azure through their Bot Service, and you are using their Azure Storage solution, you can make sure that your storage is in the same region as your bot, which will make performance faster. (Photo by Rainer Stropek)
https://codepunk.io/simple-session-management-in-microsofts-bot-framework-with-azure-table-storage/
CC-MAIN-2019-30
refinedweb
441
61.97
Unanswered: Value of converted field not updating on refresh Unanswered: Value of converted field not updating on refresh Hi all! I have a List backed by a Store, with the PullRefresh plugin. One of the fields in my Model is a calculated field. It represents the average of two other fields. (This is for showing disk I/O performance. readOpCountAvgPerSec is the average number of read operations, writeOpCountAvgPerSec is the number of write operations. In the list, I am showing just an average between the two). Code: { name: 'opCountAvgPerSec', type: 'int', convert: function(value, record) { return ((record.get('readOpCountAvgPerSec') + record.get('writeOpCountAvgPerSec')) / 2; } } I set a breakpoint in the convert function and restarted my app. The convert function gets called when the Store is first loaded, as expected, but never gets called again. I tried doing a pull-to-refresh and also explicitly going in my console and calling Ext.getStore('DiskPerformance').load(), but neither case triggered my breakpoint. Is there something else I need to do to make the function be called to re-calculate with new data? Thanks! Looking forward to SenchaCon! - Join Date - Mar 2007 - Location - St. Louis, MO - 35,121 - Answers - 3287 - Vote Rating - 581 You need to set opCountAvgPerSec field as an empty string or something to trigger the convert method to be fired. Code: record.set({ readOpCountAvgPerSec : 1, writeOpCountAvgPerSec : 2, opCountAvgPerSec : '' //triggers the would be the appropriate place to do this if I need this field updated on every refresh? Add a listener to the load event on the Store, then iterate over all items and set the field blank to force the update? Thanks, this is pretty critical info for anyone trying to use 'convert'; I've added this comment to the docs.
http://www.sencha.com/forum/showthread.php?261667-Value-of-converted-field-not-updating-on-refresh
CC-MAIN-2013-48
refinedweb
290
56.76
Created on 2014-08-17 11:42 by grahamd, last changed 2019-10-17 23:01 by pyscripter. In am embedded system, as the 'python' executable is itself not run and the Python interpreter is initialised in process explicitly using PyInitialize(), in order to find the location of the Python installation, an elaborate sequence of checks is run as implemented in calculate_path() of Modules/getpath.c. The primary mechanism is usually to search for a 'python' executable on PATH and use that as a starting point. From that it then back tracks up the file system from the bin directory to arrive at what would be the perceived equivalent of PYTHONHOME. The lib/pythonX.Y directory under that for the matching version X.Y of Python being initialised would then be used. Problems can often occur with the way this search is done though. For example, if someone is not using the system Python installation but has installed a different version of Python under /usr/local. At run time, the correct Python shared library would be getting loaded from /usr/local/lib, but because the 'python' executable is found from /usr/bin, it uses /usr as sys.prefix instead of /usr/local. This can cause two distinct problems. The first is that there is no Python installation at all under /usr corresponding to the Python version which was embedded, with the result of it not being able to import 'site' module and therefore failing. The second is that there is a Python installation of the same major/minor but potentially a different patch revision, or compiled with different binary API flags or different Unicode character width. The Python interpreter in this case may well be able to start up, but the mismatch in the Python modules or extension modules and the core Python library that was actually linked can cause odd errors or crashes to occur. Anyway, that is the background. For an embedded system the way this problem was overcome was for it to use Py_SetPythonHome() to forcibly override what should be used for PYTHONHOME so that the correct installation was found and used at runtime. Now this would work quite happily even for Python virtual environments constructed using 'virtualenv' allowing the embedded system to be run in that separate virtual environment distinct from the main Python installation it was created from. Although this works for Python virtual environments created using 'virtualenv', it doesn't work if the virtual environment was created using pyvenv. One can easily illustrate the problem without even using an embedded system. $ which python3.4 /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 $ pyvenv-3.4 py34-pyvenv $ py34-pyvenv/bin/python Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.prefix '/private/tmp/py34-pyvenv' >>>', '/private/tmp/py34-pyvenv/lib/python3.4/site-packages'] $ PYTHONHOME=/tmp/py34-pyvenv python3.4 Fatal Python error: Py_Initialize: unable to load the file system codec ImportError: No module named 'encodings' Abort trap: 6 The basic problem is that in a pyvenv virtual environment, there is no duplication of stuff in lib/pythonX.Y, with the only thing in there being the site-packages directory. When you start up the 'python' executable direct from the pyvenv virtual environment, the startup sequence checks know this and consult the pyvenv.cfg to extract the: home = /Library/Frameworks/Python.framework/Versions/3.4/bin setting and from that derive where the actual run time files are. When PYTHONHOME or Py_SetPythonHome() is used, then the getpath.c checks blindly believe that is the authoritative value: * Step 2. See if the $PYTHONHOME environment variable points to the * installed location of the Python libraries. If $PYTHONHOME is set, then * it points to prefix and exec_prefix. $PYTHONHOME can be a single * directory, which is used for both, or the prefix and exec_prefix * directories separated by a colon. /* If PYTHONHOME is set, we believe it unconditionally */ if (home) { wchar_t *delim; wcsncpy(prefix, home, MAXPATHLEN); prefix[MAXPATHLEN] = L'\0'; delim = wcschr(prefix, DELIM); if (delim) *delim = L'\0'; joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); return 1; } Because of this, the problem above occurs as the proper runtime directories for files aren't included in sys.path. The result being that the 'encodings' module cannot even be found. What I believe should occur is that PYTHONHOME should not be believed unconditionally. Instead there should be a check to see if that directory contains a pyvenv.cfg file and if there is one, realise it is a pyvenv style virtual environment and do the same sort of adjustments which would be made based on looking at what that pyvenv.cfg file contains. For the record this issue is affecting Apache/mod_wsgi and right now the only workaround I have is to tell people that in addition to setting the configuration setting corresponding to PYTHONHOME, to use configuration settings to have the same effect as doing: PYTHONPATH= so that the correct runtime files are found. I am still trying to work out a more permanent workaround I can add to mod_wsgi code itself since can't rely on a fix for existing Python versions with pyvenv support. Only other option is to tell people not to use pyvenv and use virtualenv instead. Right now I can offer no actual patch as that getpath.c code is scary enough that not even sure at this point where the check should be incorporated or how. Only thing I can surmise is that the current check for pyvenv.cfg being before the search for the prefix is meaning that it isn't consulted. executable's directory and then in the parent directory. If found, open it for use when searching for prefixes. */ { wchar_t tmpbuffer[MAXPATHLEN+1]; wchar_t *env_cfg = L"pyvenv.cfg"; FILE * env_file = NULL; wcscpy(tmpbuffer, argv0_path); joinpath(tmpbuffer, env_cfg); env_file = _Py_wfopen(tmpbuffer, L"r"); if (env_file == NULL) { errno = 0; reduce(tmpbuffer); reduce(tmpbuffer); joinpath(tmpbuffer, env_cfg); env_file = _Py_wfopen(tmpbuffer, L"r"); if (env_file == NULL) { errno = 0; } } if (env_file != NULL) { /* Look for a 'home' variable and set argv0_path to it, if found */ if (find_env_config_value(env_file, L"home", tmpbuffer)) { wcscpy(argv0_path, tmpbuffer); } fclose(env_file); env_file = NULL; } } pfound = search_for_prefix(argv0_path, home, _prefix, lib_python); Yeah, PEP 432 (my proposal to redesign the startup sequence) could just as well be subtitled "getpath.c hurts my brain" :P One tricky part here is going to be figuring out how to test this - perhaps adding a new test option to _testembed and then running it both inside and outside a venv. Graham pointed out that setting PYTHONHOME ends up triggering the same control flow through getpath.c as calling Py_SetPythonHome, so this can be tested just with pyvenv and a suitably configured environment. It may still be a little tricky though, since we normally run the pyvenv tests in isolated mode to avoid spurious failures due to bad environment settings... Some more experiments, comparing an installed vs uninstalled Python. One failure mode is that setting PYTHONHOME just plain breaks running from a source checkout (setting PYTHONHOME to the checkout directory also fails): $ ./python -m venv --without-pip /tmp/issue22213-py35 $ /tmp/issue22213-py35/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" /usr/local /usr/local $ PYTHONHOME=/usr/local /tmp/issue22213-py35/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' Aborted (core dumped) Trying after running "make altinstall" (which I had previously done for 3.4) is a bit more enlightening: $ python3.4 -m venv --without-pip /tmp/issue22213-py34 $ /tmp/issue22213-py34/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" /usr/local /usr/local $ PYTHONHOME=/usr/local /tmp/issue22213-py34/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" /usr/local /usr/local $ PYTHONHOME=/tmp/issue22213-py34 /tmp/issue22213-py34/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' Aborted (core dumped) $ PYTHONHOME=/tmp/issue22213-py34:/usr/local /tmp/issue22213-py34/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' Aborted (core dumped) [ncoghlan@lancre py34]$ PYTHONHOME=/usr/local:/tmp/issue22213-py34/bin /tmp/issue22213-py34/bin/python -c "import sys; print(sys.base_prefix, sys.base_exec_prefix)" /usr/local /tmp/issue22213-py34/bin I think what this is actually showing is that there's a fundamental conflict between mod_wsgi's expectation of being able to set PYTHONHOME to point to the virtual environment, and the way PEP 405 virtual environments actually work. With PEP 405, all the operations in getpath.c expect to execute while pointing to the *base* environment: where the standard library lives. It is then up to site.py to later adjust the based prefix location, as can be demonstrated by the fact pyvenv.cfg isn't processed if processing the site module is disabled: $ /tmp/issue22213-py34/bin/python -c "import sys; print(sys.prefix, sys.exec_prefix)" /tmp/issue22213-py34 /tmp/issue22213-py34 $ /tmp/issue22213-py34/bin/python -S -c "import sys; print(sys.prefix, sys.exec_prefix)" /usr/local /usr/local At this point in time, there isn't an easy way for an embedding application to say "here's the standard library, here's the virtual environment with user packages" - it's necessary to just override the path calculations entirely. Allowing that kind of more granular configuration is one of the design goals of PEP 432, so adding that as a dependency here. It is actually very easy for me to work around and I released a new mod_wsgi version today which works. When I get a Python home option, instead of calling Py_SetPythonHome() with it, I append '/bin/python' to it and call Py_SetProgramName() instead. Excellent! If I recall correctly, that works because we resolve the symlink when looking for the standard library, but not when looking for venv configuration file. I also suspect this is all thoroughly broken on Windows - there are so many configuration operations and platform specific considerations that need to be accounted for in getpath.c these days that it has become close to incomprehensible :( One of my main goals with PEP 432 is actually to make it possible to rewrite the path configuration code in a more maintainable way - my unofficial subtitle for that PEP is "getpath.c must die!" :) I. That workaround would definitely deserve being wrapped in a higher-level API invokable by embedding applications, IMHO. (Added Victor, Eric, and Steve to the nosy list here, as I'd actually forgotten about this until issue #35706 reminded me) Core of the problem: the embedding APIs don't currently offer a Windows-compatible way of setting up "use this base Python and this venv site-packages", and the way of getting it to work on other platforms is pretty obscure. Vict. Yeah, I mainly cc'ed Victor and Eric since making this easier ties into one of the original design goals for PEP 432 (even though I haven't managed to persuade either of them to become co-authors of that PEP yet). PEP 432 will allow to give with fine control on parameters used to initialize Python. Sadly, I failed to agree with Nick Coghlan and Eric Snow on the API. The current implementation (_PyCoreConfig and _PyMainInterpreterConfig) has some flaw (don't separate clearly the early initialization and Unicode-ready state, the interpreter contains main and core config whereas some options are duplicated in both configs, etc.). See also bpo-35706. I. :-) Thanks, Victor, that's great information. > Memory allocator, context, different structures for configuration... it's really not an easy topic :-( There are so many constraints put into a single API!. For example, imagine instead of all the PySet*() functions followed by Py_Initialize() you could do this: PyObject *runtime = PyRuntime_Create(); /* optional calls */ PyRuntime_SetAllocators(runtime, &my_malloc, &my_realloc, &my_free); PyRuntime_SetHashSeed(runtime, 12345); /* sets this as the current runtime via a thread local */ auto old_runtime = PyRuntime_Activate(runtime); assert(old_runtime == NULL) /* pretend triple quoting works in C for a minute ;) */ const char *init = """ import os.path import sys sys.executable = argv0 sys.prefix = os.path.dirname(argv0) sys.path = [os.getcwd(), sys.prefix, os.path.join(sys.prefix, "Lib")] pyvenv = os.path.join(sys.prefix, "pyvenv.cfg") try: with open(pyvenv, "r", encoding="utf-8") as f: # *only* utf-8 support at this stage for line in f: if line.startswith("home"): sys.path.append(line.partition("=")[2].strip()) break except FileNotFoundError: pass if sys.platform == "win32": sys.stdout = open("CONOUT$", "w", encoding="utf-8") else: # no idea if this is right, but you get the idea sys.stdout = open("/dev/tty", "w", encoding="utf-8") """; PyObject *globals = PyDict_New(); /* only UTF-8 support at this stage */ PyDict_SetItemString(globals, "argv0", PyUnicode_FromString(argv[0])); PyRuntime_Initialize(runtime, init_code, globals); Py_DECREF(globals); /* now we've initialised, loading codecs will succeed if we can find them or fail if not, * so we'd have to do cleanup to avoid depending on them without the user being able to * avoid it... */ PyEval_EvalString("open('file.txt', 'w', encoding='gb18030').close()"); /* may as well reuse DECREF for consistency */ Py_DECREF(runtime); Maybe it's a terrible idea? Honestly I'd be inclined to do other big changes at the same time (make PyObject opaque and interface driven, for example). My point is that if the goal is to "move the existing internals around" then that's all we'll ever achieve. If we can say "the goal is to make this example work" then we'll be able to do much more.. On Wed, Feb 13, 2019 at 5:09 PM Steve Dower <report@bugs.python.org> wrote: >.. Steve, you're describing the goals of PEP 432 - design the desired API, then write the code to implement it. So while Victor's goal was specifically to get PEP 540 implemented, mine was just to make it so working on the startup sequence was less awful (and in particular, to make it possible to rewrite getpath.c in Python at some point). Unfortunately, it turns out that redesigning a going-on-thirty-year-old startup sequence takes a while, as we first have to discover what all the global settings actually *are* :) describes an older iteration of the draft API design that was reasonably accurate at the point where Eric merged the in-development refactoring as a private API (see and for details). However, that initial change was basically just a skeleton - we didn't migrate many of the settings over to the new system at that point (although we did successfully split the import system initialization into two parts, so you can enable builtin and frozen imports without necessarily enabling external ones). The significant contribution that Victor then made was to actually start migrating settings into the new structure, adapting it as needed based on the goals of PEP 540. Eric updated quite a few more internal APIs as he worked on improving the subinterpreter support. Between us, we also made a number of improvements to based on what we learned in the process of making those changes. So I'm completely open to changing the details of the API that PEP 432 is proposing, but the main lesson we've learned from what we've done so far is that CPython's long history of embedding support *does* constrain what we can do in practice, so it's necessary to account for feasibility of implementation when considering what we want to offer. Ideally, the next step would be to update PEP 432 with a status report on what was learned in the development of Python 3.7 with the new configuration structures, and what the internal startup APIs actually look like now. Even though I reviewed quite a few of Victor and Eric's PR, even I don't have a clear overall picture of where we are now, and I suspect Victor and Eric are in a similar situation. Note. Since I haven't really written them down anywhere else, noting some items I'm aware of from the Python 3.7 internals work that haven't made their way back into the PEP 432 public API proposal yet: * If we only had to care about the pure embedding case, this would be a lot easier. We don't though: we also care about "CPython interpreter variants" that end up calling Py_Main, and hence respect all the CPython environment variables, command line arguments, and in-process global variables. So what Victor ended up having to implement was data structs for all three of those configuration sources, and then helper functions to write them into the consolidated config structs (as well as writing them back to the in-process global variables). * Keeping the Py_Initialize and Py_Main APIs working mean that there are several API preconfiguration functions that need a way to auto-initialize the core runtime state with sensible defaults * the current private implementation uses the PyCoreConfig/PyMainInterpreterConfig naming scheme. Based on some of Eric's work, the PEP currently suggests PyRuntimeConfig PyMainInterpreterConfig, but I don't think any of us are especially in love with the latter name. Our inability to find a good name for it may also be a sign that it needs to be broken up into three distinct pieces (PySystemInterfaceConfig, PyCompilerConfig, PyMainModuleConfig) I created bpo-36142: "Add a new _PyPreConfig step to Python initialization to setup memory allocator and encodings". I. To Victor: So how does the implementation of PEP-587 help configure embedded python with venv? It would be great help to provide some minimal instructions. Just in case this will be of help to anyone, I found a way to use venvs in embedded python. - You first need to Initialize python that is referred as home in pyvenv.cfg. - Then you execute the following script: import sys sys.executable = r"Path to the python executable inside the venv" path = sys.path for i in range(len(path)-1, -1, -1): if path[i].find("site-packages") > 0: path.pop(i) import site site.main() del sys, path, i, site If. To Steve: I want the embedded venv to have the same sys.path as if you were running the venv python interpreter. So my method takes into account for instance the include-system-site-packages option in pyvenv.cfg. Also my method sets sys.prefix in the same way as the venv python interpreter.
https://bugs.python.org/issue22213
CC-MAIN-2019-47
refinedweb
3,107
51.99
WebEngine Qt Quick Minimal Example QtWebEngine::initialize. #include <QGuiApplication> #include <QQmlApplicationEngine> #include <qtwebengineglobal.h> In the main function we first set the Qt::AA_EnableHighDpiScaling attribute. This lets the web view automatically scale on high-dpi displays. Then we instantiate a QGuiApplication object. Next, we call QtWebEngine:, QGuiApplication::exec() launches the main event loop.(); } QML Code In main.qml we create the top level window, set a sensible default size and make it visible. The window will be filled by a WebEngineView item loading the Qt Homepage. import QtQuick 2.0 import QtQuick.Window 2.0 import QtWebEngine 1.0 Window { width: 1024 height: 750 visible: true WebEngineView { anchors.fill: parent url: "" } } Requirements The example requires a working internet connection to render the Qt Homepage. An optional system proxy should be picked up automatically..
https://doc.qt.io/archives/qt-5.7/qtwebengine-webengine-minimal-example.html
CC-MAIN-2021-10
refinedweb
133
54.79
Book Review: CoffeeScript: Accelerated JavaScript Development samzenpus posted more than 2 years ago | from the read-all-about-it dept. Michael J. Ross writes "For decades, programmers have written computer code in one language, and then programmatically translated that code into another, lower-level form (typically machine code that can be run directly by a microprocessor, or some sort of bytecode that can be interpreted by a virtual machine). For instance, source code written in C or C++ is compiled and assembled into machine code. In web programming, there are emerging languages and other tools for translating code into JavaScript. For instance, Google Web Toolkit allows the programmer to create web apps in Java. The latest addition to this category is CoffeeScript, a language that can be compiled into JavaScript, and is intended to reduce source code size and clutter by incorporating some of the best operators from other Web scripting languages, particularly Ruby. It is also the topic of a new tutorial, CoffeeScript: Accelerated JavaScript Development." Read on to learn what Michael thinks of this book.This book is authored by Trevor Burnham, who is credited as one of the early contributors to the project by Jeremy Ashkenas (the creator and project lead of CoffeeScript) in his foreword to the book. Published by Pragmatic Bookshelf on 3 August 2011, under the ISBN 978-1934356784, CoffeeScript: Accelerated JavaScript Development fills only 138 pages, which is certainly a change of pace from the majority of programming tomes now being released. This book's material is grouped into six chapters, plus four appendices — aside from a preface, which introduces CoffeeScript as well as a word game, which is used as the example project throughout the book. Oddly enough, the preface mentions jQuery, but not as one of the well-known attempts to streamline JavaScript code. The first chapter, "Getting Started," begins by briefly explaining how to install Node and npm (Node Package Manager). These instructions assume that you are following along in a Linux environment or some emulation thereof. They also seem to assume that nothing goes wrong in any of the steps, because no troubleshooting guidance or references are provided. Given the number of moving parts required to get CoffeeScript running, as well as the technical pitfalls that could ensnare a Windows or Mac user, the author should have provided more clear and detailed installation instructions. Also, readers unfamiliar with Linux/Unix may be puzzled by some of the instructions. For instance, page 3 appears to state that the way to check that those two aforesaid packages are on your path, is to simply type in "PATH" (whereas what is needed is "echo $PATH"). From that point forward, the narrative gradually becomes more opaque, with cursory coverage of text editor plug-ins, the "coffee" command line compiler, REPL, "the soak" (an existential chain operator), and the limitations of trying to debug CoffeeScript code. It is quite possible that by the end of this chapter, many readers will decide to not bother trying to learn CoffeeScript, and instead to stick with plain JavaScript, possibly supplemented with jQuery (which is not to say that jQuery code is any easier to read). In the next three chapters, the author presents the basics of CoffeeScript, including how to: define and use functions and their arguments; test conditionals; throw and catch exceptions; understand variable scoping and context; create arrays using splats; accept input from the console; create objects, arrays, and soaks (in more detail than before); iterate over collections; match patterns; define namespaces using modules; and create prototypes and classes. He makes extensive use of examples, which thankfully are concise (unlike some programming books whose example code span far too many lines, and sometimes even multiple pages — forcing the reader to dig through the code, trying to find the important lines). Also, the brevity of CoffeeScript syntax is undoubtedly a factor. However, his concise style extends to the narrative as well, and will likely cause newbies to have to read the material several times — and even then wonder whether they fully grasp the concepts. It seems that the author understands CoffeeScript extremely well, but is not always able to communicate that knowledge to the reader in a patient and comprehensible manner. Chapter 5 is a primer on jQuery, and is apparently included in the book so that the example application (the word game) can be made to work in a web browser — since none of the code or narrative (aside from the example app) appears to be related to CoffeeScript. It would have been more efficient to simply point the reader to an online jQuery tutorial, and then present only the CoffeeScript-specific differences — or just briefly explain how to load CoffeeScript files in an HTML file, which could have been done in a sidebar. The last chapter demonstrates how to run CoffeeScript on a web server, utilizing Node.js, and also explores how the lack of threads in JavaScript can impact Node programming. The example project is made multiplayer using Node, Connect, and WebSocket. The appendices provide answers to the end-of-chapter exercises, alternative methods of running CoffeeScript code, a JavaScript cheat sheet, and a list of a half dozen bibliographic references. This book concludes with a suspiciously-short index, at less than three pages long, which appears to provide only the first or earliest occurrences of the major terms. Consequently, anyone who tries to use this book as a reference work for looking up key terms quickly — or for finding their later occurrences — will likely need to obtain an electronic version of the book, since all e-readers have search functionality. Furthermore, the index is missing some key terms used in the text, such as "function callbacks" and "arbitrary expressions" — heck, it's even missing "expressions," a fundamental concept in any programming language. Prospective readers who wish to learn more about the book, can visit Pragmatic Bookshelf's page, which offers brief descriptions of the book and its author — as does O'Reilly Media's page. But, as of this writing, only the former makes available an e-book version, pre-publication reader comments, a discussion forum, the example source code used in the book, and a link to a page for reporting errata, which already has more than half a dozen items listed. More are present in the text: "add [a] multiplayer capability" (page xx); a lone ")" missing its matching "(" (in Exercise 6, page 34); "in a lot in functions" (page 107; should read "in a lot of functions"); "a[n] overhead" (page 110); "everyone and their dog is" (page 116). The author's writing style is sometimes quirky, which in most cases adds a bit of levity, but occasionally leads to the misuse of terms, e.g., array ranges usage described as "fantastical" (page 43). "BDFL" (page xiii) will prove puzzling at first to most readers. On page xvi, the reader is told that JavaScript "contains multitudes." — multitudes of what? And nothing can excuse the groan-inducing "automagically" (page 100). In terms of the ordering of the topics, one of the most exasperating aspects of this book is the way that many language concepts — such as chained comparisons, and variables being true or false (or "truthy" or "falsy") — are not presented up front, on their own, but mixed in with discussions of other topics, including development of the game application, and even in the answers to the chapter questions (Appendix 1). This makes the book generally unsuitable as a reference, especially when combined with a disappointing index. One might assume that the modest size of this book is a result of the small size of the language itself. But another factor is surely the pithy presentation style for even some of the most important concepts in the language. Perhaps worst of all — especially from the perspective of someone relatively new to programming — some basic concepts are not addressed, or the example code does not address common use cases. For instance, in CoffeeScript, how does one create a block consisting of multiple lines of code? On page 17, indentation is briefly mentioned, but the sample code shows single-line blocks only. Other important ideas are "saved as an exercise" (which may induce flashbacks to exasperating technical college textbooks). Some readers may conclude that the author didn't want to make the effort of fully describing the language, in a more canonical fashion, which would have resulted in a much longer, but more valuable book. It is unclear as to how much of the likely mystification and frustration of the average reader will be due to the writing choices made by the author, and how much can be blamed on the sometimes cryptic syntax of CoffeeScript, evident in the discussion of topics such as function binding (Chapter 2) and keywords (e.g., from page 106, "what.x and @x are, of course, equivalent if and only if what is this." Of course!). Readers are told in the introduction that they do not need to be experts in JavaScript to understand the book's material, and can be amateurs (page xviii). But there are several places in the book where intermediate-level knowledge, at a minimum, would be needed. That sort of difficult material may be another point in the CoffeeScript journey where some readers will decide to eschew learning the language. The production quality of the book is fine, except that the chosen font's ratio of height to width is more than what is usually found in books nowadays; when combined with inadequate spacing among the words within many of the sentences, it makes it difficult for the reader to rapidly scan the material. The e-book version reflects the same minor problem. Yet it makes excellent use of color for syntactically highlighting the code — a feature not seen in the print version. So if you would like to do some JavaScript programming, but without writing any JavaScript, then one possible place to start your journey is CoffeeScript: Accelerated JavaScript Development. As of this writing, it is the only CoffeeScript book on the market. Yet should the language continue growing in popularity, then more substantial and recommendable books will probably become available. Michael J. Ross is a freelance web developer and writer. You can purchase CoffeeScript: Accelerated JavaScript Development from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37268496) It is already the write less, do more library... Re:What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37268592) Obligatory xkcd [xkcd.com] Re:What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37268762) Obligatory XKCD [xkcd.com] You have to click it! CLICK IT NOW!!!! Re:What's wrong with jQuery? (-1) Anonymous Coward | more than 2 years ago | (#37268596) if blacks ever accomplished ANYTHING of lasting value like just one stable black nation, or one revolutionary technological advancement, or if having lots of blacks in a neighborhood meant it was improving and becoming a more pleasant place to live (instead of what that means now that your once beloved home is turning into a crime-ridden drug-filled ghetto where it's not safe to walk the streets), ANYTHING like that, ANYTHING AT ALL, that would do more to end racism than all the liberal political correctness brainwashing in the world. no doubt about it. Re:What's wrong with jQuery? (-1) Anonymous Coward | more than 2 years ago | (#37268644) Re:What's wrong with jQuery? (1) rtfa-troll (1340807) | more than 2 years ago | (#37268636) Re:What's wrong with jQuery? (1) Anonymous Coward | more than 2 years ago | (#37268866):What's wrong with jQuery? (1) slim (1652) | more than 2 years ago | (#37273256) alternatives on servers. I sense a few of reasons for this. One is a bunch of web developers have JS skills they honed on the browser, for the reason given above. Another reason is that the callback oriented programming style required by Node.js is familiar to people writing JS for the browser. And finally -- a technical reason -- because you can now write code once, and run it both on the client and the server. I really like CoffeeScript. It takes an afternoon to learn, it protects you from some of JS's nastiest gotchas (e.g. the weirdness of '=='). It frees you up from the parenthesis hell you get in JS, especially when using anonymous functions as parameters to function calls. Re:What's wrong with jQuery? (1) rock_climbing_guy (630276) | more than 2 years ago | (#37274860) The only thing I find wrong with it is that its seeming similarity to Java and C# makes it easy to expect something in JavaScript to act like something in C#. Re:What's wrong with jQuery? (1) slim (1652) | more than 2 years ago | (#37275130) the way of the meaning of the code. I keep forgetting that parentheses are optional in CoffeeScript function calls; I always feel the code is clearer when I remove them. streams[i].pipe(streams[i+1]) streams[i].pipe streams[i+1] Re:What's wrong with jQuery? (1) overlordofmu (1422163) | more than 2 years ago | (#37276986) Parentheses and white spaces alone do make some magically readable code once you become accustomed to it. Re:What's wrong with jQuery? (1) slim (1652) | more than 2 years ago | (#37283760) I did not for one second intend to demean LISP. Re:What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37268870) Can you use qooxdoo with it easily? Re:What's wrong with jQuery? (1) rtfa-troll (1340807) | more than 2 years ago | (#37269976) Re:What's wrong with jQuery? (1) slim (1652) | more than 2 years ago | (#37273270) Think of CoffeeScript as a Javascript generator. You can generate any JS with it, including JS that calls qooxdoo, or whatever you like. You can even embed literal Javascript, although I've never needed to do it. Re:What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37268662) CoffeScript solves a different problem than jQuery. Though it does have a query library, the core 'compiler' provides an improved language syntax and object system compared to Javascript. You can use jQuery with CoffeScript if you like, it works perfectly. Re:What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37269024) Re:What's wrong with jQuery? (1) luis_a_espinal (1810296) | more than 2 years ago | (#37273794) I don't consider it an improvement. Maybe if you get a hard on for ruby or python. Subjective, ain'tcha? Re:What's wrong with jQuery? (0) Anonymous Coward | more than 2 years ago | (#37268834) It's a hackish DOM wrapper, and little more. Re:What's wrong with jQuery? (1) omnichad (1198475) | more than 2 years ago | (#37269286) To be fair, being hackish is a requirement of being cross-browser. At least you don't have to write hackish code yourself when using jQuery, everything is more likely to "just work" with a few exceptions. Re:What's wrong with jQuery? (1) rickkw (920898) | more than 2 years ago | (#37269358) Re:What's wrong with jQuery? (1) e4g4 (533831) | more than 2 years ago | (#37270302) Re:What's wrong with jQuery? (1) slim (1652) | more than 2 years ago | (#37273976) very well. So who will write ExpressoScript? (1) Dareth (47614) | more than 2 years ago | (#37268566) And then who will write ExpressoScriptDoubleShot? Re:So who will write ExpressoScript? (1) XxtraLarGe (551297) | more than 2 years ago | (#37268726) Re:So who will write ExpressoScript? (0) Anonymous Coward | more than 2 years ago | (#37268838) I'm waiting for AmericanoScript - watered-down and overpriced. Re:So who will write ExpressoScript? (1) wsxyz (543068) | more than 2 years ago | (#37269162) I'm waiting for Americano... Now I'm going to have to break out the Campari and Cinzano. My evening is shot and it's all your fault! Re:So who will write ExpressoScript? (1) tgv (254536) | more than 2 years ago | (#37268864) Shouldn't that be LatteText? Or MaccchiatoSculpt? Re:So who will write ExpressoScript? (1) bjoast (1310293) | more than 2 years ago | (#37269066) Re:So who will write ExpressoScript? (1) Quirkz (1206400) | more than 2 years ago | (#37274666) debugging (1) Anonymous Coward | more than 2 years ago | (#37268684) It must be such a joy to debug programs written in these higher level languages. Especially on internet explorer, where error messages are practically meaningless. Re:debugging (1) Anonymous Coward | more than 2 years ago | (#37268792):debugging (2) Elf Sternberg (13087) | more than 2 years ago | (#37269316):debugging (0) Anonymous Coward | more than 2 years ago | (#37270318) I can't speak to Coffeescript, but debugging GWT is actually one of the bigger selling points of the framework. Even in internet explorer, you can use the Java debugger in your IDE to step through your code just as you'd do with a actual Java application. The only thing that could trip you up is a bug in the framework, but those are pretty much non-existant. not even close to ruby syntax (0) Anonymous Coward | more than 2 years ago | (#37268778) it's an interesting little language but it's syntax when doing callbacks could be cleaner and it's return policy is not so fun in node.js Re:not even close to ruby syntax (1) slim (1652) | more than 2 years ago | (#37273424) case. I personally find all those '});' -- and worse -- bracket clusters in JS and Java, distasteful. Re:not even close to ruby syntax (1) metamatic (202216) | more than 2 years ago | (#37276132) I personally find all those '});' -- and worse -- bracket clusters in JS and Java, distasteful. I find Python-style semantic indentation distasteful. So here we are. yet another language (0) nurb432 (527695) | more than 2 years ago | (#37268882) Just what we need. Re:yet another language (1) bl4nk (607569) | more than 2 years ago | (#37268904) Re:yet another language (2) royallthefourth (1564389) | more than 2 years ago | (#37268958):yet another language (0) Anonymous Coward | more than 2 years ago | (#37268998) The problem with JavaScript is that it's tough to get a team on the same page for quality. CoffeeScript helps solve some of those issues. Re:yet another language (1) bl4nk (607569) | more than 2 years ago | (#37269068) Re:yet another language (0) Anonymous Coward | more than 2 years ago | (#37269122) Maybe get a less shitacular team. If they spent more time writing decent code rather than rubbing one out over the latest web-programming craze, they might get something useful done. Re:yet another language (1) rickkw (920898) | more than 2 years ago | (#37269394) Re:yet another language (0) Anonymous Coward | more than 2 years ago | (#37270018) I think it boils down to the same methodology that produces templating languages for use in PHP, etc. People want to be on the bleeding edge, even if that blood has a bit of Hepatitis C. javascript is inferior (0) Anonymous Coward | more than 2 years ago | (#37270622) I am inclined to say javascript sucks, but it is better than many, lesser known languages. The official language for the web browser should be at least somewhat good, like Python. Re:yet another language (1) outsider007 (115534) | more than 2 years ago | (#37270726):yet another language (0) Anonymous Coward | more than 2 years ago | (#37270798) you can blame it on python programmers who can't wrap their head around anything that doesn't have significant whitespace. Python programmers who want to do front-end web development tend to hate javascript because it doesn't conform to their favorite syntax, and so we end up with the clusterfuck that is coffeescript. Back-end python programmers really won't get much done on the front-end anyway if they don't already have much experience with javascript, and no professional javascript coder is going to jump to coffeescript. coffeescript is really best for personal projects of python/ruby programmers, and should not be used for front-end projects where people are contributing front-end code. choosing coffeescript as the base for the front-end code is to cut out many, many experienced front-end developers from contributing to your project, because they just don't need coffeescript and they shouldn't have to learn it. Re:yet another language (1) drb226 (1938360) | more than 2 years ago | (#37271708) Re:yet another language (1) slim (1652) | more than 2 years ago | (#37273292). (1) luis_a_espinal (1810296) | more than 2 years ago | (#37273548) pushing the envelope (even when things go bad), we would still be wondering whether it is possible to write code without GOTO statements or higher-level languages. From someone who has had to work with JavaScript, I can say that anything that can bring some more sanity to its syntax is a good thing. When one has to rely on a book that explicitly says to cover only its good parts [amazon.com] (a good book mind you), that tells you a lot about the language. Even Brendan Eich, its creator admits its shortcomings (as he was pretty much arm-twisted into rushing in it out before it was ready with a clear mandate to make it look like Java.) Yes, it can be a reliable workhorse, you can still create applications (good applications) with JavaScript as-is ... provided you tuck your elbows, true of any languages, but for a very high-level, sandboxed application language, it is not that much acceptable. But if there is a language that needs a saner-replacement (even if it is just an abstraction as a source-code compiler), JavaScript is that language. With that analogy, I could write modern apps using Java 1.0 instead of Java 1.5 or Java 1.6, but why would you? Same in this case. I have one better (1) roman_mir (125474) | more than 2 years ago | (#37269004) I have developed even a better computer language, here is the syntax: this is the output: it does all that, then it adds $1,000,000 to my bank account and gives me a blow job. Re:I have one better (0) Anonymous Coward | more than 2 years ago | (#37269278) Re:I have one better (1) rubycodez (864176) | more than 2 years ago | (#37269510) Re:I have one better (1) Anonymous Coward | more than 2 years ago | (#37269678) I bet he is lying about his heritage. Re:I have one better (1) jc42 (318812) | more than 2 years ago | (#37269814):I have one better (1) rubycodez (864176) | more than 2 years ago | (#37271252) Re:I have one better (1) jc42 (318812) | more than 2 years ago | (#37280078) Re:I have one better (1) Rizimar (1986164) | more than 2 years ago | (#37271262) Eh, I must be new at this. My input looks the same: But the result is this: Re:I have one better (1) roman_mir (125474) | more than 2 years ago | (#37273020) You just want the wrong thing, it's a nube thing. Uphill both ways in the snow. (1) b.honeydew (1087465) | more than 2 years ago | (#37269048) Re:Uphill both ways in the snow. (3, Informative) Aladrin (926209) | more than 2 years ago | (#37269252). (3, Interesting) Barefoot Monkey (1657313) | more than 2 years ago | (#37269720) Re:Uphill both ways in the snow. (1) slim (1652) | more than 2 years ago | (#37273330):Uphill both ways in the snow. (1) Aladrin (926209) | more than 2 years ago | (#37274028) Maybe he means [github.com] ? Some discussion on why it could be bad: [github.com] Personally, I tend to use classes extensively, so this is a lot less likely to happen. (Because you need to use "this." or "@" for class variables.) Re:Uphill both ways in the snow. (1) angel'o'sphere (80593) | more than 2 years ago | (#37274498) etc. or extensive agriculture where you use a lot of land, likely a less fertile one, and e.g. hold free running cattle there. ;D kinda strange, isn't it? However I see what you want to say with "I tend to use classes extensively", somhow intensiv and extensiv are both the opposite of "rarely" Re:Uphill both ways in the snow. (1) slim (1652) | more than 2 years ago | (#37275666) In the common usage, "extensive" means "having a large extent". In agriculture and physics, it can be used as the opposite of "intensive", but it would only be understood among subject expert peers. Re:Uphill both ways in the snow. (0, Informative) Anonymous Coward | more than 2 years ago | (#37270634) this is bullshit. it doesn't produce better javascript. that is part of the false hype that coffeescripts spew, among many many other false statements. coffeescript is a clusterfuck that's only reason to exist is to cater to python/ruby programmers who don't want to write javascript. Those people shouldn't be coding a front-end language anyway, they don't have the mindset needed for it. A programmer who focuses on front-end javascript will produce far better code than anything a python programmer with coffeescript can produce. Reviewer is illiterate (0, Informative) Anonymous Coward | more than 2 years ago | (#37269170) On page xvi, the reader is told that JavaScript "contains multitudes." — multitudes of what? OF NOTHING IN PARTICULAR, you illiterate fucktard. If you can't be bothered to actually be educated, at least bother to Google stuff before proclaiming your ignorance in public - it's a reference to Whitman's Song Of Myself [wikipedia.org] . On the upside, your review made me want to buy the book as I'm utterly sick of technical authors who seem to feel the need to hold my DICK while I take a piss. Not everything can (or should) be spoon-fed to n00bs; maybe they should just let the adults work and wait for the Coffeescript For Dummies class at DeVry. Re:Reviewer is illiterate (1) rubycodez (864176) | more than 2 years ago | (#37269536) Too much layers (-1) Anonymous Coward | more than 2 years ago | (#37269324) This appears to be the evolution of every programming language 1. Super-complicated (ASM) 2. Super-easy, but hard to understand, and errors are not picked up at compile time (C, Perl, PHP, Javascript) 3. Extensions and Frameworks (OBJC,C++, C++2011, STL, PEAR, CPAN) to make things "easier" but all they do is make things more bloated and aren't adopted by the masses. 4. New programming language that compiles into an older one. (JAVA,LLVM,"Managed" C/C++/Javascript, etc) Too much API cruft in the way. What needs to happen is that these upper-most languages need to "flatten the layers" to use a photoshop analogy, down to just a CPU/GPU-neutral LLVM JIT compiler. This isn't what happens now. I mean, gods, this is exactly what Google Chrome is doing with NACL, except it doesn't get rid of the API cruft in the way. I imagine 30 years from now we'll be wondering why computers still suck at doing basic things. Quit reinventing the damned wheel for no reason. If N00B's were meant to code, they'd want to learn it, they don't need their hand held. Re:Too much layers (1) ArcadeNut (85398) | more than 2 years ago | (#37269412):Too much layers (1) the linux geek (799780) | more than 2 years ago | (#37269748) Re:Too much layers (1) royallthefourth (1564389) | more than 2 years ago | (#37269816) In the "irrelevant" pile since nobody uses them outside the university. Re:Too much layers (0) Anonymous Coward | more than 2 years ago | (#37271488) 2. Super-easy, but hard to understand, and errors are not picked up at compile time (C, Perl, PHP, Javascript) Tons of errors are picked up at compile time with C. 3. Extensions and Frameworks (OBJC,C++, C++2011, STL, PEAR, CPAN) to make things "easier" but all they do is make things more bloated and aren't adopted by the masses. Since when was C++ not adopted by the masses? And complaining about C++0x note being adopted when it was only just finalized? Seriously? Re:Too much layers (1) ultranova (717540) | more than 2 years ago | (#37271632) Most people don't want to learn things for their own sake, they want to get something done and learn just enough to accomplish that. Thanks, but no thanks. (1) Anonymous Coward | more than 2 years ago | (#37269450):Thanks, but no thanks. (1) Gorimek (61128) | more than 2 years ago | (#37272844) Debuggers have been handling this for decades already. You just embed the original line numbers in the generated source. Someone is bound to write that debugger plugin, if they haven't already. Re:Thanks, but no thanks. (1) slim (1652) | more than 2 years ago | (#37273344) ? (3, Insightful) ptr2004 (695756) | more than 2 years ago | (#37269512) Re:Isn't this a worse solution ? (1) BradleyUffner (103496) | more than 2 years ago | (#37270048) I thought the problem with javascript was it was weakly typed , dynamic and not typesafe. I agree with you... But I have friends who argue that those exact problems are actually its strengths. It boggles the mind. Re:Isn't this a worse solution ? (1) Anonymous Coward | more than 2 years ago | (#37270694):Isn't this a worse solution ? (0) Anonymous Coward | more than 2 years ago | (#37272394) There are some drivers who never have an accident, but they see a lot in their rear view mirror... Re:Isn't this a worse solution ? (0) Anonymous Coward | more than 2 years ago | (#37270468) I thought the problem with javascript was it was weakly typed , dynamic and not typesafe so it was very hard to maintain a really large javascript project. I thought coffeescript would be something more like java so that it was easier to write maintainable code. I'm a big fan of strongly-typed languages for the simple reason that I'd rather see code fail and embarrass me at design time instead of popping up in the middle of production. But the biggest frustration for me with JavaScript is that, as implemented in web browsers, trying to simple test datatypes and null objects is a major exercise in frustration. Putting a civilized veneer over JavaScript is all very well and good, but someone really needs to clean up JavaScript itself. Re:Isn't this a worse solution ? (1) slim (1652) | more than 2 years ago | (#37273394) in recognising the bad parts, recognising the good parts, and carving out a subset of the language that allows you to code in an elegant, efficient manner. The community has developed a number of conventions that work around Javascript's nastiest aspects in a pretty satisfactory way -- for example the export/require module system used by Node.js and elsewhere. CoffeeScript has the nice property of working within these guidelines. Re:Isn't this a worse solution ? (1) slim (1652) | more than 2 years ago | (#37273658):Isn't this a worse solution ? (1) angel'o'sphere (80593) | more than 2 years ago | (#37274418) JavaScript is not weakly typed, it is dynamic typed, yes but still strong typed. Re:Isn't this a worse solution ? (0) Anonymous Coward | more than 2 years ago | (#37285756) JavaScript is not weakly typed, it is dynamic typed, yes but still strong typed. Yes it is weakly typed. Try this in JS: alert(8 + "5"); A strongly typed language wouldn't allow this, but JS does conversion for you to allow it to happen. It's also dynamic typed, but like you point out, those two things are very different. Response from the author (2) Trevor Burnham (2451014) | more than 2 years ago | (#37270102) Re:Response from the author (0) Anonymous Coward | more than 2 years ago | (#37276522) If you're fluent in JavaSCript why would you bother? What's the gain? Re:Response from the author (1) maraist (68387) | more than 2 years ago | (#37297580) If you're already fine with nondeterminisitic 'this' values, and are comfortable with your own thing with modular coding, then this doesn't really bring much to the table for you. But I've read my fare share of unreadible javascript code, and normalized structure is not something that would hurt the language/platform. Syntactic sugar (2) Animats (122034) | more than 2 years ago | (#37272036)! (1) Gorimek (61128) | more than 2 years ago | (#37272822) Then again, any language is just another syntax for writing Assembler. Re:Syntax matters! (1) voogzy (1418593) | more than 2 years ago | (#37274280) Don't stop there. :) Assemler too is a kind of syntax sugar for writing machine code. isn't it? And machine code is a kind of 'syntax' so you dont have to make special circuits for everything you want it to do, right? Re:Syntax matters! (1) maraist (68387) | more than 2 years ago | (#37297860) Re:Syntax matters! (0) Anonymous Coward | more than 2 years ago | (#37275540) Clearly you've not done much programming, then. Solving a problem in assembler is an entirely different thing from solving it in a high-level abstract language. Syntax doesn't even enter into it. Re:Syntax matters! (1) maraist (68387) | more than 2 years ago | (#37297846) Re:Syntactic sugar (0) Anonymous Coward | more than 2 years ago | (#37273054) Well, yes, it IS just syntactic sugar. The thing is, that's what the authors tout as its MAIN advantage. The CoffeeScript motto is quite literally: "It's just JavaScript" It's on the first paragraph of the first page of coffeescript.com shit with sugar on is still shit (0) Anonymous Coward | more than 2 years ago | (#37273112) Javascript is shit. Anything that compiles to shit is a shit generator, which is as close to shit as anyone gives a shit about. A friend told me but I didn't believe. (0) Anonymous Coward | more than 2 years ago | (#37273930) So many comments here are a signpost that the old Slashdot is dead.
http://beta.slashdot.org/story/157058
CC-MAIN-2014-35
refinedweb
5,681
69.21
A few weeks ago we talked about the type Future and its use to create asynchronous calls. We saw how to work with blocking calls to obtain the value of the future. We also used callbacks in order to obtain the result of the future asynchronously. However, there are some issues that were left unsaid. And by that I’m referring to transforming the Future without blocking the execution. Future transformations In order to transform futures, as with other Scala basic types, mainly two methods are used: map and flatmap. Map method Map method allows us to change the content of a future by applying a function. For instance, if we have a method to get the first million prime numbers but we want to transform it to return just the first hundred ones, we can apply the map method in the following way: def getFirstMillionOfPrimes(): Future[List[Int]] = ??? getFirstMillionOfPrimes().map( (list: List[Int]) => list.take(100) ) This way we will be transforming the inside of the future without breaking the asynchrony. FlatMap method On the other hand, the flatMap method allows us to apply a function to the content of the future and returning a future in turn. After that, a flatten operation is applied to convert the Future[Future[A]] into a simple Future[A]. What the f…? Better explained with an example. Imagine we want to concatenate the first million prime numbers in a string. To do so, we’ll use a new method: def concatenate(l: List[Int]): Future[String] = ??? and now we perform a flatMap getFirstMillionOfPrimes().flatMap( (list: List[Int]) => concatenate(list) ) //Future[String] And how can we do all this in a more simple way? Easy question. For comprehension to the rescue! With a spoonful of syntactic sugar we can write a much more readable code. for { primes <- getFirstMillionOfPrimes() primesString <- concatenate(primes) } yield primesString This way, the concatenation operation won’t be applied until the prime numbers are obtained with the method getFirstMillionPrimes. This allows us to keep an order when composing asynchronous calls. Besides, if the first asynchronous call fails, the second won’t be conducted. And that’s all for today. Now you know how to change the future. What a shame not to be able to change the past 😦 See you soon!
https://scalerablog.wordpress.com/tag/flatmap/
CC-MAIN-2019-26
refinedweb
381
65.93
Hi,I was trying some preliminary models on a huge single datafile (~150G, each row represents a data point) which is not able to be loaded into memory all at once. Therefore, I wrote a data-iterator as follows for batch-wise loading&training. However, I found the loading procedure is very slow. When the batch size is set to 1024, it takes ~0.9s to load making loading data a bottleneck in the experiment. It seems that torch.utils.data.DataLoader is preferable for those datasets where each data point can be efficiently accessed and not suitable for this case. I was wondering if anyone can provide some recommendations on improving the loading efficiency? Millions of thanks in advance. def data_iterator(data_path, batch_size): print("Loading data in {}".format(data_path)) count = 0 X = list() y = list() with open(data_path, 'rb') as fr: for line in fr: items = line.strip().split('\t') label = int(items[2]) trip = items[5] trip = json.loads(trip) for frame in trip: count += 1 frame = np.asarray(frame) frame = np.reshape(frame,(1,200,50)) X.append(frame) y.append(label) if count % batch_size == 0: yield X, y del X del y X = list() y = list() if len(X)>0: yield X, y
https://discuss.pytorch.org/t/rookie-ask-how-to-speed-up-the-loading-speed-in-pytorch/4714
CC-MAIN-2022-33
refinedweb
207
68.16
30 Sep 11:41 2013 org.Hs.eg.db Dear all, I have a problem with the "org.Hs.eg.db" package and would like to ask for some advice on how to get it to work. Currently, the problem I am facing is that R does not seem to recognize the package, see below for the context, error message and the sessionInfo(). I have been able to make "org.Mm.eg.db" and "org.Sc.sgd.db" work, but "org.Hs.eg.db" is not recognized. I would be grateful for any help. Thanks in advance. /Krakno -- output of sessionInfo(): > source("") > biocLite("org.Hs.eg.db") BioC_mirror: Using Bioconductor version 2.12 (BiocInstaller 1.10.3), R version 3.0.1. Installing package(s) 'org.Hs.eg.db' trying URL '' Content type 'application/zip' length 53311411 bytes (50.8 Mb) opened URL downloaded 50.8 Mb Warning: cannot remove prior installation of package âorg.Hs.eg.dbâ The downloaded binary packages are in C:\Users\<...>\AppData\Local\Temp\RtmpE3cnj9\downloaded_packages > library(org.Hs.eg.db) Error in library(org.Hs.eg.db) : there is no package called âorg.Hs.eg.dbâ > sessionInfo() R version 3.0.1 (2013-05-16) Platform: x86_64-w64] parallel stats graphics grDevices utils datasets methods [8] base other attached packages: [1] BSgenome.Hsapiens.UCSC.hg19_1.3.19 BSgenome_1.28.0 [3] Biostrings_2.28.0 GenomicRanges_1.12.5 [5] IRanges_1.18.4 org.Mm.eg.db_2.9.0 [7] RSQLite_0.11.4 DBI_0.2-7 [9] AnnotationDbi_1.22.6 Biobase_2.20.1 [11] BiocGenerics_0.6.0 BiocInstaller_1.10.3 loaded via a namespace (and not attached): [1] stats4_3.0.1 tools_3.0.1 -- Sent via the guest posting facility at bioconductor.org. _______________________________________________ Bioconductor mailing list Bioconductor@... Search the archives:
http://permalink.gmane.org/gmane.science.biology.informatics.conductor/50667
CC-MAIN-2015-35
refinedweb
295
56.62
How I can use tooltip for QML component. Hi, just wondering since when is there a ToolTip QML object? I don't see any in the documentation so no wonder you are getting errors!? Or am I missing something here? lol (no tooltip, also in my latest Qt version 5.2.1 in QtCreator shows nothing just QToolTip widget). You're right. Here is the link "QML Tooltip...": After some more investigating seems it is part of Qt Quick Components for symbian / harmattan. My mistake, but on the other hand worth having a look at the sources Hi everyone! I still can't find the solution for my problem with tooltip and I've posted the bugreport to "JIRA":. If someone found the solution please post it here. Thanks for the help! author="Eddy" date="1396165453"] Thanks for the reply but I can use the QtQuick Components in my Qt projects. You can use it too if you add to your QML files next lines of code: @ import QtQuick 2.2 import QtQuick.Controls 1.2 //QtQuick Components import QtQuick.Dialogs 1.1 //Dialogs import QtQuick.Window 2.0 //Windows @ But I can't use ToolTip component because the current version of QtQuick doesn't supported it. And you are right I can use my own component for show tooltip and I done this for now. But I think in future release of Qt will be grade to see this component. author="Eddy" date="1396168836"] Hi, I want to share my implementation of ToolTip component. This varian doesn't apply to the best implementation but I think for the begin of the tooltip this is a nice solution for me. The code of ToolTip component looks like: @ import QtQuick 2.0 import QtQuick.Controls 1.1 import QtGraphicalEffects 1.0 Item { id: toolTipRoot height: toolTipContainer.height visible: false clip: false z: 999999999 property alias text: toolTip.text property alias backgroundColor: content.color property alias textColor: toolTip.color property alias font: toolTip.font function onMouseHover(x, y) { toolTipRoot.x = x; toolTipRoot.y = y + 5; } function onVisibleStatus(flag) { toolTipRoot.visible = flag; } Component.onCompleted: {)}}', toolTipRoot.parent, "mouseItem"); newObject.mouserHover.connect(onMouseHover); newObject.showChanged.connect(onVisibleStatus); } Item { id: toolTipContainer width: content.width + toolTipShadow.radius height: content.height + toolTipShadow.radius Rectangle { id: content width: toolTipRoot.width height: toolTip.contentHeight + 10 radius: 10 Text { id: toolTip anchors {fill: parent; margins: 5} wrapMode: Text.WrapAnywhere } } } DropShadow { id: toolTipShadow z: toolTipRoot.z anchors.fill: source cached: true horizontalOffset: 4 verticalOffset: 4 radius: 8.0 samples: 16 color: "#80000000" smooth: true source: toolTipContainer } } @ The code to use it looks like: @ ToolTip { id: tooltip width: 300 //default width is 150px. and height is calculate automatically using the text size. backgroundColor: "yellow" //set the background color textColor: "blue" //set the text colour font.pointSize: 18 //You can use all font settings to set custom font. text: "Some <b>text</b> <i>here</i>"; //You can use HTML tags in text. } @ But Now I have a problem with z-index of tooltip component. I try to understand why z index in my component is not work correctly. If tooltip will show on the login form where both textfields looks like a group you can see the second textfield is overlaps my tooltip. If you optimised this component please post your version here. Thanks for the help! Hi, Thanks for sharing. When you use your tooltip , do you put it as the last part of your dialog? [quote author="Eddy" date="1396200453"]Hi, Thanks for sharing. When you use your tooltip , do you put it as the last part of your dialog? [/quote] No, I use it as a part of TextField. Here's how looks like the code of my login dialog (full source code): @ import QtQuick 2.2 import QtQuick.Controls 1.2 import QtQuick.Dialogs 1.1 import QtQuick.Window 2.0 import QtQuick.Layouts 1.1 import QtGraphicalEffects 1.0 import com.shav.qtforum 1.0 import "../" Window { id: userLoginWindow width: 400 height: 150 minimumWidth: 400 maximumWidth: 400 minimumHeight: 150 maximumHeight: 150 modality: Qt.WindowModal title: "Login" color: "#e8e8e8" property var rootApp: null signal userIsLogIn() function onUserLoginStatus(status) { spinner.running = false; if(status === true) { userLoginWindow.userIsLogIn(); userLoginWindow.close(); } } Component.onCompleted: { if(rootApp !== null && rootApp.manager !== null) { rootApp.manager.userDidLogin.connect(onUserLoginStatus); } } Rectangle { id: contentView anchors {fill: parent; margins: 10} color: "transparent" clip: true BusyIndicator { id: spinner running: false anchors {left: parent.left; bottom: parent.bottom} width: 30 height: 30 } Rectangle { id: userLoginSettings width: parent.width height: parent.height - buttonsRow.height - 10 color: "transparent" clip: true Column { id: settingsColumn width: parent.width height: parent.height spacing: 5 Row { id: userNameRow width: parent.width height: userNameField.height spacing: 20 Label { id: userNameLabel width: 100 height: parent.height verticalAlignment: Qt.AlignVCenter text: "Username: " } TextField { id: userNameField width: parent.width - userNameLabel.width - 20 placeholderText: "Your login name here..." ToolTip { id: tooltip width: 300 backgroundColor: "yellow" textColor: "blue" font.pointSize: 18 text: "Some <b>text</b> <i>here</i>"; } } } Row { id: userPasswordRow width: parent.width height: userPasswordField.height spacing: 20 Label { id: userPasswordLabel width: 100 height: parent.height verticalAlignment: Qt.AlignVCenter text: "Password: " } TextField { id: userPasswordField width: parent.width - userPasswordLabel.width - 20 echoMode: TextInput.Password placeholderText: "Your password here..." } } CheckBox { id: savePassword checked: true text: "Keep me logged in for two weeks" } } } Row { id: buttonsRow width: btnClose.width + btnRegister.width + btnLogin.width height: btnClose.height anchors {right: parent.right; top: userLoginSettings.bottom; topMargin: 10} Button { id: btnClose text: "Close" onClicked: { userLoginWindow.close(); } } Button { id: btnRegister text: "Sign Up" onClicked: { if(rootApp !== null && rootApp.manager !== null) { rootApp.manager.getRegistrationHiddenFields(); userLoginWindow.close(); } } } Button { id: btnLogin isDefault: true text: "Login" onClicked: { if(userNameField.text.length > 0 && userPasswordField.text.length > 0) { if(rootApp !== null && rootApp.manager !== null) { spinner.running = true; userLoginWindow.userIsLogIn(); rootApp.manager.login(userNameField.text, userPasswordField.text, savePassword.checked); } } } } } } } @ The z-index only works for sibling items and the parent, not other items deeper in the item tree and siblings of the parent are not affected by it (sadly), that is why it doesn't work in your code. [quote author="Xander84" date="1396201249"]The z-index only works for sibling items and the parent, not other items deeper in the item tree and siblings of the parent are not affected by it (sadly), that is why it doesn't work in your code.[/quote] Thanks for the reply! Well I'll try to fix it and upload a new version here tomorrow. I could publish my Tooltip version later, it a little bit different :D It's will be grade! Ok here you go, maybe that is useful for someone. I've created a more dynamic tooltip, so usually they are created from JavaScript and not included in the QML layout directly (but can also be done if needed). Tooltip.qml: @ import QtQuick 2.2 Rectangle { id: tooltip property alias text: tooltipText.text property alias textItem: tooltipText property int fadeInDelay: 500 property int fadeOutDelay: 500 property bool autoHide: true property alias autoHideDelay: hideTimer.interval property bool destroyOnHide: true function show() { state = "showing" if (hideTimer.running) { hideTimer.restart() } } function hide() { if (hideTimer.running) { hideTimer.stop() } state = "hidden" } width: tooltipText.width + 20 height: tooltipText.height + 10 color: "#dd000000" radius: 6 opacity: 0 Text { id: tooltipText anchors.centerIn: parent horizontalAlignment: Text.AlignHCenter color: "white" font.pointSize: 10 font.bold: true } MouseArea { anchors.fill: parent onClicked: hide() } Timer { id: hideTimer interval: 5000 onTriggered: hide() } states: [ State { name: "showing" PropertyChanges { target: tooltip; opacity: 1 } onCompleted: { if (autoHide) { hideTimer.start() } } }, State { name: "hidden" PropertyChanges { target: tooltip; opacity: 0 } onCompleted: { if (destroyOnHide) { tooltip.destroy() } } } ] transitions: [ Transition { to: "showing" NumberAnimation { target: tooltip; property: "opacity"; duration: fadeInDelay } }, Transition { to: "hidden" NumberAnimation { target: tooltip; property: "opacity"; duration: fadeOutDelay } } ] } @ The tooltip has a show and hide function to fade it in and out respectively, by default it will destroy itself after it's hidden (the destroyOnHide property can be set to false if you don't want that). Also I have a simple JavaScript file to make it a little easier to create tooltips. TooltipCreator.js @ var component = Qt.createComponent("Tooltip.qml"); function create(text, parent, properties) { if (typeof properties === "undefined") { properties = { anchors: { horizontalCenter: parent.horizontalCenter, bottom: parent.bottom, bottomMargin: parent.height / 8 } }; } properties.text = text; var tooltip = component.createObject(parent, properties); if (tooltip === null) { console.error("error creating tooltip: " + component.errorString()); } else if (properties.anchors) { // manual anchor mapping necessary for (var anchor in properties.anchors) { tooltip.anchors[anchor] = properties.anchors[anchor]; } } return tooltip; } @ manual anchor mapping was necessary because it didn't work with Component.createObject properties!? I don't know if that is a bug or an error on my side. so I use that TooltipCreator like this for example: @ import "TooltipCreator.js" as TooltipCreator ... TooltipCreator.create("text on the tooltip", parentItem).show() @ by default it will fade in, stay visible for 5 seconds and than fade out and destroy itself, the user can click on the tooltip to hide it immediately, also it will be anchored at the bottom center of the provided parent Item (see the TooltipCreator.js) The 3rd optional argument can be used to specify custom properties for the tooltip, e.g. @ TooltipCreator.create("absolute positioned tooltip"), rootItem, { x: 100, y: 50 }).show() @ or set the properties on the item directly @ var tooltip = TooltipCreator.create(qsTr("Network Error!\nPlease check your network connection\nor try again later."), mainView) tooltip.color = "#ddff0000" tooltip.textItem.color = "white" tooltip.show() @ I hope that helps, it's not perfect but an easy way to show a simple tooltip I think. Thanks for sharing Xander! Are you interested in putting it in a wiki page ? We can help you with that if you haven't done it yet. Just let us know. BTW : thanks for all your contributions on Devnet. We are really happy having you on board!!! [quote author="Eddy" date="1396255883"] Are you interested in putting it in a wiki page ? [/quote] Hi, I want to do it but I don't know how I can do it. Could you help me with it. I want to create two version of ToolTip. The one is from the Xander84 and one is a my if you don't mind. The new version of my ToolTip looks like: @ import QtQuick 2.0 import QtQuick.Controls 1.1 import QtGraphicalEffects 1.0 Item { id: toolTipRoot width: toolTip.contentWidth height: toolTipContainer.height visible: false clip: false z: 999999999 property alias text: toolTip.text property alias radius: content.radius property alias backgroundColor: content.color property alias textColor: toolTip.color property alias font: toolTip.font property var target: null function onMouseHover(x, y) { var obj = toolTipRoot.target.mapToItem(null, x, y); toolTipRoot.x = obj.x; toolTipRoot.y = obj.y; } function onVisibleStatus(flag) { toolTipRoot.visible = flag; } Component.onCompleted: { var itemParent = toolTipRoot.target;)}}', itemParent, "mouseItem"); newObject.mouserHover.connect(onMouseHover); newObject.showChanged.connect(onVisibleStatus); } Item { id: toolTipContainer z: toolTipRoot.z + 1 width: content.width + (2*toolTipShadow.radius) height: content.height + (2*toolTipShadow.radius) Rectangle { id: content anchors.centerIn: parent width: toolTipRoot.width height: toolTip.contentHeight + 10 radius: 3 Text { id: toolTip anchors {fill: parent; margins: 5} wrapMode: Text.WrapAnywhere } } } DropShadow { id: toolTipShadow z: toolTipRoot.z + 1 anchors.fill: source cached: true horizontalOffset: 4 verticalOffset: 4 radius: 8.0 samples: 16 color: "#80000000" smooth: true source: toolTipContainer } Behavior on visible { NumberAnimation { duration: 200 }} } @ I think the Xander84 version looks more standard. And I think it's will be great if other developers could have a more variants of implementation the tooltip. [quote author="Eddy" date="1396255883"] BTW : thanks for all your contributions on Devnet. We are really happy having you on board!!![/quote] Thanks! I'm happy be with you on board. I'll want to thank you for your hard work on Qt. bq. I want to do it but I don’t know how I can do it. Could you help me with it. Have a look at : "How to add wiki pages": PS: let Xander decide on his code, since he's the author. Thanks for the link to documentation. I'll check it. [quote author="Eddy" date="1396263262"]PS: let Xander decide on his code, since he's the author.[/quote] Sure, I'll wait the Xander answer. hey, sure you can post it on the wiki if you like, feel free to use the code. maybe I will release some more QML code or apps in the future, actually I just started using QML some month ago and released my first app a week ago, if anybody is interested how it looks on Android: and thanks Eddy, I like to contribute to the community :) Hi, I've created the wiki page "QtQuick_ToolTip_Component": So please read this and if you found any mistakes let me know by email. Thanks for the help. bq. actually I just started using QML some month ago and released my first app a week ago, if anybody is interested how it looks on Android: looks very nice, cool color choice! I took a different approach and tried creating an actual tooltip window. It works pretty well but there are some flaws. See the code: @ import QtQuick 2.2 import QtQuick.Window 2.1 import QtGraphicalEffects 1.0 // Simple tooltip. There are some flaws: // 1. When the tooltip is shown the main window loses focus! There's no way around that currently. // 2. Each tooltip has its own window - so if your app has 100 tooltips there will always be // 100 (hidden) windows open. Probably not great for performance. // 3. You need to provide it with your main window coordinates via mainWindowX and mainWindowY. // this is because there is no way to get screen coordinates in QML currently. MouseArea { hoverEnabled: true property alias text: content.text // You must alias these to the main window positions. property int mainWindowX property int mainWindowY property int xOffset: 20 property int yOffset: 5 onEntered: { window.visible = true; } onExited: { window.visible = false; } Window { id: window flags: Qt.ToolTip | Qt.FramelessWindowHint | Qt.WA_TranslucentBackground | Qt.WindowDoesNotAcceptFocus color: "#00000000" width: frame.width + 5 // Space for drop shadow. height: frame.height + 5 x: mapToItem(null, mouseX, mouseY).x + mainWindowX + xOffset y: mapToItem(null, mouseX, mouseY).y + mainWindowY + yOffset Rectangle { id: frame width: content.contentWidth + 10 // Padding for text. height: content.contentHeight + 10 color: "#f3f2a5" border.width: 1 border.color: "#bebebe" Text { id: content anchors.centerIn: parent } } DropShadow { anchors.fill: frame horizontalOffset: 3 verticalOffset: 3 radius: 5 samples: 16 color: "#80000000" source: frame cached: true fast: true // This looks better for some reason. transparentBorder: true // Required. But there's no documentation so I don't know why. } } } @ QML is not mature enough to do this in a bug-free way yet. If you want it to work well you will have to write a C++ component, which is not too difficult. However, I'm reasonably happy with the above code so I'll wait until the trolls write an official implementation I think. Hey guys, I was happy enough with the tooltip that came with "Button.qml":, so I extracted the relevant parts from its source code (located in C:\Qt\5.3\msvc2013_64\qml\QtQuick\Controls\Private for me) and used it, instead of a custom solution. Here is a minimal example: @ import QtQuick 2.2 import QtQuick.Controls 1.2 import QtQuick.Controls.Styles 1.1 import QtQuick.Controls.Private 1.0 Label { property string tooltip: "hello" MouseArea { id: behavior anchors.fill: parent hoverEnabled: true onExited: Tooltip.hideText() onCanceled: Tooltip.hideText() Timer { interval: 1000 running: behavior.containsMouse && tooltip.length onTriggered: Tooltip.showText(behavior, Qt.point(behavior.mouseX, behavior.mouseY), tooltip) } } }@ I did like the solutions by shav and Xander, but didn't really want to roll a custom solution unless I really needed to. - webmaster128 last edited by I'd love to here your opinion on this approach:
https://forum.qt.io/topic/39591/how-i-can-use-tooltip-for-qml-component/24
CC-MAIN-2019-43
refinedweb
2,615
53.58
Making anti-aliasing in Java work Today I had quite a bad (although, eventually successful) experience of trying to fix anti-aliasing in JDK. The problem is that it is not on by default (at least for those members of the fringe who use something slick like XMonad instead of monstrosities like Gnome) and to turn it on one needs to set the awt.useSystemAAFontSettings Java VM property to one of the supported values (e.g. gasp, or lcd). Now, I'm not really keen on changing the code of every Java application I happen to run on my machine, nor can I add -Dawt.useSystemAAFontSettings=lcd to every Java command line (did they really mean it?!). I started to look for a method to set properties globally, and of course I found suggestions of using swing.properties file. In retrospect, that wasn't a smart thing to try: I wanted to set AWT property, not Swing one, so eventually (by reading JDK source code) I found out that Java wasn't loading all the properties from the file, only those few which it knew, and it was obscure about the one I needed. Fast-forward several hours, I found out that there is another interesting file: accessibility.properties. Although JDK only sets the properties that thinks can appear in the file (which isn't very helpful), one of the properties there is really a big step towards the solution, its key is assistive_technologies. This property value is a class name which gets instantiated some time during AWT initialization. Now, if only we could create a class which sets the abominable anti-aliasing property when instantiated, it would solve the problem once and for all... Or would it? We need one more piece of the puzzle: suppose we have the class compiled, how do we make JRE see it, so that it could load it. If JRE doesn't have it in its classpath, an AWTError would be thrown during assistive technologies initialization. Setting classpath on the command line is not going to help us: we specificially wanted to do without changing Java command lines. Setting CLASSPATH environment variable won't help either: as per java(1) man, if classpath is set on the command line, it overrides the CLASSPATH variable completely. And putting the class/jar file into JRE lib directory doesn't make it visible to the system classloader — bummer! Good news: we have the JDK source code and if one knows what to look for, its usually not that hard to find. The thing I was looking for was the list of initial classpath elements. Actually, I could just append my anti-aliasing workaround class into rt.jar, but that's not very flexible. So I found the list, and after a list of JRE jars there was a directory: " classes/"! Since the search is done starting from the JRE home directory, I could just create the classes directory there and put my class there. My workaround class code follows: package hacks; public class AntialiasingHack { public AntialiasingHack() { System.setProperty("awt.useSystemAAFontSettings", "lcd_hrgb"); } } Contents of jre/lib/accessibility.properties (or ~/.accessibility.properties) file: assistive_technologies=hacks.AntialiasingHack PS: If you have a more clean solution (other than filing an RFE for a generic startup properties file loader, arguing that it won't make the system more insecure than it already is, and waiting for several yearsjiffies to get it actually implemented and delivered in the next version of JDK), please-please-pretty-please tell me!
http://blogs.sun.com/navi/
crawl-002
refinedweb
586
59.94
Before you start Here's what to expect from this tutorial, and how to get the most out of it. About this tutorial. Objectives. Prerequisite knowledge To get the most from this tutorial, you should be able to create XML schemas (or document type definitions, also known as DTDs) and XSLT stylesheets. See Resources for developerWorks articles and tutorials that will help you learn these skills. System requirements. The conversion process: A quick reference Here's a summary of the entire process: After you read the tutorial, you might want to return to the following table and use it as a quick reference as you plan, schedule and do the work. Note: You can apply the process described in this tutorial series to XML instance documents based on a document type definition (DTD), as well as those based on a schema. For brevity, I refer only to schema-based documents. The process is applied to the XML instance documents, not the schema or DTD. Table 1. Process steps Apache Ant: Introduction and installation instructions The Apache Software Foundation (see Resources) describes Ant as a Java-based build tool. If you've worked with make, another build tool, Ant's functions will be somewhat familiar to you. For the methodology described in this tutorial, Ant is a process controller and will control these steps for you: - Create working directories. - Determine which files to process. - Create new XML instance documents. - Validate the new XML instance documents against your new schema. - Transform the updated XML instance documents to HTML. Ant gets its processing instructions from a simple XML configuration file that you create. No Java technology programming experience is required. Download and install Ant These instructions assume you're using Windows XP. The Apache Software Foundation states that Ant will run on "...Linux, commercial flavours of UNIX such as Solaris and HP-UX, Windows 9x and NT, OS/2 Warp, Novell Netware 6 and MacOS X". See the online Ant manual for more information. - Download Ant from the Apache site. You'll want the *.zip version for Windows machines. - Uncompress the ZIP file into a directory on your machine. These instructions assume you'll save Ant version 1.6.5 in the C:\Program Filesdirectory. The path to Ant would then be: C:\Program Files\apache-ant-1.6.5 - Open the online manual stored in C:\Program Files\apache-ant-1.6.5\docs\index.html, and read the System Requirements, Installing Ant, and Platform Specific Issues sections. At the very least you'll have to: - Add the C:\Program Files\apache-ant-1.6.5\bindirectory to your path - Create an environment variable for ANT_HOMEwith a value of C:\Program Files\apache-ant-1.6.5 This concludes the Ant installation. However, Ant requires Java™ SE (or EE), so install that next. Download and install Java SE You can install J2SE™ Runtime Environment or J2SE Development Kit. The Runtime Environment is sufficient for the process described in this tutorial. J2EE™ will also work, but is not needed for this process. You will transform XML files, so you also need an XSL transformer. If you install Java SE version 1.4 or later (Runtime or Development Kit), an XSL transformer is included. Otherwise, you need to install an XSL transformer, such as Xalan-Java, separately. For this tutorial, I assume you will download J2SE Runtime Environment 1.4.2 which comes with an XSL transformer. Download information for non-IBM employees The IBM developer kits page has downloads and documentation for current releases of Java SE for various operating systems, including the IBM 32-bit Runtime Environment for Windows. Similarly, the Sun Developer Network (SDN) has Java SE downloads and documentation. Download information for IBM employees A legal agreement between IBM and Sun Microsystems, Inc. requires IBM employees to download Java specifications, reference implementations or test compatibility kits only from the Java Information Manager (JIM) IBM intranet site. IBM employees may not download them from the Sun Microsystems site, nor the Java Community Process (JCP) site. However, if IBM employees need only the Runtime Environment (as is the case for this tutorial), and are not shipping Java technology functionality within products they're developing, they may download the IBM Java Runtime (version 1.4.2 SR5 for Windows, currently) from the IBM Standard Software Installer (ISSI) IBM intranet site. The ISSI installation process handles the necessary machine configuration steps for you. Regardless of your download source, please read the system requirements and installation instructions carefully. Create a build.xml file for Ant Ant refers to an XML configuration file that you create for its processing instructions. You may give any name to this file; by default, it looks for a file named build.xml. You can create a build.xml file that instructs Ant to: - Create working directories. - Determine which files to process. - Create new XML instance documents. - Validate the new XML instance documents against your new schema. - Transform the updated XML instance documents to HTML. It's important to note that Ant is an extremely flexible tool and has a much wider variety of functions available than what I introduce here. The documentation that comes with Ant is very good; it's stored in the /docs directory under the primary Ant directory on your machine. The information in the /manual directory will be most helpful as you begin coding your build.xml files. Augment the descriptions below with a review of their functions in the Ant manual. How the build.xml file is structured The build.xml file is composed of one or more property settings and a set of processing instructions. Each processing instruction is called a target, and is contained within a target element. A target can convey several pieces of information, such as: - The target's name - Description - The name of the target that must be executed before this one - Base, source, destination, and classpath directories associated with the target - File names and file extension names associated with the base and destination files referenced by the target ...and many other optional values, depending on your use of Ant. A sample build.xml file explained First, review Directory-based tasks in your Ant manual before proceeding; it will help you understand the directory-related syntax in the examples below. When you're ready to proceed, refer to A sample build.xml file in a separate browser window while you read this section. I review each part of the sample build.xml file below. Listing 1. The project element <project name="xml-conversion" default="go" basedir="."> The project element associates the build.xml file with a specific project. Its primary use is to tell Ant which target to start with if none is specified when Ant is run, and the directory, relative to where build.xml is located, from which the file paths in all targets are based. In the sample file, you tell Ant to start with the go target, and that all file paths are relative to the current (.) directory. Listing 2. The description element <description>Converts XML files from version 1 to version 2</description> The description element is meant for humans to read. You should describe what your Ant process does here. Listing 3. The property element <!-- Holds the original source XML files. These aren't changed at all. --> <property name="src-xml" location="v1xml"></property> <!-- Holds XML files that have been converted to V2--> <property name="converted-xml" location="v2xml"></property> <!-- Holds HTML files transformed from V2-based XML files --> <property name="html" location="V2html"></property> You use property elements to define aliases for the directories Ant will use. The name attribute defines the alias, while the location attribute defines the actual file system directory path, relative to the base directory defined earlier in the project element. For example, you defined the alias src-xml for the actual directory named v1xml. Because you previously defined the base directory to be the current (.) directory, the one where the build.xml file resides, v1xml is, therefore, a subdirectory of the current directory. Listing 4. The target element: init <target name="init" description="Create the directory structure."> <!-- Create the time stamp --> <tstamp></tstamp> <!-- Create the directories for output XML and HTML files --> <mkdir dir="${converted-xml}"></mkdir> <mkdir dir="${html}"></mkdir> </target> You use this target element to create a time stamp ( <tstamp></tstamp>) for the Ant job, and to create the file system directories where Ant will store the XML output from the conversion process (the converted-xml alias) and the HTML output from the transformation of the new XML into HTML (the html alias). Time stamps can be useful if you wish to redirect message or error output from Ant to a file instead of your screen (usually the default). Listing 5. The target element: deleteUnnecessaryFiles <target name="deleteUnnecessaryFiles" depends="init" description="Delete files we don't need."> <delete> <fileset dir="${src-xml}" includes="**/*.*" excludes="**/*.xml"> </fileset> </delete> </target> You use this target element to ensure you're only processing XML files in the source directory. The depends attribute specifies that the init target must be processed before this target. The delete element, which performs the actual file deletion(s), contains a fileset element. The fileset element is where you define: - The directory from which files are deleted (the dirattribute). In our example, the value is the alias src-xml, which corresponds to the v1xmldirectory on the file system. - Which files are to considered for the delete action (the includesattribute). In our example, the value is **/*.*, which means, "All directories under the src-xmldirectory" ( **), and within them, all files ( *.*). - Of those files being considered, which files are excluded from the delete action (the excludesattribute). In our example, the value is **/*.xml, which means, "All directories under the src-xmldirectory" ( **), and within them, all files with xmlfile extensions ( *.xml). Listing 6. The target element: convertToV2 <target name="convertToV2" depends="deleteUnnecessaryFiles" description="Apply the conversion stylesheet to all V1 XML files"> <xslt basedir="${src-xml}" destdir="${converted-xml}" extension=".xml" style="convert-to-v2.xsl" includes="**/*.xml" excludesFile="../excludes.text"> </xslt> </target> This target element is responsible for applying the conversion stylesheet. The stylesheet is applied to all the existing XML files specified in the includes and excludesFile attributes in order to transform them into updated XML files that conform to the new schema. The components of this target are: - The dependsattribute: The value deleteUnnecessaryFileshere means that the deleteUnnecessaryFiles target must be processed before this target. - The xsltelement: - The basedirattribute: The (alias) value src-xmlmeans "look there for files to transform." - The destdirattribute: The (alias) value converted-xmlmeans "store the transformed XML files here." - The classpathattribute: Though not shown in the example, the classpath value specifies the location of the XSL transformer's .jar files. Refer to your Ant version's manual for more information on the possible values, or whether you need this attribute at all. Your version of Ant might scan your machine's classpath by default to look for and use the first TrAX-compliant (the Java Transformation API for XML) XSL processor it encounters, negating the need for this classpath attribute. For example, both Xalan 2 and Saxon are TrAX-compliant XSL processors. - The extensionattribute: The file extension .xmlmeans "the transformed files should have the .xml file extension." - The styleattribute: The value of convert-to-v2.xslmeans "transform the files using the stylesheet named convert-to-v2.xsl." - The includesattribute: You've seen this before, and it means the same thing in this context: Include all the files with .xml extensions in all the directories within the directory named in the basedirattribute. - The excludesFileattribute: With this attribute, Ant gives you the capability to list, in a separate file, the names of individual files (wildcards accepted) that are to be excluded from processing, even if they meet the criteria established by the includesattribute. Each line of the file expresses a pattern that should identify one or more files. This is very helpful if you know you have files that don't meet certain criteria necessary to process them further, such as: down-level, pre-production, archived Listing 7. The target element: validateV2 <target name="validateXML" depends="convertToV2" description="Validates all newly-updated XML files against employee2.xsd" <xmlvalidate failonerror="yes"> <fileset dir="${converted-xml}" includes="**/*.xml"> </fileset> <attribute name="" value="true" /> <attribute name="" value="true" /> <property name="" value="E:\developerworks\library\tom\toms-xml-tutorial\employee2.xsd"/> </xmlvalidate> </target> This target element validates the newly-updated XML files against the new schema. The components of this target you haven't seen previously are: - The xmlvalidateelement: This is the element that does the work. Within it is a failonerrorattribute, and two attributeelements (an unfortunately confusing name for an element) you haven't see before: - The failonerrorattribute: The attribute value of truemeans "Stop the Ant build if an invalid file is found." If set to no, the build will continue, even if invalid documents are found. - The first attributeelement tells Ant to use its built-in JAXP parser to perform the validation. - Since JAXP's default setting is not to be namespace-aware, you need to specify the second attributeelement, which essentially turns on namespace awareness. - The propertyelement: Here you set a property to tell Ant where the schema is located. You do this because the output XML files in this project will not have a schema declaration within them. You don't need this property otherwise. Listing 8. The target element: transformToHtml <target name="transformToHTML" depends="convertToV2" description="Transforms all V2 xml documents into HTML."> <xslt basedir="${converted-xml}" destdir="${html}" extension=".html" style="transform-to-html.xsl" includes="**/*.xml" excludesFile="../excludes.text"> </xslt> <fixcrlf srcdir="${html}" destdir="${html}" tab="remove" tablength="2" eol="crlf" includes="**/*.html"> </fixcrlf> </target> This target element is responsible for applying a stylesheet that transforms the updated XML files into HTML. The only new attribute of this target is fixcrlf, which will convert, in the HTML files produced: - Any tab characters to (2) spaces - Any eol characters to crlf (carriage return + line feed) ...and save the HTML back into the same (alias html) directory. Listing 9. The target element: go <target name="go" depends="transformToHTML"></target> This is the target element, named as the default target, Ant is to start its execution with if no other target is specified. Refer back to the description of the <project> element, and see where you named go as the default. The go target depends on the transformToHTML target, which has its own dependency, and so on. Listing 10. The target element: cleanup <target name="cleanup" description="Delete output directories and their contents"> <!-- Delete the created directory trees --> <delete dir="${converted-xml}"></delete> <delete dir="${html}"></delete> </target> This target is useful if you need to delete both output directories (and their contents) with one command. You'll probably run this target many times over the course of a project when you know you have incorrect or incomplete output for whatever reason. Next, I review how Ant is run from the command line and look at some output. Run Ant to create new XML and HTML files Assuming your build file is named build.xml, to run Ant from the command line, simply change directories to the directory where your build file is saved, type ant, and press Enter. If you choose to name your build file something other than build.xml, like build-tom.xml, then you'd type: Listing 11. Refer to a non-standard build file name ant -buildfile build-tom.xml Be sure to read the Ant manual for more command line options, as well as options for running Ant from within Java programs. Ant output The following figure displays what Ant 1.6.5 running on Windows XP returns during and after execution of a simple excercise to validate four XML documents. Listing 12. Sample Ant output Buildfile: validateV2.xml ValidateXML: [xmlvalidate] 4 file(s) have been successfully validated. BUILD SUCCESSFUL Total time: 2 seconds To get this output, I redirected the output to a file named ant-output.txt using the following command at a DOS prompt: Listing 13. Redirect Ant output to a file ant -buildfile validateV2.xml > ant-output.txt Refer to this sample Ant output for an example of the messages you receive if you use Ant to process the sample files included with this tutorial. In conclusion In this second part of this 2-part tutorial series, I introduced and you installed Apache Ant, along with Java SE. You created the XML-based instructions that Ant uses to transform existing XML instance documents into new ones (using your conversion stylesheet). You also incorporated XML file validation into the Ant build process and transformed the newly-updated XML files into HTML. A sample Ant build.xml file is available at Downloads. Also be sure to review Resources for more detailed information and links to XML topics, Ant, Java SE, and related developerWorks information on these topics. Acknowledgments First, thanks to our own Doug Tidwell who pioneered this process here at developerWorks several years ago. We've made some tweaks along the way, but the basic idea was his and we are far better off for it. Doug's Web services contributions and XML contributions to developerWorks have been very popular. Secondly, I have to thank the members of the developerWorks schema and stylesheet development team. Elizabeth, Frank, Jack, and Leah, your willingness to divide and conquer all of the schema and stylesheet work means more than you know. Janet and Kristin, we're grateful that you've joined the team; the list of to-do's never seems to dwindle, no matter how hard we try! I also want to thank our management team. Your encouragement to think creatively, along with the flexibility you continue to allow, makes working for developerWorks the best job in IBM. Download Resources Learn - Automate XML file updates, Part 1: Read Part 1: Acquire Ant and the Xalan XSLT processor. - IBM developer kits: Download current releases of Java SE and view documentation. - IDM Computer Solutions, Inc.: Get the Ultra-Edit text editor. - Sun Developer Network (SDN) Downlaod Java SE and view the documentation. Discuss - developerWorks XML forums: Communicate with other XML developers trying to solve the same problems you are. - developerWorks Community: Visit blogs, forums, podcasts, and wikis hosted by and for developers..
http://www.ibm.com/developerworks/web/tutorials/wa-autoxml2/index.html
CC-MAIN-2015-48
refinedweb
3,062
56.66
#include <sys/sunddi.h> int pci_param_get_ioctl(dev_info_t *dip, intptr_t arg, int mode, pci_param_t *php); Pointer to dev_info structure. The device driver is expected to pass the arguments they receive in their ioctl call directly to this interface. A pointer to a (void *) param handle. The pci_param_get_ioctl() function extracts the params from the arg argument and returns a pci_param_t handle in php. Drivers should call pci_param_free(9F) to free the param handle returned in this call after retrieving params from the handle. Drivers are expected to use pci_plist_get(9F) and pci_plist_getvf(9F) on the param handle to get the name-value list for the PF and VF devices. A valid param handle pointer php is returned The call failed to extract params from arg. The pci_param_get() function can be called from kernel non-interrupt context. See attributes(5) for descriptions of the following attributes: attributes(5), pci_param_free(9F), pci_param_get(9F), pci_plist_get(9F), pci_plist_getvf(9F)
http://docs.oracle.com/cd/E36784_01/html/E36886/pci-param-get-ioctl-9f.html
CC-MAIN-2015-32
refinedweb
153
64.3
Join devRant Search - "console" - -?31 - - - - - OMFG! I just figured out the solution for low fps in every gaming console! I hope this piece of (genius) code get to microsoft/sony!!!22 - console.log('This website owner is a verified shit nugget. Avoid business.'); If you get a bad client, warn others! ;)12 - "Is that a script or a hand job?" A friend's colleague (who's pretty bad at English) that refers to manually typing in to the console as "a hand job".16 - LET'S LEARN ANGULAR2 * look for some good tutorial * * download atom-typescript * * type "ng new demo" in console" 1185 errors. FINISHED LEARNING ANGULAR223 - Rules for server newbees: 1. Never just copy paste stuff from the internet into your console. -- End --18 - Uncle: Programmers who design physics engines do so by typing 1s and 0s on a console. That's why they get paid so much. Me: 🤔🔪10 - Looking at my play console and adMod data, I concluded that : Most of the revenue generated from my app is from the users clicking in-app ads of my competitor and finally migrating. ¯\_(ツ)_/ ¯ | /\1 - Kids, dont try this at home. [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo *CLICK* A.K.A terminal russian roulette.12 - Our CEO gave us a challenge to parse emails from a PDF, first to do it got $100 cash. I came in 2nd place because I forgot to comment out System.out.println and it took too long. The winner offered me the $100 because he just wanted the challenge. I told him to keep it, he earned it.6 - > Open google chrome console (F12) > Press Ctrl + Shift + P (or Cmd + Shift + P) > Type "dark theme" > Press enter Don't thank me, just my duty10 - - Went into Facebook's source code to update the colors from blue to green and black (don't judge me) and saw this in the console log lol. Didn't know people were that gullible...14 - - That moment when you rage-press TAB multiple times on a bash console but that path REALLY doesn't exist..6 - Woke up after not leaving home for 2 days: "Eta to Home: 18 minutes in current traffic" Yeah, thanks Google. Unless there's congestion on the stairs I think it'll be a little quicker than that to reach the kitchen..8 - First law of javascript Always open your browser console while developing Second law Never trust any javascript frameworks7 - 7. 5 hours attempting to reproduce a bug 20 minutes writing test cases 1 minute to write the fix 10 minutes making coffee and running all tests A productive Friday :-/2 - Coworker: "Hey can you look at this site and tell me why its loading so slow?" *inspects console and sees 10 links for stylesheets and 33 script tags and over 200 total http requests. wot n tarnation -___-7 - -.15 - - - - You: working on a terminal with a black background and green foreground Girl: sees the console "are you a hacker?" You: 🎶..all around me are familiar faces..🎶11 - Uninstalling literally everything in my laptop including IDEs and tools. It summed up to 94 programs. I then wrote a simple C# console app that automates the process. It is running 28/94 currently. I love being a programmer.16 - Created a function called upDawg and started sprinkling it all over the code base. Waiting to see who catches it in our next code review. All it does is console logs 'Not much man, you?' - *discovered new tool* Magnificent app which corrects your previous console command, inspired by a @liamosaur tweet. - - - - UX bought to you by the glue sniffers of Microsoft's oAuth console for your webapp. "I tried to SAVE, but accidentally nuked my account instead" oops!8 - - That feeling when you successfully set up a private Git repo on a raspberry pi, hooked up to your continuous delivery system which is building, running tests and deploying to Steam. Then you realise you are the only developer and had way more fun setting it up and working on tooling than you've had actually working on the game you've been trying to finish for over 5 years :'(4 - I know it's not too impressive, but got this working using my Windows console double-buffering system and literal bitmaps for the large numbers. I have posted about both previously if you want more details :312 - Got another 5 star review on my app, which also, according to Play Console, now has over 300 downloads. Life is good. 😁27 - - - Did you know that console.table(arr); will let you print whole JavaScript arrays in table form in console?10 - Just double buffered the Windows console. What you are seeing here is two buffers: one which is empty, and one which has the text "Hello world!", and a pause of 1 second between buffer swapping. This enables accelerated rendering in the Windows command line (By rendering to an off-screen buffer then simply swapping the active buffer), making things like advanced terminal applications in the Windows console possible. And the best part- this is the first compilation of the project. Not a single run-time error. What a fucking satisfying accomplishment, honestly.4 - True web dev power is using the dev console to get rid of modal boxes so you can see the content underneath7 - - - For webdevs who occasionally forget to delete the cache there is a setting in Chromium's/Chrome's and Firefox' Developer Console to automatically delete cache before every reload when the dev console is opened.3 - Google, really? I created all content by myself, all images, textes everything is made by me. And now I strike copyright rules?!? Shut up google._.6 - Solving Errors: Code it. Doesn't do anything, no errors in console. Try again. Doesn't work. *Realizes that you didn't call the function* ffs3 - - - When the pm learns how F12 and use Google console to change HTML style, for example the color of the font. He proclaims produly to everyone, I can code like you guys now.2 - Trying to debug some webpage JavaScript with Edge. Console window doesn't log anything before you open it. You cannot copy-paste more than a single line from it. You cannot search in it. Fuck. Just FUCK.11 - - Read the console message... LOL DIY : Go to Lucidworks.com/vision Open the JavaScript console Click on next, until you get something funny5 - - :)22 - - The most annoying thing about using both bash and browsers is accidentally pressing ctrl + shift + C in the browser and the fucking debug console appearing. I just want to copy some shit from stack overflow!2 - Was making a text based console game last year. Had to know natural human responses. Got too tired of it and make it print "Uhh, I've never had a lot of education, please use easy words." - - - - Couldn't remember how to write to console in c#. Refused to Google it. Wasted probably a good 10 minutes being stubborn. Turns out it was Console.WriteLine not Console.WriteLn6 - The nerdiest way to say happy birthday to someone? Tell them to paste atob("SGFwcHkgQmlydGhkYXkh") in the chrome console/firebug.3 - Anti Rant: Is it just me or are Google Play app updates rolling out really fast... Like i have published some updates recently and they have been live in under 10 mins. Looks like Google got their act together!10 - If you type "12oatmeal" in one of my school assignment console games, it plays a beep. V e r y u s e f u l ™6 - - - Happened way too often: after a bunch of 'git add's, 'git commit's and 'git push's trying to close console with 'git exit'.2 - - - Any firmware developers like me here?? .!! The second class citizens of the world of software development.... People who code in outdated languages, use outdated tools(console print is a luxury) to create cool stuff.3 - I hate it when people start giving me condolences when my code doesn't run. What are you? A console? - - This seems like a good place to give this advice: whenever I'm having a bad day, my console consoles me.2 - - - Just bought a new car, my first with an on board computer system. First thoughts, "how do I 'hack' this thing to add my own shit?" Anyone here ever modified their cars computer system?4 - - - I'm fascinated by the programs in use by stores. I was buying a piece of furniture yesterday and noticed that the employee typed my order using the console. Literally everything - the model, the color, the shipping address...5 - - STOP. FUCKING. REINSTALLING. BROKEN. NVIDIA DRIVERS. WINDOWS 10. DIE IN A FUCKING PIT OF FIRE I CAN’T EVEN WATCH A YOUTUBE VIDEO UNDER 1 FPS1 - - - - *starts install of creators update for windows* *Butthole tightens in anticipation of everything breaking* *Install finishes* *Everything seems to be fine* *NPM start* *Console lights up like Christmas tree* GOD DAMN IT.3 - - Client asks to point their domain to a new 'squarespace' they just got, then call you bc they cannot access the admin console to their old site and 'it's so weird that all the requests are now going to squarespace !!'1 - So...the windows console is getting emoji support. I can't convey how happy it makes me that this is what they've been working on. Very happy. Because of little smiling pictures of yellow people in a command line.4 - - - - For some reason, when testing if a block of code is firing, I always do console.log('fart'); More often than not I forget to remove it before going to production. I feel good knowing that's out there on dozens of sites right now.8 - Setting up a CMS for my personal gamedev with JenkinsCI for automatic testing and continuous delivery to Steams servers. Every time I see JenkinsCI post a success in my slack channel I cheer a little on the inside.3 - a) when i wanted to write a twitter client for the console b) when i automated my job that i had at a school event just the ability to do such stuff is very exciting to me. -. - -not commenting -leaving console logs behind in production -not testing if it works in IE -using root too much -using if instead of switch -never staying consistent with naming conventions -starting projects and never finishing3 - Tried to open 'Recent App Crashes' tab in the Google Play Console app. Play Console crashed. Thanks Google.3 - I'll just leave this here. RIP Firebug. Not only you made me the front end developer I'm today, you also made me a man.4 - I knew I had found the right group of friends when one of them suggested we try SQL Injection on the instant messaging feature of the bowling alley console. Unrelated, do people not think, "hmm, that seems like an unnecessary feature?"2 - - - WINDOWS!!! Why, just why would you think that choosing frigging "Enter" as the copy key in cmd was a good idea?!? At least for pasting, Ctrl+Shift+V works, it just jumps through some menus first, for whatever reason. But Ctrl+Shift+C doesn't work. In general, after using a Linux console a lot recently, everything about the Windows console seems stupid to me.11 - - What do you do when a modal tries to cover up something you're reading? Developer console. Delete div. *Flip off Screen * Ahh, z-index: 300000, how quaint? Delete class. Continue reading. - So apparently Package Manager Console adds 6 hours to the boot time of Visual Studio... I was wondering why it took so long to start up. - Just spent like 5 minutes trying to figure out why my page would raise a blob not found in the console, then finally checked the actual origin script headers and saw this, fuck.. I should go sleep.9 - - - - Fuck you apple! All I want to do is put music on my ancient old iPod via iTunes. I'm not going to spend a penny in your shitty store so why are you insisting that I give you payment details?! This is why I'm a windows user.7 - @dfox sorry for nitpicking, but could you check the "viewport" meta tag? The "-" in "minimum-scale" is missing. I like the Chrome console to be clean :P3 - Submiting a form with Ajax without e.preventDefault() Chrome : Yeah it's all good Firefox : No. Eat shit. Display a length error in console... IE : I'll let you pass but I'll crash right after... I'll never forget again - Once I had to help our graphic designer with a problem and I asked him to show me his console to see the error. He just answered: "I don't own any console". - Microsoft, do you even care what your shitty updates are doing or have you just given up? Not only did the update start immediately after waking up from standby, it also had to brighten up my day by deleting everything afterwards. Turns out the anniversary update gets confused by dual boot systems and then just deletes all partitions. And apparently they didn't manage to fix this for months now. Can't wait for the coming "Creator's update", always wanted to see how an exploding PC looks.2 - - I have created a extension to read devrant feeds in developer console in browser. Check it out. rantConsole (...) Let me know any thoughts.2 - Submitting my changes for review and my CTO catches the line: ```js console.log("It fucking works") ```7 - - - Interviewer: so why should we hirer you? Me: I think the real question is: how much will you pay me if I can make "Hello World!" pop up on the console?4 - I was trying to make sometimng like cheatengine in console and that happened. Its really cool to see it when your friend is told you thats not the thing you should do5 - - Overheard in ikea "they can spy on ya, in your smart TVs and smart kettles, they can spy on ya, I read it in the daily mail" The daily mail, says it all. Was that before or after the story about a page 3 model being abducted by aliens? I don't think the government cares about how many soaps you watch or how infrequently you descale your kettle.6 - Before i found out about unit tests i'd create a console application where i'd test the functions Good times - Using the console to print out variables is a perfectly valid method of debugging for new developers: often, it can help you resolve the problem faster than using a debugger.2 - - - - - 1990, I was about 11. my dad had old computer magazines that contained PRINTED basic games. I used to type those to the gwbasic console on my PC, play some, and then mod them for my younger brother's amusement. - Had to submit a form and couldn't because of some js errors. I hacked my way through with the console to submit none the -. - About two weeks ago, at my workplace, I learnt about Django deployment in Nginx server with Docker and Kubernetes on Google Cloud Console.2 - I always thought my dream was to get into game development. I've released a few over the years but my God it's so fucking tedious and boring. It's 5% creativity and awesomeness, 95% repetitive bullshit. For the love of God, don't do it solo!! Once you've done the game logic all you've got left is hour upon hour upon hour upon shitty boring tedious fucking hour of content creation, and that is worse than a minimum wage data entry job. Get a team and pass it off to some other poor sucker. For the record I don't use unity or unreal, so this is gamedev without their constant crashing and unstable updates. The most exciting bit is creating the framework and tools to try and reduce the time needed for content to creation, but using them? Mind fucking numbing. Even with a project your passionate about. App and tool development is becoming more appealing by the day. Do app developers feel the same about apps?1 - !rant When I need an extra 10 minutes of doing nothing, I hit up my console on full screen, "htop" and leave with the words "ouch, this is gonna take a while". - - Turning a java console application into a swing GUI application isn't as easy as I thought it would be.1 - Old but gold - try this in the Dev Tools Console and see Batman in action: Array(16).join("lol" - 2) + " Batman!";1 - So this guy I know mentions a 7/10 proficiency in web development on his resume and doesn't know about the web console in browsers.6 - I can not believe it took me so long to discover Cmder. I finally have a tabbed console on Windows - - - So I'm trying to check in on a flight via Wizz Air. The passport expiry requires you to use the calendar they have, doesn't accept input. Unfortunately it locks itself into 2019 regardless of what I do. Gf sees me open the console and set the content myself. "What the fuck that is so illegal you bad boy. Oh my god that's fucking amazing!!1!1!". Don't know if I should tell her what I did and how anything in a browser par trying to read Google Play Stores review info with a web crawler isn't all that difficult (fuck that frustrated me, gave up on that in the end.. their ToS don't allow it anyway..) Ah well. Guess I'm a Hacker to somebody in the world now... - - Porting a very old program I wrote from Console to WPF app... looking at the source code, I'm amazed that it has been working all these years...1 - My APHuG class requires us to use a website to keep a bunch of weekly essays together, and today I realized it was acting strange. I checked the console, found some weird error messages, so I checked their sources. And then I found this beauty. What should I do, devRant? Tell the website, or let their poor decisions destroy them?8 - Bought me an Arduino Uno today as part of some cheap china robot arm. The holes in the acrylic don't accommodate the screws so I have to give up on the project for now. Anyway, I tried to read analogue output from it with a joystick module as a quick test. Spent 30 minutes wondering why I couldn't read to console until I realised that bottom console in the Arduino IDE isn't for that... You have your own Serial Monitor *facepalm* - Live coding interview to code tic tac toe console game and I couldn’t even print out the game board. FML.3 - Have you ever copy the the data from the console in chrome? Means the data you print by using console.log(). There is a sure way to copy the data from the chrome console. Even there is many nested objects. I love that feature of chrome.2 - - "Ok, let's see what ffplay offers us ... " * enters 'ffplay -h' into console * holy... freaking.... cow....... (it's still running while writing this "rant") -... - I'm not a beefy dude, But I consider myself as a terminator 🔫 because when I find a BUG I fucking console log the shit out of it ! - That moment when js is like: bro wtf are doing? You don't declare variables types here. then you're like: wtf this is right, it works. until you look at the js console and you grab a cup of bleach. - In the latest update of firefox, the dev console shows all tabs as labels instead of the icons that never really made any sense to me, and in Swedish too! This is a great improvement, I love it! :)1 - Guys has this happened with anyone ..my older aws ec2 instance just vanished from my console but I can still ssh into it, how do I manage it for security groups and other things..?9 - Going back to java after over a year of c and cpp. System.out.println("yeah I still got this"); System.in......what was the console object called again1 - why on Earth do I find PHP error notices in the _JS_ console when debugging this old project... and those notices are even stopping the code from working. seriously, PHP, why??6 - Internet Explorer needs to just die and go to hell where it belongs. Doesn't even give me useful console errors-_-2 - - - There is a lot of talk regarding IDE themes but what about your console? >At home Green text black background bash on Centos >Work Green text black background DOS prompt9 - Surprise surprise, Atari is gonna be back in the hardware business with a new gaming console... -! - Just spent 10 minutes debugging why my game is launching with the console presets and UI only to see that I set my configuration to Console... Well done...2 - The moment of truth when you write "javac name.java" into the console and you are waiting there and thinking "pls no bugs :o" and then it hits you with an error "nooo :(" :D3 - Started testing my most recent side project today... Renaming 1.1TB of movie files according to proper naming conventions over a 100Mbs network. Been running for 11hours already and not even a quarter of the way through9 - - - We came across a bug that only manifested itself in Edge if, and only if, the developer console was closed. Which we only discovered once it went live since during testing we always had the console open to monitor things... D:2 - spent half a day on setting break points and printing shit to console. turned out I closed my parenthesis one term too soon.2 - - - - Finally solved the most elusive bug I have ever encountered. It only occurred in chrome and the reason I could never recreate it is because it didn't happen when developer tools was open WTF! Try solving an apparent JS bug without your console - I've never been this happy/relieved!2 - - If someone asks you to hack facebook just tell him to press F12 and navigate to console. Facebook devs will do their work... + The guy will never ever ask for help4 - - - - Is it worth it to make a UI in c? (console application) Note: That is our school assgignment due next month, make an interactive app using databases in c that runs in console ex) theater seat reservation system4 - Anybody else get frustrated doing online shopping and use the console to filter out the results you want?1 - New Holiday idea: Bring your console to work day. To show what your doing in the time you are not playing with them. PS. Not sexist, your game PC can also come. - - Sometimes I feel like the AWS consoles UI is overly complicated on purpose to discourage using it over the API. - Anyone else add increasingly snarky or desperate comments and console log messages when things aren't working right? My messages are like watching a coder's mental breakdown slowly progress. - Any other old dinosaur here that started their path of the geek with Amiga? Boy, how that console was ahead of its time.3 - Some zygote just came into my shop, and had "PC Master Race" tattooed on his arm... I'm all for pc over console but Lord is that dedication1 - Is anyone else having troubles loading github ? I opened the console and saw their css was being blocked by CORS :D3 - Yesterday: Enjoying my VFIO machine running on Ubuntu. Windows nastiness confined to a VM, full performance graphics. Heaven. Today: Take a system update. Systemd hanging on boot. No console output because systemd helpfully prevents all that from showing. AARGH!1 - The sun is glaring on my laptop screen so badly, that I can't see my dark-theme console. I really hope `git add .` does only what I wanted it to today. That's why we have source control, right? - Is it just me or does the Google Play developer console gets worse and worse with every change they make. Right now its bullshit they add one nice Feature but then fuck up multiple other things at once - console(config)#ip ssh port 22 InCorrect Port-Number : Port-Number Should be in the Range <1025 - 65535> console(config)#4 - When I was 14, I "registered" to Google Play Dev Console. I make apps since then. Most of them are only available in Hungary, but I have some international ideas.4 - Time to learn how to write an MVC Windows Console App in C++ in just a few days while also having 1 presentation, 2 technical demos, and 4 exams this week... - How I envision the package maintainer for gstreamer, every time they're getting ready to push updates, knowing that the end user will have to spend the next 35 minutes in front of their bash console, watching each package build...1 -.... - When adding line breaks to a string that get injected into a html view I always use \r\n instead of just \n. Cus I know one day some smart motherfucker will download one of my webpages with a console app and log out the html to the console to make sure it worked. And when that day comes.. I will have won.1 - This Dev I won't name, Ashley Martins, chown'd the /etc directory rather than her own config, and we didn't have console access, so was unable to ssh in.6 - That moment when you save a file in atom and ie starts up with console open, a paused atom screenshot and an error message :/1 - - - "-Hey, I don't have this method in the proxy -But you just told me you have it in the console" Happy debugging to me - On a stag party in Portugal. Sat in an Irish bar. Friends talking football and I'm more interested in the two guys behind me writing java on their laptops. Why is it so hard to switch off? - Why the F is my console.log not printing to the console!?!?!?!......level left as "Errors only" #doh4 - - I am feeling really stupid right now. How to run devrantron via the console (using manjaro with i3wm, installed via the aur). I feel like i tried everything but i am sure i am overlooking something obvious.1 - Not too long ago I bought 3 monitors. Now I have my IDE on the center, console and debugger (and devrant) on the left, git and music on the right. Still figuring out the best arrangement for all windows but this already feels awesome!3 - So you can stream and play console games or that's what Google's Project Stream aims at. Now that's something to look for.4 - New additional monitor arrived. Now how do I decide whether it goes landscape or portrait?! My middle monitor is landscape as I have several windows side by side while working, so having the new monitor also landscape looks a lot nicer and tidier. But having a portrait monitor at the side for reading and research is perfect, but looks incredibly odd to the point it's distracting. - Hello fellow Ranters, I'm in need of some help, I want to try building a small website, like maybe 4 pages worth of work for my uncle. But I'd like to build it in such a way that a non-programmer (my uncle) could upload photos to a portfolio section through an administrative console page. I'm doing this mostly to learn how to build something like this and also as a side project to help out my uncle. From what I've read, I'm thinking that Angular (maybe?) might be the right way to go about building dynamic pages, but I'm not really sure and was wondering what you guys would suggest? If possible can you please also recommend a place where I can find examples for something like this? Thank you in advance for your help and recommendations, I really appreciate it!!!7 - Can't operate in normal conditions, hmmm... These airplane media systems really need someone to come in and change the game. Linux stack, nice, but most obviously some Linux frontend? 🤔 Although, this is satellite, my rant remains the same! Need to change the game! - I'm currently developing a retro console powered by pico-8 that I'll be putting in front of the co-driver in my car :) Oh and I'll 3d print a handheld version as well.8 - Trying to improve my console experience with Windows, I had antergos with Sindragosa in background and blue console font before, now it's time for Doomguy + yellow font and I like it :P2 -)...2 - ...Firefox I feel like you just stabbed me in the back. Version 49.0.1 I pull out Internet on Mac, navigator.onLine returns false. I pull out Internet on PC (windows 8) same version navigator.onLine returns true even though work offline mode is off. - ! - Does anyone know how to bring the integrated console in VS code to a separate window ? PS: Mac user here wants to see the debug window in another screen1 - Recently i switched from using git with gui tools to just console, and love the speed and reliability increase, but guys do you really resolve merge conflicts in console? Is it effective/worth getting used to?4 - Send a complete & as helpfull as I could imagine bugreport to dropbox. All info about OS version, browser, console messages where their application failed etc. Fuckers send (a bot?) mail back directing me to the faq. You're welcome. Last fucking time! - When you see: "Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." in the Jenkins console log and realize that XCode was updated. - - - Visual studio Code lens. Who thought it was a good idea to have this shit enabled by default? Makes my eyes bleed..5 - I don't like BizTalk. It's very powerful and all but the resource needed to develop, support and maintain far outweigh the benefits. Everything seems half finished, for example the way to deploy, update and the admin console GUI are all a massive core to work with. A small part of me dies every time I end up with a BizTalk project.1 - to lazy to open atom, open git, to commit and push to add/test some features on my website, just used the chrome console to add and test new stuff 🤷♂️ - - So you're the owner or founder of this project? Pls next time don't leave ur console.log like this project is own by your grandparents. Tell me how can I continue with this bs now! Thousand of console and util.log or util.warning wttttfffff!!3 - Might of just shot myself in the foot. Asked user on screen record to open dev tools by pressing f12 and click into console so I could visually see if any errors occur. What have I done...the questions and confusion are overflowing. - deadlines and digitalocean can suck my kiss. if deadlines are made by not talking to developer and digitalocean with its ssh stuff. figuring that out for 2-3 hours with new keys resetting passwords online console. then switched to freaking heroku, was up in 5 minutes - - - tired with chalk to make console look more beautiful ? here is the new thing "..." for node js3 - When the services team asks the mobile team what the response on a request is... And then requests console logging on the app so that they can test their code. - - - - What's the best Linux distribution for servers? I don't want an UI and that fancy stuff. I just want a 1337 hax0r console.11 - Primary debugging tool while working with PHP: print_r(); Primary debugging tool while working with Angular: Developer Console logs Primary debugging tool while working with Node JS: Node Terminal. What's yours?4 - Why couldn't I use ssh remote to start my node.js app? Why must I go into the laggy web console to do deployment? #digitalocean6 - I'm so fond of "joe" as the main console editor. But Arch Linux hasn't it in the repos. Screw you Arch! Keeping Fedora.3 - - Company automatically disables your employee login passwords after every 45 days, which is a good practice for ensuring security. However I get no notifications that my password is being disabled. The result, for the past 4 months, I've been going to IT support requesting them to let me change my password on their admin console because I forgot to change it 'once again'. Sigh.. :/2 - !! - - I was working on a simple notebook project in java (console app) But I think I need a little help : When user wants to edit a note , he should write the note all over again! How can insert the current note in console(like user input) so that the user can iterate and modify the text ? Thanks3 - Logging to the console in an aesthetically appealing manner makes the development experience 1000x better!2 - NOT A RANT Any of you guys and gals on DevRant bought a Nintendo Switch? If Yes, what's your verdict on the console/handheld hybrid? And how's Zelda BoTW?? - Working in google developer console api.. i have this feeling like everything is there but something is missing... and then i google for it.... Voila. - "This debugging session is releaved to be more fractious than expected. Let's clean console and terminal" - - - vim: because best editor ever tmux: split windows and copy/paste in console only systems like servers, although i use it on my pc also. fossil: much better than git, easier to manage1 - - - I was using separate console for running my django project. But then, I discovered run and debug functionality of pycharm. Awestruck. Feeling blessed. - !ng5 Out of nowhere my directive stops working... Didn't change anything there in die last weeks.😥 No console Errors and no console log entries i added. Why? 😥 - - - Can i get some stats? Currently running windhoos, definitely gonna swap to linux but still not sure what distro, my server runs debian 8 and console wise its quite neat. Whats your favorite distro and why?1 - Our Prof has written a "Bandmodell" (band model in English) it should represent a escalator. So we have to do some practical coding challenges and the first one was an escalator control. Everything alright but after that we had to do a timer and had to use his buggy band model just because it had a text field for console output. Why can't we use the console, if everything our application should do, is printing the elapsed time. - Is there a way to increase the text size in the browser's web console? I'm getting older and that tiny text doesn't work for me. I primarily use Firefox.4 - Why node.js tutorials are all about typing stuff on console as if this is the real world example?!?!??!1 - First funky public app with now, a plain chat in the console (does not work on mobile then) - Spawn sandbox console Make change for client (gui bugged) on Friday Listen to complains after weekend why bug appeared again... - - - - Sigh, when you realise your bank is using depracated dojo.js (uncompressed with console warnings) and it wont proceed unless you turn ublock origin off ... - - Help. Has Python changed in version 3.6.5, or is there something wrong with my code?! The following doesn't work: import os def main(): console = input("...") rom = input("...") The following does work: import os console = input("...") rom = input("...") def main() :12 - Idea for the "why did I think of this" pile: SQL console skill for Alexa/Google home. Data storage has never been so frustrating! - Does no one check the dev console before comming to you about site code not working? It says it right there! You can't load a src with http while the site is https. - Top Tags
https://devrant.com/search?term=console
CC-MAIN-2018-47
refinedweb
6,095
73.47
A bit late to the party, here are my solutions on Ruby: Part 1: twos = 0 threes = 0 File.open('day-02_input.txt').each_line do |line| counter = {} line.each_char do |char| next if line.count(char) <= 1 counter[char] = line.count(char) end twos += 1 if counter.value? 2 threes += 1 if counter.value? 3 end puts twos * threes Part 2: boxes = [] File.open('day-02_input.txt').each_line { |box| boxes << box.chomp! } def find_distance pair, distance = 0 pair[0].each_char.with_index do |char, index| distance += 1 if char != pair[1][index] end distance end boxes.combination(2).each do |pair| next unless find_distance(pair) == 1 str = '' pair[0].chars.each_with_index do |_, i| str << pair[0][i] if pair[0][i] == pair[1][i] end puts str end I learnt about the combination method :) We're a place where coders share, stay up-to-date and grow their careers. We strive for transparency and don't collect excess data. re: AoC Day 2: Inventory Management System VIEW POSTVIEW FULL DISCUSSION A bit late to the party, here are my solutions on Ruby: Part 1: Part 2: I learnt about the combination method :)
https://dev.to/pabloxcl/comment/7d55
CC-MAIN-2019-26
refinedweb
192
69.68
On Sun, 2011-12-18 at 16:55 -0800, Eric W. Biederman wrote:> I expect by the time this makes it to "out of the box" experiences on> enterprise distros, useradd and friends will be giving out 1000 or so uids> to new accounts.Hmm...how would that work? Would it be something that would happen atPAM time, like a module that looks up some file in /etc and says "OKthis uid gets this range" and uploads that to the kernel? This whole idea of a normal uid getting *other* slave uids is cool butscary at the same time. So much infrastructure in what I think of as"General Purpose Linux"[1] is built up around a uid - resourcerestrictions and authentication for example.I guess as long as we're sure that all cases where a "uid" crosses auser namespace (say socket credentials) and appears as the right thing,it may be secure.> I think the user namespace will do what you need. Certainly it appears> that everything in your example binary will be allowed by the time it is> done.That's cool, I will keep an eye on what you guys are doing. Looks likethe containers list on linuxfoundation.org is the right one to follow?[1] The code that's shared between RHEL and Debian roughly between thekernel and GNOME, discarding the pointless "packaging" differences
https://lkml.org/lkml/2011/12/20/335
CC-MAIN-2016-36
refinedweb
228
71.75
I am trying to fit some data with a Gaussian (and more complex) function(s). I have created a small example below. My first question is, am I doing it right? My second question is, how do I add an error in the x-direction, i.e. in the x-position of the observations/data? It is very hard to find nice guides on how to do this kind of regression in pyMC. Perhaps because its easier to use some least squares, or similar approach, I however have many parameters in the end and need to see how well we can constrain them and compare different models, pyMC seemed like the good choice for that. import pymc import numpy as np import matplotlib.pyplot as plt; plt.ion() x = np.arange(5,400,10)*1e3 # Parameters for gaussian amp_true = 0.2 size_true = 1.8 ps_true = 0.1 # Gaussian function gauss = lambda x,amp,size,ps: amp*np.exp(-1*(np.pi**2/(3600.*180.)*size*x)**2/(4.*np.log(2.)))+ps f_true = gauss(x=x,amp=amp_true, size=size_true, ps=ps_true ) # add noise to the data points noise = np.random.normal(size=len(x)) * .02 f = f_true + noise f_error = np.ones_like(f_true)*0.05*f.max() # define the model/function to be fitted. def model(x, f): amp = pymc.Uniform('amp', 0.05, 0.4, value= 0.15) size = pymc.Uniform('size', 0.5, 2.5, value= 1.0) ps = pymc.Normal('ps', 0.13, 40, value=0.15) @pymc.deterministic(plot=False) def gauss(x=x, amp=amp, size=size, ps=ps): e = -1*(np.pi**2*size*x/(3600.*180.))**2/(4.*np.log(2.)) return amp*np.exp(e)+ps y = pymc.Normal('y', mu=gauss, tau=1.0/f_error**2, value=f, observed=True) return locals() MDL = pymc.MCMC(model(x,f)) MDL.sample(1e4) # extract and plot results y_min = MDL.stats()['gauss']['quantiles'][2.5] y_max = MDL.stats()['gauss']['quantiles'][97.5] y_fit = MDL.stats()['gauss']['mean'] plt.plot(x,f_true,'b', marker='None', ls='-', lw=1, label='True') plt.errorbar(x,f,yerr=f_error, color='r', marker='.', ls='None', label='Observed') plt.plot(x,y_fit,'k', marker='+', ls='None', ms=5, mew=2, label='Fit') plt.fill_between(x, y_min, y_max, color='0.5', alpha=0.5) plt.legend() My first question is, am I doing it right? Yes! You need to include a burn-in period, which you know. I like to throw out the first half of my samples. You don't need to do any thinning, but sometimes it will make your post-MCMC work faster to process and smaller to store. The only other thing I advise is to set a random seed, so that your results are "reproducible": np.random.seed(12345) will do the trick. Oh, and if I was really giving too much advice, I'd say import seaborn to make the matplotlib results a little more beautiful. My second question is, how do I add an error in the x-direction, i.e. in the x-position of the observations/data? One way is to include a latent variable for each error. This works in your example, but will not be feasible if you have many more observations. I'll give a little example to get you started down this road: # add noise to observed x values x_obs = pm.rnormal(mu=x, tau=(1e4)**-2) # define the model/function to be fitted. def model(x_obs, f): amp = pm.Uniform('amp', 0.05, 0.4, value= 0.15) size = pm.Uniform('size', 0.5, 2.5, value= 1.0) ps = pm.Normal('ps', 0.13, 40, value=0.15) x_pred = pm.Normal('x', mu=x_obs, tau=(1e4)**-2) # this allows error in x_obs @pm.deterministic(plot=False) def gauss(x=x_pred, amp=amp, size=size, ps=ps): e = -1*(np.pi**2*size*x/(3600.*180.))**2/(4.*np.log(2.)) return amp*np.exp(e)+ps y = pm.Normal('y', mu=gauss, tau=1.0/f_error**2, value=f, observed=True) return locals() MDL = pm.MCMC(model(x_obs, f)) MDL.use_step_method(pm.AdaptiveMetropolis, MDL.x_pred) # use AdaptiveMetropolis to "learn" how to step MDL.sample(200000, 100000, 10) # run chain longer since there are more dimensions It looks like it may be hard to get good answers if you have noise in x and y: Here is a notebook collecting this all up.
https://codedump.io/share/r4bzNVsB0bKP/1/fit-a-non-linear-function-to-dataobservations-with-pymcmcpymc
CC-MAIN-2017-26
refinedweb
736
63.36
Documentation edit Description editmsgcat command are used to localise text in a program. Commands are provided to manipulate a database of translations for strings of text. The commands can be stored in separate files having the suffix, .msg.Instead of label .x -text Filesif you write label .x -text [mc Files] Message Catalog editUse mcload to load translations into the message catalog from files ending in the suffix .msg.The naming convention for .msg files is that the root name shall be the target locale of its contents, e.g. "en_us_funky". msgcat searches the contents first of en_us_funky.msg, then en_us.msg, then en.msg.mcset can be used to add translations to the message catalog. See, for example, Vogel spiral.Alexandru provided this page for general localisation hints: [1 Setting the Locale edit$env(LANG), $env(LC_ALL), or $env(LC_MESSAGES). is used to determine the initial locale. The locale can be explicitly set, e.g.: ::msgcat::mclocale fr Formatting editmc applies format to the translated string, so mc "Directory contains %d files" $nfilesallows a translator to work with the string, "Directory contains %d files".escargo 2003-12-08: What if you want to do some form of parameter substitution in the strings that you might use with msgcat? In some systems I have developed, messages were somewhat macro-like; you might pass a number or a name (of a file, for example) that should be part of the message. Is there anything in the msgcat that does the substitution internally, or do I have to add my own layer on top of it?RS: Easy, for instance with format: msgcat::mcset fr "Directory contains %d files" "Il y a %d fichiers" ... puts [format [mc "Directory contains %d files"] $nfiles]DGP: Even easier: There's a format already built-in to mc: puts [mc "Directory contains %d files" $nfiles]EKB: I moved this example up to the top of the page and combined it with the intro text so it's easier to find.AM Also very useful: the %1$s type format codes - with this you can interchange variables if needed. % mc "this is a %s test for %s" first anything this is a first test for anything % mc {this is a %2$s test for %1$s} first anything this is a anything test for firstNote the {} around the text to prevent interpretation of $ variable substitution Usage edit package require msgcat ;# and done namespace import msgcat::* ;# (or msgcat::mc).Provided you have .msg files containing ::msgcat::mcset de Files Dateien ::msgcat::mcset fr Files FichiersThe following will produce the translation, depending on the current locale: mc Files Example: Basic editRS 2007-01-08: Here's a simple self-contained example for testing: #!/usr/bin/env tclsh package require msgcat msgcat::mcset de yes Ja msgcat::mcset de no Nein msgcat::mcset fr yes Oui msgcat::mcset fr no Non proc localbool value { if {$value} {msgcat::mc yes} else {msgcat::mc no} } puts [localbool 0]/[localbool 1] hat's all. Save that to a file, and run it with different LANG settings: $ /Tcl/msgcat.tcl Nein/Ja $ LANG=fr /Tcl/msgcat.tcl Non/Oui $ LANG=en /Tcl/msgcat.tcl no/yes Example: Switching Languages editcompliments of dgp: (HaO 20156-07-01: the tk (re)load is only necessary for msgcat prior to version 1.6) package require Tk # Show the bg error box in the default language bgerror 123 # Show the bg error box in French language msgcat::mclocale "fr" msgcat::mcload [file join $::tk_library msgs] bgerror 123 # Show the bg error box in British English language msgcat::mclocale "en_gb" msgcat::mcload [file join $::tk_library msgs] bgerror 123 Using Tags Instead of Text editHaO 2012-07-17:Given the code with a localised error message: if {[catch {open $File r} Err]} { puts stderr [mc "File error accessing '%s': %s" $File $Err] }and the German translation (the contents of the de.msg file): msgcat::mcset de "File error accessing '%s': %s" "Zugriffsfehler Datei '%s': %s"I use tags instead of a default translation. The default (English) text is contained in the root translation:Contents of the de.msg file: msgcat::mcset de errFile "Zugriffsfehler Datei '%s': %s"Contents of the ROOT.msg file: msgcat::mcset {} errFile "File error accessing '%s': %s"Example: if {[catch {open $File r} Err]} { puts stderr [mc errFile $File $Err] }Why that ? - If I change the default text, I do not have to change the translation keys - It feels more systematic to me to separate text and code - If a text is the same in english but different in german, I may not make any difference - If I forget a translation, I get only a stupid tag. Nothing for lazy guys... proc ::msgcat::mcunknown {locale args} { return $args }Default mcunknown: % msgcat::mc tag1 p1 p2 tag1Custom mcunknown: % msgcat::mc tag1 p1 p2 tag1 p1 p2 Other Examples edit - simple text editor - HiLo-international - multilingual menu - Tk internationalization - A little stopwatch - Vogel Spiral - Uses mcset to populate the message catalog. Illustrates use of source strings that serve as tags rather than as the default text, using "%" as an ad-hoc prefix that denotes tags. Locale Detection editHaO 2013-05-10:It is relatively hard to debug language guessing, as the developpers depend on computers in any language which is seldomly the case. Thus I ask your help, if you think, the language guessing is not correct.From Windows Vista on, the language system of windows passed from a numerical identifier to IETF language tags.Start wish and type: % msgcat::mclocale de_deOn Windows Vista and later, you should mostly get a language and a country. If you only get the language, please check the following:Verify, if one of the following environment variables are set: 'LC_ALL', 'LC_MESSAGES' or 'LANG'. This might be the fact due to an installed Cygwin: % msgcat::mclocale de % parray env ... LANG=deIn this case start wish without those environment variables set, for example by the following batch file: set LANG= c:\tcl\bin\wish86.exeNow, the language settings are taken from the registry. If you still get bad results, please execute the following commands in a wish and post them with the correct language choice: package require msgcat msgcat::mclocale package require registry registry get {HKEY_CURRENT_USER\Control Panel\Desktop} PreferredUILanguages registry get {HKEY_CURRENT_USER\Control Panel\International} LocaleName registry get {HKEY_CURRENT_USER\Control Panel\International} localeIn the upcoming msgcat 1.5.2, those keys are checked in this order. The first is the IETF language tag, and exists only if language packs are installed. The second is the IETF language tag for default file language. The third is the numeric language ID as used up to Windows XPHere is a result table: Implicit locale for mc files editPer TIP 404.HaO 2012-10-15: This feature is now included in TCL8.6b3 (docs) msgcat::mcflset original translationinstead of msgcat::mcset locale original translationwithin message files which are loaded by msgcat::mcload. Open Issue: Using msgcat with TclOO editTwylite 2013-03-01: msgcat searches for messages in the current namespace, then parent namespaces up to the global namespace. To look up a message in a different (non-parent) namespace you must use namespace eval or an equivalent.TclOO class names are distinct from the unique namespace dynamically-allocated to the class on construction. The class name may or may not correspond to the name of a namespace. To support file-based message catalogs (*.msg) we would need to (i) have the messages in a namespace; and (ii) have a static pre-determined name for the namespace.Twylite 2013-03-12: Working towards a TIP, as requested (see below). Following feedback from DKF I think that it is conceptually reasonable to search for messages in an object's inheritance hierarchy, and to avoid using namespace search at all when dealing with objects. To keep the interface clean there should be new msgcat::oo::* procs to indicate that we are working with a message in the inheritance hierarchy, rather than turning msgcat::mc into a DWIM.The solution below is a minimal embodiment of the interface, and does not yet support message inheritance. Use oo::define $cls mcset ... to define a message on a class, or msgcat::oo::mcset $cls ... to do the same in a .msg file. Use mymc ... in a method declared on a class to retrieve a message defined on that class. mymc should support inheritance and polymorphism in future, but for now you can use msgcat::oo::mc $otherclass ... to explicitly refer to a message in a superclass.For the original solution see the page History. Description of the original solution: The solution I propose is to put messages for a class ::$ns::$cls into the namespace ::msgs::$ns::$cls, and to provide helpers oo::define $cls mcset and ::msgcat::classmc to respectively set and retrieve catalog messages. As an alternative to ::msgcat::classmc a class method mc is also provided. # See for oo::DefWhat proc ::oo::DefWhat {} { uplevel 3 [list namespace which [lindex [info level -2] 1]] } namespace eval ::msgcat::oo {} proc ::msgcat::oo::mcset {cls locale src {dest {}}} { namespace eval $cls [list ::msgcat::mcset $locale $src $dest] } proc ::msgcat::oo::mc {cls src args} { namespace eval $cls [list ::msgcat::mc $src {*}$args] } proc ::oo::define::mcset {args} { tailcall ::msgcat::oo::mcset [::oo::DefWhat] {*}$args } proc oo::Helpers::mymc {args} { tailcall ::msgcat::oo::mc [uplevel 1 { self class }] {*}$args }Using it: package require compat oo::class create ::Alpha oo::define Alpha mcset en FooMsg "this is the foo msg" namespace eval ::Alpha { ::msgcat::mcset fr FooMsg "this is the french msg" } oo::define ::Alpha method testMsg1 {} { mymc FooMsg } oo::define ::Alpha method testMsg2 {} { msgcat::oo::mc [self class] FooMsg } set a [Alpha new] oo::class create ::Beta { superclass ::Alpha mcset en BarMsg "this is the bar msg" method testMsg3 {} { mymc BarMsg } } set b [Beta new] oo::class create ::Gamma { method testMsg4 {} { mymc FooMsg ;# no inheritance yet } method testMsg5 {} { msgcat::oo::mc ::Alpha FooMsg } } set g [Gamma new] ::msgcat::mclocale en $a testMsg1 $a testMsg2 $b testMsg1 $b testMsg2 $b testMsg3 $g testMsg4 $g testMsg5 ::msgcat::mclocale fr $a testMsg1 $a testMsg2 $b testMsg1 $b testMsg2 $b testMsg3 $g testMsg4 $g testMsg5HaO Looks reasonable to me. Could you prepare a TIP?EB: Here is another attempt to use msgcat and TclOO. Using an Alternate msgcat Package editHaO 2012-07-24 PYK 2013-08-22:Both Tk and clock, which may be loaded before any script is able to extend the auto_path, load msgcat. Therefore, to use an alternate msgcat, place it in the default module path.Name the replacement msgcat.tcl to msgcat-1.x.x.tm, where 1.x.x is greater than the version that is being replaced. Typically, these files should be placed in - <tcl install folder>/lib/lib8/8.5 - <programname>.vfs/lib/lib8/8.5 if {1 != [catch {package present msgcat} ver] && ![package vsatisfies $ver 1.6-] } { package forget msgcat namespace delete ::msgcat } package require msgcat 1.6- # if tk is used eventually reload the tk msgcat setup msgcat::mcload [file join $::tk_library msgs] TIP399: Change Locale at Run-time editThere was previously an alternate implementation here, which has been superseded by the following information.HaO 2012-07-17:TIP 399 - This feature is also included in the download files of #3544988 . There is also a tclapp tap-file available as download. - AK has asked how other packages may ask for information about a locale change (see below Dynamic namespace change callback). - TIP 399 was voted yes. DGP voted present with the following comment: What I would prefer is to vote YES for the "turn the whole package over to Harald Oehlmann to do as he pleases". The proposal seems fine, to address the problem posed. What gives me pause is that the TIP seems to demonstrate that the original design of msgcat just isn't any good. At some point we'd be better off not slapping in more bells and whistles and alternatives and just creating a new (version of a?) package that learns the lessons and gets it right this time. Complete solutionI came to the conclusion, that dynamic local change is wanted but the proposed solution only solves parts of the issue. Here is an extract of my message on the core-list: Unfortunately, the solution within the tip is half-baken and I ask for some time to design a better solution and rewrite a tip.I am sorry for that but I am convinced, this is the best way to go. I might be wrong, but at least I will try.A good solution for TIP 399 must automatically reload locale files on a locale change. Sketch of my current view of a solutionThere is a new command to set per caller namespace config data (namespace equal package, as each package should have one namespace and one set of locale files): msgcat::mcpackageconfig ?-namespace namespace? setting ?value?Settings per caller namespace/package: - message file folder (also auto-set by msgcat::mcload) (to be able to load missing locale files on a locale change) - callback function before reload of the message file due to a locale change (change to a jet unloaded locale) - callback function after a locale change - flag, if locale files should be reloaded if needed - the concept of the caller/package namespace already exists within msgcat. This is continued. - the caller namespace may be autodetected or specified - the settings might automatically be cleared if the namespace is removed and the corresponding function may be automatically disabled - IMHO very transparent - currently loaded locales (sum of all mcpreferences, readonly) - Flag, if unneeded locale data is cleared on locale change Locale change callback edit(HaO 2015-07-01: local change callback is implemented in msgcat 1.6 with TIP412 which will be included in tcl 8.6.4)HaO 2012-08-22: AK asked by personal email:Do we have a <<LocaleChanged>> virtual event like we have <<ThemeChanged>>, which is used to inform all widgets when 'mclocale' was switched at runtime ?HaO answered:No, we dont have this currently.As it is a tcl-only package, we do not have the bind command.Thus we could register a command which is called when the locale changes: msgcat::mcconfig -command ?lcmd? - lcmd : list of cmd ?namespace? - cmd: Command to call when locale changes. Specify empty string to unregister. - namespace: the callers module namespace which is only used as a register id to store the command. If not specified, the callers current namespace is used. There is one registered command possible per namespace value. package provide mymodule 1.0 namespace eval mymodule { # Register a locale change callback msgcat::mcconfig -command [list myLocaleChanged] ... # Unregister the locale change callback msgcat::mcconfig -command "" }AK 2012-08-22 by email:> As it is a tcl-only package, we do not have the bind command.True. Nor the 'event generate'.I had thought about auto-detecting a Tk environment to restrict when it broadcasts a change, however your idea with a configurable callback is better, from an architectural point of view.Hm. ... Hadn't thought about multiple callbacks. Guess because I was thinking in terms of events, where I can bind multiple things as I see fit.This restriction to one-per-namespace, and providing it through a list ... I do not like that too much. It is workable, true. Still don't like it. This shoehorning multiple callbacks through a single config option feels wrong.For multiple callbacks I would use dedicated (un)register commands, and tokens. I.e. msgcat::register <cmdprefix>returns a token, which is then the argument to msgcat::unregister <token>to identify the callbacks and remove them individually.See uevent MG 2012-08-22: I use something similar to this in his app: proc setLocale {new_locale} { variable locales; variable current_locale; set split [split $new_locale "_"] set preflist [list] for {set i 0} {$i < [llength $split]} {incr i} { lappend preflist [join [lrange $split 0 end-$i] "_"] } set current_locale "" foreach x $preflist { if { [info exists locales($x)] } { set current_locale $x break; } } if { ![info exists current_locale] || $current_locale eq "" } { set current_locale "en_gb" } # Set our best available ::msgcat::mclocale $current_locale # Update display to make sure we're using it if { $skin ne "" } { ::skin::${skin}::locale } setUpMenu setAppTitle return; };# setLocaleThe $locales array records exactly which locales I've loaded some form of translation for, since msgcat doesn't seem to expose that information. The code makes sure that there actually is a translation for the requested locale, and picks a less specific one if necessary in much the same way msgcat does. It falls back on en_gb as a default. Like msgcat, all the locale names are stored entirely in lowercase (en_gb not en_GB). The code after the last comment calls various procs which alter existing GUI elements to use the new locale, but could easily be replaced with something like proc rchildren {widget} { event generate $widget <<LocaleChanged>> foreach x [winfo children $widget] { rchildren $x } } rchildren .so you could bind to <<LocaleChanged>> for the assorted widgets instead.HaO 2012-08-27: Thank you, Mike, for the contribution. The language change is user level and should still work as you do it, but this is slightly off-topic. Andreas is asking, how non-user packages which store translated messages somehow (like the tcllib tooltip package) may by their action be informed about a locale change. TIP 412 Dynamic Locale Changing for msgcat with On-Demand File Load editHaO 2015-07-01: Vote to tip accepted, changes are merged to the core. TCL 8.6.5+ will probably have it buildin. Discussion on future msgcat on ETCL 2014 conferenceHaO 2014-02-25: I proposed a discussion on the ETCL 2014 conference about the future of msgcat. Please feel free to contribute (also below this text).Here are the slides: [2] History editmsgcat became a built-in package with Tcl version 8.1msgcat 1.3, distributed with Tcl 8.4 also initializes the locale from $env(LC_ALL) or $env(LC_MESSAGES). The 8.3.4 release of the PPC binary is broken in that it lacks msgcat and bgerror implementations. Melissa Schrumpf explains the situation with her customary clarity ... bgerror and msgcat are contained in tcl/library/msgcat/msgcat.tcl. Do this: Copy "Simply Tk (PPC)" to "Simply Tk (PPC).edit" Run ResEdit (or Resourcer, or whathaveyou). Open a "Simply Tk (PPC).edit" in ResEdit. Open the "TEXT" resources. Open resource ID "package require msgcat" This will be right at the top. Next, open tcl/library/msgcat/msgcat.tcl in a text editor. Copy from the beginning of the line: package provide msgcat 1.1.1 through to the end of the file. Return to ResEdit. Delete the line "package require msgcat" and, in its place, paste the code you copied from msgcat.tcl. Close all resources and save. You now have a fixed stand-alone Tk shell. See Also edit - msgcat magic - msgcat and shortcut keys - important for GUI application writers - ampersand magic - further information about shortcut keys - msgcat-Ready Script Utility - msgcat-x - locale - localization - message catalog - Tk and msgcat - frink - uses msgcat when formatting source code, replacing source strings with their translations directly in the source code - unicodize.tcl - A small but useful script by Anton Kovalenko which converts non-ascii characters from current system encoding to \uXXXX sequences. Possibly useful to anyone who works often with tcl message catalogs. - GNU gettext - as of version 0.13, has support for Tcl msgcat and conversion tools from and to PO format.
http://wiki.tcl.tk/1488
CC-MAIN-2016-44
refinedweb
3,247
54.02
State The state object is where we store data in a component that is expected to change over time. When the state object changes, the component re-renders. Props are passed down by parent components, whereas state is created and maintained by the component itself. Class and functional components handle state differently. Functional components use hooks to manage state. The following will address how class components manage state. Creating the state Object The state object is initialized in the component’s constructor(): class Car extends React.Component {constructor(props) {super(props);// The state objectthis.state = {brand: 'Chevrolet',model: 'Malibu',color: 'white',year: 1998,};}render() {return (<div><h1>My First Car</h1></div>);}} Using the state Object Refer to the state object in the render() method: class Car extends React.Component {constructor(props) {super(props);this.state = {brand: 'Chevrolet',model: 'Malibu',color: 'white',year: 1998,};}render() {return (<div><h1>My First Car</h1><p>It is a {this.state.color}{this.state.brand}{this.state.model}made in {this.state.year}. 🚙</p></div>);}} It will appear like this: Caution When React component’s state is updated, it will automatically re-render. This means that the state should never be updated in a render() method because it will cause an infinite loop. Interested in helping build Docs? Read the Contribution Guide or share your feedback form. Edit this page on GitHub
https://www.codecademy.com/resources/docs/react/state?utm_source=ccblog&utm_medium=ccblog&utm_campaign=ccblog&utm_content=cw_react_interview_questions
CC-MAIN-2022-33
refinedweb
229
51.85
instanceof instanceof simple example for instance of operator what exactly it will do when v used CoreJava CoreJava Sir, What is the difference between pass by value and pass by reference. can u give an example PHP Instanceof Operator Type Operators: This is another kind of operator, instanceof, this operator... or not. instanceof can also be used to determine whether an object of a class... that an object is not an instanceof a class, the logical not is used is the method of the PrintWriter class which is an example of overloading... constructor super(). Lets take an example, Suppose you have a "good citizen"... he can obtain an instance of the named class. Example of using Class.forName php instanceof php instanceof What is the use a instanceof function in PHP Type Comparison Operator ;. On the other hand, this example will generate an error, if the expression is written...; Java provides a run-time operator instanceof to compare a class... an object to a specified class type. The instanceof operator is defined Error on example Error on example When I execute this program,it is throwing ArrayIndexOutOfBound exception. How can I solve this. Post your code error error When I deploye the example I have this message cannot Deploy HelloWorld Deployment Error for module: HelloWorld: Error occurred during deployment: Exception while deploying the app [HelloWorld CoreJava Project CoreJava Project Hi Sir, I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account error in sample example error in sample example hi can u please help me XmlBeanFactory class is deprecation in java 6.0 so, pls send advance version class Use XmlBeanFactory(Resource) with an InputStreamResource parameter Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava Diff Bn Marker Interface and instanceOf - Java Interview Questions Diff Bn Marker Interface and instanceOf Hi Friends, Wats d difference bn Marker Interface and instanceOf method. Thanks corejava - Java Beginners corejava - Java Interview Questions CoreJava - Java Beginners compile error compile error Hello All for example public class A { static void main(String args[]) { System.out.println("Hello World... program with Test.java and try to compile with javac test.java an error like Java Compilation error. Hibernate code problem. Struts first example - Hibernate Java Compilation error. Hibernate code problem. Struts first example Java Compilation error. Hibernate code problem. Struts first example The instance of keyword is the example how the instanceOf operator is used. public ...; The keyword instanceOf in java programming language... of the such type of classes. Syntax: Here is the syntax for using an instanceOf error - JDBC error i wrote the program using dbms type 4 driver.it is comipled,i got a errors d:temp> java DBConnect db Connect Example...(String[] args) { System.out.println("db Connect Example."); Connection Error - Struts Error Hi, I downloaded the roseindia first struts example and configured in eclips. It is working fine. But when I add the new action and I create the url for that action then "Struts Problem Report Struts has detected PHP Error Handling Functions the given error handling tutorial for example code. PHP Error Handling Example...Though every programming language offers default error handling methods. You can also write your own error handling functions in PHP. There is a bit java error - Java Beginners be dereferenced If Programme saved in SortFileData also shows some error Please rectify... Student) throws ClassCastException { if (!(Student instanceof ShowData)) throw new ClassCastException("Error"); int ide = ((ShowData) Student).getId(); return Difference between error and exception ???????? Difference between error and exception ? Can we handle a error in java if yes than give an code of an example? Difference between error... yourself or that might be thrown because of an obvious run-time error such as trying error - Hibernate Hibernate error I had run hibernate first example but it an error appeared. Error is java.lang.NullPointerException. Hi Friend, Please explain in detail your problem so that we can discuss and solve it. If you JSP Error 500 JSP Error 500 JSP Error 500 is to generate error status 500 in jsp. The Error 500 occurred when the server encounter an internal error java compilation error - Applet java compilation error hi friends the following is the awt front design program error, give me the replay E:\ramesh>javac...:// Thanks error error while iam compiling iam getting expected error java runtime error - JDBC driver this error is coming at runtime: Exception in thread "main..., give me the suggesion yo solve this problem This kind of error due... that is not supported by the JDK attempting to run it. In the above example java error - Java Beginners . But if I want to run that program the fetches me the following error. For example... uninstalled jdk and NetBeans and reinstalled them, Then too its the same error compilation error - Java Beginners this program it is giving an error as integer number is too large.why? and what... representation for the variable values. For example : Decimal Literal( without any... not in the Hexadecimal or Octal. Here is fraction of Java code example which will help you SQL error - JSP-Servlet with referrence to that column value. For example, the query...(String[] args) { System.out.println("Table Creation Example...){ System.out.println("Error occured while updating!!!"); } con.close Error- Error- Hello, I would like to know about XSD file. I try to print XML file but I am getting error SAXException-- says Content is not allowed in prolog. Please help me Java error stream Java error stream The Java error stream is used to print error that arises during the execution of a program. The execution of program display an output and error error error i have 404 error in my program plz tell me yhe solution about PHP Error handling below example, we create a custom error handler plus also set it for error...PHP Error handling Your application must have an error handling codes. Without it, it looks very unprofessional. PHP have following error handling methods simple session bean .................. Error in simple session bean .................. Hi friends, i am..., exampleHome.class); <br /> example myHelloWorld = home.create(); <br />... more EJB Hello World Example Please visit the following links applet security error - Security my jsp page, the following security error occured. ERROR: Java Plug... to resolve this problem Hi Plugin example JSP Error Page JSP Error Page JSP Error Page is used to specify the custom error page and runtime error occurs with an exception being thrown, the custom PHP Error handling PHP Error handling: PHP provides so many techniques to handle error, if error occurs an error message is send to the browser. Error handling should...: Example: <?php $var=mysql_connect("localhost"," error error error error java.lang.unsupportedclassversionerror:bad major version at offset 6 how to solve this???? Hi, Please check the version of framework used and also the JDK version. This type error also comes when java file Compile error - Java Beginners Compile error I get this error when compiling my program: java:167... to be thrown tc.countLines(inFile); ^ 1 error This is an example of my code: import java.io.*; import java.util.*; import standardserviceregistrybuilder example standardserviceregistrybuilder example I am facing error in creating... class. But there is no code of standardserviceregistrybuilder example. Do you know... the complete code at Hibernate 4 Hello World: Example of Hello World program. Thanks JSF error - JSP-Servlet : jsf h:commandLink example error!!!!!!!!! error!!!!!!!!! st=con.createStatement(); int a=Integer.parseInt(txttrno.getText()); String b=txttname.getText(); String c=txtfrom.getText(); String d=txtto.getText Database Error - Hibernate ;Hi I am sending u a link where u can find lots of example which helps to solve java error - JDBC java error Why am I getting errors in the follwing program? import java.sql.*; public class MysqlConnect{ public static void main(String[] args) { System.out.println("MySQL Connect Example."); Connection conn import org.hibernate.Session error ;Hi! Im using Eclipse. Steps : 1. Downloaded the example code and library from... Example of tutorial Take the jar and code from the zip file. You will have to add loop error - Ajax : Hope error in web application error in web application In your application when i am trying to execute it from the below page <%@ page language="java" import="java.util....]); System.out.println("MySQL Connect Example."); Connection conn = null testing in JSP statements. Here is an example which shows an error testing. Here is the code...;html> <head><title>Error testing Example </title>... Error testing in JSP   Java error code Java error code Java Error code are the set of error that occurs during the compile-time and Run-time. From java error we have given you file upload error - JSP-Servlet of the project. In this particular part i got an error... by multipart/Form-data encrypted form. And this error occurred in the processing... ----------- file upload example Error While Compiling - Java Beginners Error While Compiling Hi All I Am a beginner and i face the following problem while compiling can anyone help me. C:\javatutorial\example>...;. or try to set the path in envirnment variable..ok.. example set path Java compilation error - JSP-Servlet is working.. Please help to solve this problem.. I've tried the example given... to my problem, but having some error as below.. Generated servlet error: C...; ^ Generated servlet error: C:\Program Files\Apache Software Foundation Error page in JSP is accessible in the error page only. Now, here is the example to illustrate the error page in JSP example: The "ErrorPageDemo.jsp" generate...Error page in JSP In this section we will discuss about "Error page error in accessing database - JSP-Servlet error in accessing database hiiii im tanushri im tryng to connect my... error called Got minus one from read call although i hv feeded data to my... void main(String[] args) { System.out.println("MySQL Connect Example Reply to the mail(import files error) Reply to the mail(import files error) Hi Its already there in the bin. If its class path should be set , how can i do dat? Hi, Wait... the steps to download, open the project in Eclipse and then run the example. http Reply to ur mail(Hibernate Error) Reply to ur mail(Hibernate Error) Hi! Im using Eclipse. Steps : 1. Downloaded the example code and library from rose india and extracted the content in a directory. 2. Downloaded file contains the Eclipse project. 3. Started login example response.sendRedirect("invalidLogin.jsp"); //error page } catch (Throwable Java compilation error - Java Beginners Java compilation error Hello, i am getting an error while.... the error is: javac:file not found usage:javac Regards, jyoti prakash .... For example if java is installed at c:\Program Files\Java\jdk1.6.0_01 PHP Trigger Error . Example of PHP Trigger Error Handling: <?php $div=0; if($div==0...PHP Trigger Error PHP trigger_error generates an error, warning, notice message. Basic format of the trigger_error is as follows: boolean trigger_error XML Error Checking and Locating XML Error Checking and Locating In this section, you will learn how to check and locate an error in the XML document and error position. Description of program: The following Error in laodin and saving the image . - Swing AWT Error in laodin and saving the image . I am a student who had... toBufferedImage(Image image) { if (image instanceof BufferedImage) {return...) { if (image instanceof BufferedImage) {return ((BufferedImage)image Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/95069
CC-MAIN-2016-07
refinedweb
1,917
50.53
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. how to achieve email validation in openerp 7.0 and what is the use of widget="email" In .py file write this method.......... import re def ValidateEmail(self, cr, uid, ids, email): if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None: return True else: raise osv.except_osv('Invalid Email', 'Please enter a valid email address') In view.xml file write this line <field name="email" on_change="ValidateEmail
https://www.odoo.com/forum/help-1/question/email-validation-in-openerp-7-0-27532
CC-MAIN-2017-09
refinedweb
105
71
What is IO class ? You know that Java provides so many predefined classes to make your code easily. IO class is another special class that helps you to create files and modify them. There are special sub classes within IO class to do these things. In this post I want to talk about following classes. Because they are the main classes that you want to learn for OCPJP 1Z0-851 examination. - File - FileWriter - BufferedWriter - FileReader - BufferedReader - PrintWriter - Console In OCPJP 1Z0-851 examination, we have to consider only about above things. In additionally I have noted down few things over the syllabus. Keep these thing in your mind and try to do examples to improve your knowledge with them. File class File class in an abstract representation of file and directory path names. This is not used to write or read data. It gives you information about files. This class is used for making new empty files, searching files, deleting files, making directories and working with paths. Try this example. This is a sample example for checking a file in a known directory. - For example I have created a folder in C directory and created a txt file within it called "myFile.txt". You can create either .txt, .php, .html or whatever file you like. In this demonstration I use .txt file. - Then try this code and check your result. If you create that file correctly, you will be able to get "Your file is there" message. import java.io.*; public class FileTest { public static void main(String args[]){ File f = new File("C:\\Test\\myFile.txt"); if(f.exists()){ System.out.println("Your file is there"); } else{ System.out.println("Your file is not there"); } } } - In this example I have imported java.io class. - It is necessary to add it. Because File class is a sub class of IO class. So you have import IO class manually. - Then in line four, I have created File object, its reference variable is "f". - In this line you can see I have used "\\" to set path instead of using "\". This is necessary in windows. - Next line I checked existence, using exist( ) function. - This is very simple example shows you the importance of File class. How to create a file ? Now we know about file class. Before we go to other things I thought to show you how to create files in Java. There are many ways to do it. Using createNewFile( ) function import java.io.*; public class CreateFile { public static void main(String args[]){ try{ File f = new File("C:\\Test\\file1.txt"); System.out.println(f.exists()); f.createNewFile(); System.out.println(f.exists()); } catch(Exception e){ System.out.println("There is an error."); } } } - In this example also, first I have created file object and gave the path of this file. - Then I have used createNewFile( ) function to create a new file in that given destination. - At the very first time you will be able to see the output as false and then true. If you run it again it will give true and true as a output. - You can understand what is the reason for that. Very first time there is no file in that destination. But second time there is a file in that destination. This createNewFile( ) method is Boolean type method. Using this method you cannot create files in same file name. In above example it creates file1.txt file, if it does not already exist. You can run it again and again, but it will not create more file1.txt files, just only one. Using formatter( ) method import java.util.*; public class CreateFile2 { public static void main(String args[]){ try{ new Formatter("C:\\Test\\FormatterFile.txt"); System.out.println("You have created a file"); } catch(Exception e){ System.out.println("There is an error."); } } } - This is another method of creating files. - In this method we use Formatter( ) class to create files. - Special thing is there, you can see I have not imported IO package, instead of that I have imported util package. Because Formatter class belongs to java.util package. - This method is not thread safe for multithreaded access. You need not to worry about this method in your examination and pay your attention for the first method to create files. In later sessions we discuss about Threads. Using FileWriter( ) method import java.io.*; public class CreateFile3 { public static void main(String args[]){ try{ File f = new File("C:\\Test\\Create File 3.txt"); new FileWriter(f).close(); }catch(Exception e){ System.out.println("There is an error"); } } } - FileWriter( ) method is generally used for writing characters. - But this method also create files. - In this program I have used close( ) method. This is used to prevent resource leak. You can run it without using close( ) method. But It is good practice to use close( ) to prevent resource leak. You may learn more about close( ) in later. How to write in a file ? Now we know how to create files. Then lets try to write something on the file that we have created. There are also few methods to do it. Using write( ) method import java.io.*; public class WriteFile { public static void main(String args[]){ try{ File f = new File("C:\\Test\\write.txt"); FileWriter fw = new FileWriter(f); fw.write("This is a test"); fw.close(); }catch(Exception e){ System.out.println("There is an error"); } } } - This is also like previous examples. - write( ) method allows you to write characters and string in to your file. - close ( ) method is used to prevent resource leak and stop writing to the file. If you try to write something after close( ) method, it will not printed to the file( write.txt ) and there can be an run-time exception. In this program you will be able to see a message "There is an error". Using format( ) method import java.util.*; public class WriteFile2 { public static void main(String args[]){ try{ Formatter f = new Formatter("C:\\Test\\WriteFile2.txt"); f.format("%s%s", "Ravi ", "easyjavase@live.com "); f.close(); }catch(Exception e){ System.out.println("There is an error"); } } } - You know how to create file using Formatter( ) class. - Then what I did is, using format( ) method to write something to a file you have created. How to read a file ? Already you know how to create files and how to write in to the files. Then we have to discuss how to read a file. Using FileReader( ) method - This is a very simple method that can be used to read a file. - Following example shows the way, that how can you do it. - As a Java programmer we should have to familiar with other operating systems also, specially Ubuntu. - In this program I code this program in Ubuntu OS. So I have to use path in different way. In Ubuntu it is easy to fine the path. Just you have to drag and drop the file to the ubuntu terminal. Then you will able to see the path and then you can copy it and paste it in your program. - If you are using Windows You can use the path as we used before (C:\\Test\\ReadFile.txt). import java.io.*; public class FileReaderTest { public static void main(String args[]){ try{ /*this program is created in ubuntu. If you are with windows, you have to change the file path as above programs.*/ File f = new File("/home/ravi/workspaceUbuntu/IOTest/src/Reader.txt"); FileReader fr = new FileReader(f); char a[] = new char[50]; fr.read(a); for(char c: a){ System.out.print(c); } fr.close(); }catch(Exception e){ System.out.println("There is an error"); } } } I think post was too long, I hadn't any idea about termination point. In next post I am going to talk about BufferWriter, BufferReader, PrintWriter and differences between FileWriter, FileReader and so on. Hope you enjoy...!!! IO Class Reviewed by Ravi Yasas on 9:49 PM Rating:
https://www.javafoundation.xyz/2014/03/io-class.html
CC-MAIN-2021-43
refinedweb
1,322
78.04